3

I'm trying to take an image from a video and crop out a random 64 x 64 x 3 chunk of it (64 width, 64 height, 3 for the color channels).

Here's what I have so far:

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()

I want to take a small portion of the frame (64 x 64 x 3) and save it as a .jpg file, so I'm having trouble with the last commented part. Any suggestions for how to go about this?

Thanks!

anon_swe
  • 8,791
  • 24
  • 85
  • 145
  • 2
    Are you looking for how to crop random portion of image? If so, http://stackoverflow.com/questions/15589517/how-to-crop-an-image-in-opencv-using-python – smttsp Feb 16 '17 at 02:35

2 Answers2

13

To get a random crop of your image, you should just sample a location x and y and then select that portion of the matrix as @Max explained:

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)

ted
  • 13,596
  • 9
  • 65
  • 107
4

For given c, r, width, height

img = img[r:r+height,c:c+width] will get a chunk from column c of desired width and from row r of desired height.

enter image description here

Max Walczak
  • 433
  • 2
  • 12
  • 1
    it should be `img[r:r+height, c:c+width]` – deadcode Oct 09 '19 at 15:57
  • True! I edited it. Wow I'm surprised you revisited a 2 year old post :D – Max Walczak Oct 10 '19 at 14:57
  • I believe this is not a complete answer. Suppose the randomly generated c and r are generated near the bottom right corner, in this case, the desired chunk will be small or gives an error. – ziMtyth Apr 16 '20 at 05:20
  • @ziMtyth obviously in that case the range of r and c has to be from 0 to image_height-height and image_width-width respectively so that the overflow can't occur. – Max Walczak Apr 16 '20 at 21:06