Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a video of cropped frames in Python OpenCV

In my program I am reading an original video, then cropping every frame and finally I need to make a video of all the cropped frames.
The frames are cropped with the size I define (top, bottom, left and right), but it doesn't save it to a video.
What I'm trying is the following:

input_video = cv2.VideoCapture(videosPath+"/"+video)
while True:
    ret, frame = input_video.read()
        if not ret:
            break
    for (top, right, bottom, left) in *****
        crop_img = frame[top:bottom, left:right]
        fourcc = cv2.VideoWriter_fourcc(*'XVID')
        output_movie = cv2.VideoWriter('videoPrueba.avi', fourcc, 30, (450, 360))
        output_movie.write(crop_img)

Thanks !

like image 390
Alba Egea Cadiz Avatar asked Sep 06 '25 02:09

Alba Egea Cadiz


1 Answers

The recommended stages are: read, crop, write each iteration.

Instead of reading all frames, then cropping all frames then writing all frames, I suggest the following solution:

  • Open both input and output video files above the while loop.
  • Inside the loop, each iteration: Read a frame, crop it and write the result to the output video.
  • At the end, use output_movie.release() for closing video writer.

Here is a sample code:

import cv2

top, right, bottom, left = 10, 450+10, 360+10, 10  # Sample values.


input_video = cv2.VideoCapture('Sample_Vid.mp4')

fourcc = cv2.VideoWriter_fourcc(*'XVID')
output_movie = cv2.VideoWriter('videoPrueba.avi', fourcc, 30, (450, 360))

while True:
    ret, frame = input_video.read()

    if not ret:
        break

    # Following crop assumes the video is colored, 
    # in case it's Grayscale, you may use: crop_img = frame[top:bottom, left:right]  
    crop_img = frame[top:bottom, left:right, :]

    output_movie.write(crop_img)


# Closes the video writer.
output_movie.release()
like image 123
Rotem Avatar answered Sep 07 '25 19:09

Rotem