-1

i want to crop each of the frames of this video and save all the cropped images to use them as input for a focus stacking software but my approach:

cap = cv2.VideoCapture(r"C:\Users\HP\Downloads\VID_20221128_112556.mp4")
ret, frames = cap.read()
count=0
for img in frames:
    stops.append(img)
    cv2.imwrite("../stack/croppedframe%d.jpg" % count,img[500:1300,100:1000])
    print(count)
    count += 1

Throws this error:

error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp:801: error: (-215:Assertion failed) !_img.empty() in function 'cv::imwrite'

what can i do?

  • 2
    I am not an expert on this, but I don't think you can read the whole video at once. You need to read it one frame at a time. So the cap.read likely needs to be inside your loop. Search Google for proper syntax and code. See for example https://stackoverflow.com/questions/18954889/how-to-process-images-of-a-video-frame-by-frame-in-video-streaming-using-openc – fmw42 Dec 01 '22 at 22:33

1 Answers1

3

If you take the frames variable with for loop it will give you the image on the y-axis.if you use while loop and read the next frame, the code will work. You can try the example below.

cap = cv2.VideoCapture(r"C:\Users\HP\Downloads\VID_20221128_112556.mp4")
ret, frame = cap.read()
count=0
while(ret):
    stops.append(frame)
    cv2.imwrite("../stack/croppedframe%d.jpg" % count,frame[500:1300,100:1000])
    print(count)
    count += 1
    ret, frame = cap.read()
Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
Enis
  • 166
  • 1
  • 7