当前位置:   article > 正文

pyQT5摄像头打开

pyQT5摄像头打开
  1. # opencv
  2. self.cap = cv2.VideoCapture(0)
  3. # 图像捕获
  4. self.isExternalCameraUsed = False
  5. # # 打开摄像头按钮
  6. self.openCameraButton.toggled.connect(self.startWebcam)
  7. self.openCameraButton.setCheckable(True)
  8. # 定时器
  9. self.timer = QTimer(self)
  10. self.timer.timeout.connect(self.updateFrame)

编写startWebcam函数,打开摄像头

  1. def startWebcam(self, status):
  2. if status:
  3. print('打开摄像头了')
  4. print(self.cap.isOpened())
  5. self.timer.start(5)
  6. if not self.cap.isOpened():
  7. camID = 1 if self.isExternalCameraUsed else 0 + cv2.CAP_DSHOW
  8. self.cap.open(camID)
  9. self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 680)
  10. self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 540)
  11. ret, frame = self.cap.read() # 获取摄像头调用结果
  12. if not ret:
  13. # logging.error('无法调用电脑摄像头{}'.format(camID))
  14. # self.logQueue.put('Error:初始化摄像头失败')
  15. print('无法调用电脑摄像头{}'.format(camID))
  16. print('Error:初始化摄像头失败')
  17. self.cap.release()
  18. self.openCameraButton.setIcon(QIcon('./icons/error.png'))
  19. self.openCameraButton.setChecked(False)
  20. else:
  21. self.timer.start(5)
  22. # self.enableFaceDetectButton.setEnabled(True)
  23. self.openCameraButton.setIcon(QIcon('./icons/success.png'))
  24. self.openCameraButton.setText('关闭摄像头')

然后定时器刷新updateframe函数更新frame

  1. def updateFrame(self):
  2. ret, frame = self.cap.read()
  3. # frame = cv2.flip(frame, 1) # 水平翻转图片
  4. print('调用frame函数')
  5. if ret:
  6. # self.displayImage(frame) # ?两次输出?
  7. if self.isFaceDetectEnabled: # 人脸检测
  8. # detected_frame = self.detectFace(frame)
  9. # self.displayImage(detected_frame)
  10. self.displayImage(frame)
  11. else:
  12. self.displayImage(frame)

然后图片展示的摄像展示区域更新为视频流

  1. # 显示图像
  2. def displayImage(self, img):
  3. # BGR -> RGB
  4. img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  5. # default:The image is stored using 8-bit indexes into a colormap, for example:a gray image
  6. # img = cv2.flip(img, 1)
  7. qformat = QImage.Format_Indexed8
  8. if len(img.shape) == 3: # rows[0], cols[1], channels[2]
  9. if img.shape[2] == 4:
  10. # The image is stored using a 32-bit byte-ordered RGBA format (8-8-8-8)
  11. # A: alpha channel不透明度参数。如果一个像素的alpha通道数值为0%,那它就是完全透明的
  12. qformat = QImage.Format_RGBA8888
  13. else:
  14. qformat = QImage.Format_RGB888

最后展示效果:

点击关闭按钮后:

就又恢复原样了

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/532760
推荐阅读
相关标签
  

闽ICP备14008679号