Call the external camera in C ++, and can save photos and record video

In this section we use pythonQT experiment.

First python 3.5 environment, your own Baidu.

Installation python3QT5, in case pip3 error, please Baidu own.

1. create an isolated environment

virtualenv --python=python3.5 --no-site-packages Py3QT5_ENV

2. python3-qt5.12.3 installation

pip3 download pyqt5

pip3 install PyQt5-5.12.3-5.12.4-cp35.cp36.cp37.cp38-abi3-manylinux1_x86_64.whl

pip3 install PyQt5_sip-4.19.17-cp35-cp35m-manylinux1_x86_64.whl

3. qtdesigner installation:

sudo apt-get install qt5-default qttools5-dev-tools

 

Here is the code, can be directly run python.

The following code has a few bug, please help solve some.

1, only a saved video, not being given a small video.

2, when you save the photo or video and want to bring up a save path can save any path and renamed.

Currently 2 can achieve a pop-up box, but you can not save pictures or video properly.

 

 

import sys
import os
import cv2
import numpy as np

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import QPalette, QBrush, QPixmap


class Ui_MainWindow(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Ui_MainWindow, self).__init__(parent)

        self.timer_camera = QtCore.QTimer()  # 初始化打开摄像头定时器
        self.timer_video = QtCore.QTimer()  # 初始化录视频定时器
        self.cap = cv2.VideoCapture()  # 初始化摄像头
        self.CAM_NUM = 0
        self.set_ui()
        self.slot_init()
        self.__flag_work = 0
        self.x = 0
        self.count = 0

        self.vout_1 = 0

    def set_ui(self):
        self.__layout_main = QtWidgets.QHBoxLayout()  # 采用QHBoxLayout类,按照从左到右的顺序来添加控件
        self.__layout_fun_button = QtWidgets.QHBoxLayout()
        self.__layout_data_show = QtWidgets.QVBoxLayout()  # QVBoxLayout类垂直地摆放小部件

        self.button_open_camera = QtWidgets.QPushButton(u'打开')
        self.button_close = QtWidgets.QPushButton(u'退出')
        self.button_video = QtWidgets.QPushButton(u'视频')
        self.button_picture = QtWidgets.QPushButton(u'拍照')

        # button颜色修改
        button_color = [self.button_open_camera, self.button_close, self.button_video, self.button_picture]
        for i in range(4):
            button_color[i].setStyleSheet("QPushButton{color:black}"
                                           "QPushButton:hover{color:red}"
                                           "QPushButton{background-color:rgb(78,255,255)}"
                                           "QpushButton{border:2px}"
                                           "QPushButton{border_radius:10px}"
                                           "QPushButton{padding:2px 4px}")

	# button高度
        self.button_open_camera.setMinimumHeight(50)
        self.button_close.setMinimumHeight(50)
        self.button_video.setMinimumHeight(50)
        self.button_picture.setMinimumHeight(50)
        #self.button_video.setMinimumWidth(10)
        #self.button_picture.setMinimumWidth(10)

        # move()方法是移动窗口在屏幕上的位置到x = 500,y = 500的位置上
        self.move(500, 500)

        # 信息显示
        self.label_show_camera = QtWidgets.QLabel()
        self.label_move = QtWidgets.QLabel()
        self.label_move.setFixedSize(100, 100)

        self.label_show_camera.setFixedSize(641, 481)
        self.label_show_camera.setAutoFillBackground(False)

        self.__layout_fun_button.addWidget(self.button_open_camera)
        self.__layout_fun_button.addWidget(self.button_close)
        self.__layout_fun_button.addWidget(self.button_video)
        self.__layout_fun_button.addWidget(self.button_picture)

        self.__layout_fun_button.addWidget(self.label_move)

        self.__layout_main.addLayout(self.__layout_fun_button)
        self.__layout_main.addWidget(self.label_show_camera)

        self.setLayout(self.__layout_main)
        self.label_move.raise_()
        self.setWindowTitle(u'摄像头')

        '''
        # 设置背景颜色
        palette1 = QPalette()
        palette1.setBrush(self.backgroundRole(),QBrush(QPixmap('background.jpg')))
        self.setPalette(palette1)
       '''

    def slot_init(self):  # 建立通信连接
        self.button_open_camera.clicked.connect(self.button_open_camera_click)
        self.timer_camera.timeout.connect(self.show_camera)	#打开摄像头按钮超时
        self.timer_video.timeout.connect(self.video_camera)	#录视频按钮超时
        self.button_video.clicked.connect(self.button_video_click)
        self.button_picture.clicked.connect(self.button_picture_click)
        self.button_close.clicked.connect(self.close)

    def button_open_camera_click(self):		#打开摄像头按钮
        if self.timer_camera.isActive() == False:
            flag = self.cap.open(self.CAM_NUM)	#open摄像头

            if flag == False:
                msg = QtWidgets.QMessageBox.Warning(self, u'Warning', u'请检测相机与电脑是否连接正确',
                                                    buttons=QtWidgets.QMessageBox.Ok,
                                                    defaultButton=QtWidgets.QMessageBox.Ok)
                # if msg==QtGui.QMessageBox.Cancel:
                #                     pass
            else:
                self.timer_camera.start(30)
                self.button_open_camera.setText(u'关闭')
        else:
            self.timer_camera.stop()
            self.cap.release()
            self.label_show_camera.clear()
            self.button_open_camera.setText(u'打开')


    def button_video_click(self):	#录视频按钮
        flag1, self.image1 = self.cap.read()
	#获得帧的宽高  
        #sz = (int(self.image.get(cv2.CAP_PROP_FRAME_WIDTH)),int(self.image.get(cv2.CAP_PROP_FRAME_HEIGHT)))
        #fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
        fourcc = cv2.VideoWriter_fourcc('X', 'V', 'I', 'D')
        self.vout_1 = cv2.VideoWriter('out.avi', fourcc, 30.0, (640,480))


        if self.timer_video.isActive() == False:

            if flag1 == False:
                msg = QtWidgets.QMessageBox.Warning(self, u'Warning', u'请检测相机与电脑是否连接正确',
                                                    buttons=QtWidgets.QMessageBox.Ok,
                                                    defaultButton=QtWidgets.QMessageBox.Ok)
                # if msg==QtGui.QMessageBox.Cancel:
                #                     pass
            else:
                self.timer_video.start(30)
                fourcc = cv2.VideoWriter_fourcc('X', 'V', 'I', 'D')
                self.vout_1 = cv2.VideoWriter('out.avi', fourcc, 30.0, (640,480))
                self.button_video.setText(u'结束')
        else:
            self.timer_video.stop()
            #self.label_show_camera.clear()
            self.vout_1.release()
            self.button_video.setText(u'视频')


    def video_camera(self):		# 写入视频
        #flag, self.image = self.cap.read()
        #cv2.imshow("capture",self.image)
        self.vout_1.write(self.image)
        cv2.waitKey(10)
        print("1111")
        
        
    def button_picture_click(self):	# 拍照按钮
        #flag, self.image = self.cap.read()
        # 调用存储文件dialog
        fileName, tmp = QFileDialog.getSaveFileName(self, 'Save Image', 'Image', '*.png *.jpg *.bmp')

        #if fileName is '':
         #   return
        #if self.image.size == 1:
        #    return

        # 调用OpenCV写入函数
        #cv2.imwrite(fileName, self.image)
        cv2.imwrite("aaa.jpg", self.image)

    def show_camera(self):		# 摄像头展示
        flag, self.image = self.cap.read()
        show = cv2.resize(self.image, (640, 480))	# 放大缩小
        show = cv2.cvtColor(show, cv2.COLOR_BGR2RGB)
        showImage = QtGui.QImage(show.data, show.shape[1], show.shape[0], QtGui.QImage.Format_RGB888)
        self.label_show_camera.setPixmap(QtGui.QPixmap.fromImage(showImage))

    def closeEvent(self, event):	# 关闭按钮
        ok = QtWidgets.QPushButton()
        cancel = QtWidgets.QPushButton()
        msg = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, u'关闭', u'是否关闭!')
        msg.addButton(ok, QtWidgets.QMessageBox.ActionRole)
        msg.addButton(cancel, QtWidgets.QMessageBox.RejectRole)
        ok.setText(u'确定')
        cancel.setText(u'取消')
        if msg.exec_() == QtWidgets.QMessageBox.RejectRole:
            event.ignore()
        else:
            if self.cap.isOpened():
                self.cap.release()
            if self.timer_camera.isActive():
                self.timer_camera.stop()
            event.accept()



if __name__ == '__main__':
    App = QApplication(sys.argv)
    win = Ui_MainWindow()
    win.show()
    sys.exit(App.exec_())

 

Published 26 original articles · won praise 34 · views 90000 +

Guess you like

Origin blog.csdn.net/qq_36662437/article/details/97629525