python - Python cv2 VideoWriter 文件损坏
问题描述
我正在按照本教程进行操作,并尝试将视频保存为 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
需要与frameSize
给定的VideoWriter
, (640,480) 相同。frame
正在调整大小以使其宽度为 500,而预计videoWriter
宽度为 640。
但是,将调整大小更改为frame = imutils.resize(frame, width=640)
可能也不起作用。 imutils.resize
将返回与原始图像具有相同纵横比的图像,因此高度不一定是 480。我建议将该行替换为opencv.resize
:
frame = cv2.resize(frame, (640,480))
推荐阅读
- python - 使用 for 循环创建阈值评估
- visual-studio-2012 - 如何在 VB 2012 中为组合框添加 unqiue 索引(不按顺序)
- windows-subsystem-for-linux - 使用 Linux for Windows 子系统对 ssh“连接超时”进行故障排除
- typescript - 观察模式下的 Fork TS Checker Notifier 不通知
- python - 如何从python中的对象中提取数据
- python - Jenkins for Python Unittests with sidecar MongoDB
- macos - 通过 install_name_tool 更改库搜索路径
- aws-lambda - 如何在 codebuild buildspec 和 codedeploy 中使用多个 sam 模板进行 lambda 函数部署
- amazon-web-services - 无法选择 CodePipeline 作为源
- csv - Logstash 查找弹性搜索索引