OpenCV:试图获得随机的图像部分

问题描述 投票:0回答:2

我正在尝试从视频中拍摄一张图像并裁剪出一个随机的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文件,因此我在上一个评论部分遇到问题。有关如何解决此问题的任何建议?

谢谢!

python opencv numpy
2个回答
2
投票

对于给定的c,r,宽度,高度

img = img[c:c+width,r:r+height]将从所需宽度的列c和所需高度的行r获得一个块。 enter image description here


2
投票

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

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.