OpenCV:如何随机获取图像的一部分

3

我正在尝试从视频中获取一张图像,并裁剪出一个随机的 64 x 64 x 3 的区域(64 宽,64 高,3 个颜色通道)。

以下是我目前的代码:

def process_video(video_name):
    # load video using cv2
    video_cap = cv2.VideoCapture(video_name)
    if video_cap.isOpened():
        ret, frame = video_cap.read()
    else:
        ret = False
    # while there's another frame
    i = 0
    while ret:
        ret, frame = video_cap.read()
        if i % 10 == 0:
            # save several images from frame to local directory
        i += 1
    video_cap.release()

我想从帧中取出一个小部分(64 x 64 x 3)并将其保存为 .jpg 文件,所以我在最后的注释部分遇到了麻烦。有什么建议可以解决这个问题吗?

谢谢!


2
你正在寻找如何裁剪图像的随机部分吗?如果是,请访问https://dev59.com/XGUp5IYBdhLWcg3wAj3y - smttsp
2个回答

13

要获取图像的随机裁剪,您只需对位置x和y进行采样,然后选择矩阵的那一部分,就像@Max所解释的那样:

import numpy as np

def get_random_crop(image, crop_height, crop_width):

    max_x = image.shape[1] - crop_width
    max_y = image.shape[0] - crop_height

    x = np.random.randint(0, max_x)
    y = np.random.randint(0, max_y)

    crop = image[y: y + crop_height, x: x + crop_width]

    return crop



example_image = np.random.randint(0, 256, (1024, 1024, 3))
random_crop = get_random_crop(example_image, 64, 64)


4

对于给定的c,r,width和height

img = img[r:r+height,c:c+width]将从所需高度的第r行和所需宽度的第c列获取一块图像。

enter image description here


1
它应该是 img[r:r+height, c:c+width] - deadcode
真的!我编辑了它。哇,我很惊讶你重新访问了一个两年前的帖子:D - Max Walczak
我认为这不是一个完整的答案。假设随机生成的c和r接近右下角,在这种情况下,所需的块将很小或会出现错误。 - ziMtyth
@ziMtyth 显然,在这种情况下,r和c的范围必须分别从0到image_height-height和image_width-width,以防止溢出发生。 - Max Walczak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接