一、打开摄像头
import cv2import numpy as npdef video_demo():capture = cv2.VideoCapture(0)#0为电脑内置摄像头while(True):ret, frame = capture.read()#摄像头读取,ret为是否成功打开摄像头,true,false。 frame为视频的每一帧图像frame = cv2.flip(frame, 1)#摄像头是和人对立的,将图像左右调换回来正常显示。cv2.imshow(\"video\", frame)c = cv2.waitKey(50)if c == 27:breakvideo_demo()cv2.destroyAllWindows()
二、打开摄像头并截图
import cv2cap = cv2.VideoCapture(0, cv2.CAP_DSHOW) # 打开摄像头while (1):# get a frameret, frame = cap.read()frame = cv2.flip(frame, 1) # 摄像头是和人对立的,将图像左右调换回来正常显示# show a framecv2.imshow(\"capture\", frame) # 生成摄像头窗口if cv2.waitKey(1) & 0xFF == ord(\'q\'): # 如果按下q 就截图保存并退出cv2.imwrite(\"test.png\", frame) # 保存路径breakcap.release()cv2.destroyAllWindows()
三、打开摄像头并实时自动不断截屏
def video_demo():print(\'开始\')cap = cv2.VideoCapture(0, cv2.CAP_DSHOW) # 电脑自身摄像头i = 0#定时装置初始值photoname = 1#文件名序号初始值while True:i = i + 1reg, frame = cap.read()frame = cv2.flip(frame, 1) # 图片左右调换cv2.imshow(\'window\', frame)if i == 50: # 定时装置,定时截屏,可以修改。filename = str(photoname) + \'.png\' # filename为图像名字,将photoname作为编号命名保存的截图cv2.imwrite(\'C:/Users/Administrator/Desktop/m\' + \'\\\\\' + filename, frame) # 截图 前面为放在桌面的路径 frame为此时的图像print(filename + \'保存成功\') # 打印保存成功i = 0 # 清零photoname = photoname + 1if photoname >= 20: # 最多截图20张 然后退出(如果调用photoname = 1 不用break为不断覆盖图片)# photoname = 1breakif cv2.waitKey(1) & 0xff == ord(\'q\'):break# 释放资源cap.release()video_demo()cv2.destroyAllWindows()