opencv 视频编写器没有编写任何视频,只是一个空的.mp4文件,其余部分工作正常,有什么问题吗?

3npbholx  于 2022-12-04  发布在  其他
关注(0)|答案(1)|浏览(175)
import cv2
import os

cam = cv2.VideoCapture(r"C:/Users/User/Desktop/aayfryxljh.mp4")

detector= cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
result = cv2.VideoWriter('C:/Users/User/Desktop/new.mp4',cv2.VideoWriter_fourcc(*'mp4v'),30,(112,112))

while (True):

    # reading from frame
    ret, frame = cam.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = detector.detectMultiScale(gray, 1.3, 5)
    size=(frame.shape[1],frame.shape[0])
    c = cv2.waitKey(1)
    # if video is still left continue creating images
    for (x, y, w, h) in faces:
        cropped = frame[y: y + h, x: x + w]
        cv2.imshow('frame', cropped)
        result.write(cropped)
# Release all space and windows once donecam.release()
result.release()

应该保存裁剪的人脸视频。我想将其保存为.mp4格式。它只是显示了一个空的.mp4文件,我无法理解这个问题。代码执行时没有任何错误

4nkexdtk

4nkexdtk1#

正如我在注解中提到的,while循环永远不会结束,因此result.release()永远不会被调用。看起来代码需要一种方法来结束while循环。也许:

while (True):

    # reading from frame
    ret, frame = cam.read()

    ### ADDED CODE:
    if ret == False:
        break

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = detector.detectMultiScale(gray, 1.3, 5)
    size=(frame.shape[1],frame.shape[0])
    
    ### CHANGED CODE
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

    # if video is still left continue creating images
    for (x, y, w, h) in faces:
        cropped = frame[y: y + h, x: x + w]
        cv2.imshow('frame', cropped)
        result.write(cropped)

# Release all space and windows once donecam.release()

### ADDED CODE
cam.release()
result.release()

### ADDED CODE
cv2.destroyAllWindows()

请参阅以下位置的示例:https://opencv24-python-tutorials.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html#saving-a-video

相关问题