这篇文章将为大家详细讲解有关opencv如何实现调用摄像头并显示,读取视频文件并显示,保存视频等操作,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
调用摄像头,并显示视频:
import numpy as npimport cv2 as cv# cap = cv.VideoCapture(-1)# cap = cv.VideoCapture(1)cap = cv.VideoCapture(0) # 传入一个设备索引,代表不同的摄像头,或者传入一个视频文件名# cap = cv.VideoCapture('testVideo.mp4')if not cap.isOpened():print("Cannot open camera")exit()width = cap.get(cv.CAP_PROP_FRAME_WIDTH)height = cap.get(cv.CAP_PROP_FRAME_HEIGHT)print('宽度和高度分别是:', width, height) # 宽度和高度分别是: 640.0 480.0ret = cap.set(cv.CAP_PROP_FRAME_WIDTH,320) # 设定宽度ret = cap.set(cv.CAP_PROP_FRAME_HEIGHT,240) # 设定高度while True:# Capture frame-by-frameret, frame = cap.read() # 返回True或者False,如果读取正确是True,可以用False来判断是否到达视频的末尾 # if frame is read correctly ret is Trueif not ret:print("Can't receive frame (stream end?). Exiting ...")break# Our operations on the frame come heregray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)# Display the resulting framecv.imshow('LinMaZi-frame-LinZuQuan', gray) # 设定显示窗口标题文字if cv.waitKey(1) == ord('q'): # 判断用户是否输入q键break# When everything done, release the capturecap.release() # 释放资源cv.destroyAllWindows()
读取视频文件并显示:
import numpy as npimport cv2 as cv cap = cv.VideoCapture('毕业晚会.MP4')# cap = cv.VideoCapture(0)while cap.isOpened():ret, frame = cap.read()# if frame is read correctly ret is Trueif not ret:print("Can't receive frame (stream end?). Exiting ...")breakgray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)cv.imshow('frame', gray)if cv.waitKey(25) == ord('q'): # 选择合适的刷新时间间隔,25毫秒还不错breakcap.release()cv.destroyAllWindows()
调用摄像头并显示,保存为视频文件:
import numpy as npimport cv2 as cvimport time cap = cv.VideoCapture(0)# Define the codec and create VideoWriter objectfourcc = cv.VideoWriter_fourcc(*'XVID') # 两者等效# fourcc = cv.VideoWriter_fourcc('X','V','I','D') # 两者等效saveTime = time.strftime("%Yy-%mm-%dd@%Hh%Mm%Ss", time.localtime())out = cv.VideoWriter('output_' + saveTime + '.mp4', fourcc, 20.0, (640, 480)) # 参数说明 output file name, FourCC code, frames per second (fps), frame sizewhile cap.isOpened():ret, frame = cap.read()if not ret:print("Can't receive frame (stream end?). Exiting ...")break# frame = cv.flip(frame, 1) # 左右横向翻转frame = cv.flip(frame, 0) # 上下纵向翻转# write the flipped frameout.write(frame)cv.imshow('LinMaZi-frame-LinZuQuan', frame)if cv.waitKey(1) == ord('q'):break# Release everything if job is finishedcap.release()out.release()cv.destroyAllWindows()
关于“opencv如何实现调用摄像头并显示,读取视频文件并显示,保存视频等操作”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。