python - Python cv2 VideoWriter文件损坏

标签 python opencv cv2

我正在按照本教程进行操作,并尝试将视频保存到avi文件,但是每次尝试该文件都已损坏。我可以使用cv2.imwrite()单独保存框架,但是将各个框架缝合在一起是一项繁重的工作,并且会滞后整个程序。这是我的代码:

from imutils.video import VideoStream
import imutils
import time
import cv2

MINIMUM_AREA = 500

# For Video Recording Purposes
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('vibralert_test001.avi', fourcc, 20, (640, 480))

vs = VideoStream(src=0).start()

print("Setting up feed.")
time.sleep(2)
print("Live")

firstFrame = None

while True:
    frame = vs.read()
    text = "No Movement Detected"

    frame = imutils.resize(frame, width=500)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (21, 21), 0)

    if firstFrame is None:
        firstFrame = gray
        continue

    delta = cv2.absdiff(firstFrame, gray)
    thresh = cv2.threshold(delta, 25, 255, cv2.THRESH_BINARY)[1]

    thresh = cv2.dilate(thresh, None, iterations=2)
    cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
                            cv2.CHAIN_APPROX_SIMPLE)
    cnts = imutils.grab_contours(cnts)

    for c in cnts:
        if cv2.contourArea(c) < MINIMUM_AREA:
            continue

        (x, y, w, h) = cv2.boundingRect(c)
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        text = "Movement Detected"

    cv2.putText(frame, "Room Status: {}".format(text), (10, 20),
                cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)

    cv2.imshow("VibrAlert v0.1", frame)
    out.write(frame)

    key = cv2.waitKey(1) & 0xFF

    if key == 27:
        break

vs.stop()
out.release()
cv2.destroyAllWindows()

print('End Feed')

最佳答案

frame图像的大小必须与提供给frameSizeVideoWriter相同(640,480)。 frame的大小已调整为宽度为500,而videoWriter的宽度为640。

但是,将大小调整为frame = imutils.resize(frame, width=640)可能也不起作用。 imutils.resize将返回与原始图像具有相同长宽比的图像,因此高度不必为480。我建议将该行替换为opencv.resize:

frame = cv2.resize(frame, (640,480))

关于python - Python cv2 VideoWriter文件损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53695143/

相关文章:

opencv - ubuntu 中 cv2 的安装问题

python - 在 Python 中使用 OpenCV 旋转图像时指定背景颜色

python - keras模型加载错误

python - 我如何告诉类方法等待,直到捕获到来自 QDialog 类方法的信号?

python - GStreamer-关键 ** : gst_element_make_from_uri: assertion 'gst_uri_is_valid (uri)' failed

python-3.x - 如何使用 cv2.waitKey() 等待两个不同的键

Python 引用资料

python - 如何通过标识整数转换数据帧列的每个值

opencv - 多 View 几何

xml - OpenCV XML分类器