python利用opencv实现保存、播放视频?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
1.首先创建一个VideoCapture对象,它的参数包含两种:
3.释放捕捉物。
import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
if not cap.isOpened():
print("Cannot open camera")
exit()
while True:
# Capture frame-by-frame
ret, frame = cap.read()
# if frame is read correctly ret is True
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
# Our operations on the frame come here
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
# Display the resulting frame
cv.imshow('frame', gray)
if cv.waitKey(1) == ord('q'):
break
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()
其他:
cap.read()
返回布尔值,如果frame读取正确,为True,可以通过这个值判断视频是否已经结束。cap.isOpened()
来检查其是否被初始化,如果为True那是最好,如果不是,可以使用cap.open()
来尝试打开它。cap.get(propId)
的方式获取视频的一些属性,如帧的宽度,帧的高度,帧速等。propId是0-18的数字,每个数字代表一个属性,对应关系见底部附录。cap.set(3,320), cap.set(4,240)
。从文件中播放视频
代码和从相机中捕获视频基本相同,不同之处在于传入VideoCapture的参数,此时传入视频文件的名称。
在显示每一帧的时候,可以使用cv2.waitKey()
设置适当的时间,如果值很小,视频将会很快。正常情况下,25ms就ok。
import numpy as np
import cv2
cap = cv2.VideoCapture('vtest.avi')
while(cap.isOpened()):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
保存视频
1.创建一个VideoWriter 对象,指定如下参数:
2.FourCC code传递有两种方式:
3.FourCC是一个用于指定视频编解码器的4字节代码。
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)
# write the flipped frame
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
看完上述内容,你们掌握python利用opencv实现保存、播放视频的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。