crop frames of a video using opencv

Question:

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:UsersHPDownloadsVID_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:aopencv-pythonopencv-pythonopencvmodulesimgcodecssrcloadsave.cpp:801: error: (-215:Assertion failed) !_img.empty() in function 'cv::imwrite'

what can i do?

Answers:

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:UsersHPDownloadsVID_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()
Answered By: Enis