赞
踩
- # opencv
- self.cap = cv2.VideoCapture(0)
- # 图像捕获
- self.isExternalCameraUsed = False
- # # 打开摄像头按钮
- self.openCameraButton.toggled.connect(self.startWebcam)
- self.openCameraButton.setCheckable(True)
-
- # 定时器
- self.timer = QTimer(self)
- self.timer.timeout.connect(self.updateFrame)
编写startWebcam函数,打开摄像头
- def startWebcam(self, status):
- if status:
- print('打开摄像头了')
-
- print(self.cap.isOpened())
- self.timer.start(5)
- if not self.cap.isOpened():
- camID = 1 if self.isExternalCameraUsed else 0 + cv2.CAP_DSHOW
- self.cap.open(camID)
- self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 680)
- self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 540)
- ret, frame = self.cap.read() # 获取摄像头调用结果
-
- if not ret:
- # logging.error('无法调用电脑摄像头{}'.format(camID))
- # self.logQueue.put('Error:初始化摄像头失败')
- print('无法调用电脑摄像头{}'.format(camID))
- print('Error:初始化摄像头失败')
- self.cap.release()
- self.openCameraButton.setIcon(QIcon('./icons/error.png'))
- self.openCameraButton.setChecked(False)
- else:
- self.timer.start(5)
- # self.enableFaceDetectButton.setEnabled(True)
- self.openCameraButton.setIcon(QIcon('./icons/success.png'))
- self.openCameraButton.setText('关闭摄像头')
然后定时器刷新updateframe函数更新frame
- def updateFrame(self):
- ret, frame = self.cap.read()
- # frame = cv2.flip(frame, 1) # 水平翻转图片
- print('调用frame函数')
- if ret:
- # self.displayImage(frame) # ?两次输出?
-
- if self.isFaceDetectEnabled: # 人脸检测
- # detected_frame = self.detectFace(frame)
- # self.displayImage(detected_frame)
- self.displayImage(frame)
- else:
- self.displayImage(frame)
然后图片展示的摄像展示区域更新为视频流
- # 显示图像
- def displayImage(self, img):
- # BGR -> RGB
- img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
- # default:The image is stored using 8-bit indexes into a colormap, for example:a gray image
- # img = cv2.flip(img, 1)
- qformat = QImage.Format_Indexed8
-
- if len(img.shape) == 3: # rows[0], cols[1], channels[2]
- if img.shape[2] == 4:
- # The image is stored using a 32-bit byte-ordered RGBA format (8-8-8-8)
- # A: alpha channel不透明度参数。如果一个像素的alpha通道数值为0%,那它就是完全透明的
- qformat = QImage.Format_RGBA8888
- else:
- qformat = QImage.Format_RGB888
最后展示效果:
点击关闭按钮后:
就又恢复原样了
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。