OpenCV:尝试获取图像的随机部分

bcl*_*man 3 python opencv numpy

我正在尝试从视频中获取图像并裁剪出随机的 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()
Run Code Online (Sandbox Code Playgroud)

我想取帧的一小部分 (64 x 64 x 3) 并将其另存为 .jpg 文件,所以我在最后评论的部分遇到了问题。关于如何解决这个问题的任何建议?

谢谢!

ted*_*ted 11

要随机裁剪图像,您应该只对位置 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)

Run Code Online (Sandbox Code Playgroud)