当前位置:网站首页>Implementation of a simple camera based on pyqt5
Implementation of a simple camera based on pyqt5
2022-06-30 01:49:00 【*Program black*】
1、 First of all to ui Layout , The initialization interface is set with four buttons and a black background cloth , The four key function is set to turn on the camera 、 Turn off camera 、 Taking pictures 、 videotape , Pictured :
open and close It's one of two , Click on open In the future, in addition to opening and displaying the camera screen , You have to close Key enable , hold open stop it 
Click again close Will return to the black background , And turn off the open camera , Free the memory occupied by the camera , So that it can be opened next time 
The two buttons can alternately control the camera to read , Memory occupation and release .
The implementation process is :
self.openCameraBtn = QPushButton(‘open’) This is the setting named open The buttons
self.openCameraBtn.clicked.connect(self.openCamera) This is the function connection triggered after the setting key is pressed , That is, set the key open Press trigger openCamera Execution of a function .
self.openCameraBtn.setEnabled(True) This is to enable the key
self.openCameraBtn.setEnabled(False) This is to turn off the key
The camera image display here also involves the problem of timing refresh . So when the program is started, in addition to initialization UI It also initializes a timer :
def initTimer(self):
self.timer = QTimer(self)# Import timer
self.timer.timeout.connect(self.show_pic)# Timeout refresh function self.show_pic
def show_pic(self):
ret, img = self.camera.read()
if not ret:
print('read error!\n')
self.closeCamera()
csbox = QMessageBox(QMessageBox.Warning, self.tr(" Read failed "), self.tr(" Camera open failed , Please check the connection !"), QMessageBox.NoButton, self)
csbox.exec_()
return
# cv2.flip(img, 1, img)# Parameters : original image , Flip type , New image Flip type : level ( about ) Flip >0, vertical ( Up and down ) Flip =0, Flip horizontally and vertically <0
frame = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
print(frame.shape)#(480, 640, 3) Row number , Number of columns , Number of color channels ( namely RGB) img.shape[0] What you get is the height of the picture ,img.shape[1] The result is the width of the picture
heigt, width = frame.shape[:2]#[0] and [1]
pixmap = QImage(frame, width, heigt, QImage.Format_RGB888)# Read images
# print(pixmap)
pixmap = QPixmap.fromImage(pixmap)
self.showcamera.setPixmap(pixmap)# Set pixel
self.imgsave=img
if self.opencameras==True and self.openvideo==True:
self.out.write(frame)
self.videoCameraBtn.setEnabled(False)
else:
print(self.openvideo)
self.openvideo=False
self.videoCameraBtn.setEnabled(True)
2、 The next step is to set the photographing function , Press the Photo button to enter pictureCamera function , The function looks like this , It can be seen that there is detection to ensure that the camera is turned on before reading and writing image data , If you don't make sure the camera is on , Data is empty , An error will be reported when the graph is written , Make sure the camera is turned on before taking photos and videos .
if self.opencameras==True:# The camera has been turned on
img_name = 'pictures/%d.jpg'%self.count
cv2.imwrite(img_name, self.imgsave) # Training set write path
self.count += 1
cv2.imshow("camera", self.imgsave)


You can see , After pressing the button to take pictures, the current camera status will be saved and written into a picture named in sequence , And a captured image will pop up .
3、 Here is how to set the video recording function , Press the video button to enter videoCamera function , The function looks like this , It can be seen that there is also detection to ensure that the camera is turned on before reading and writing image data .
if self.opencameras==True:# The camera has been turned on
self.nowtimes = time.strftime("%Y-%m-%d_%H_%M_%S_%p",time.localtime())+"_"+time.strftime("%u",time.localtime())
videos='./videos/'+self.nowtimes+'.avi'
print(videos)
self.out = cv2.VideoWriter(videos,self.fourcc, 20.0, (640,480))# Create a video file
self.openvideo=True # Open the tag of the video file
self.videoCameraBtn.setEnabled(False)
In addition to the normal process of creating video files , There is also a button to turn off video recording , This also means that only one video can be generated at a time avi file , Each time the image is refreshed regularly, it will be judged whether it is in the recording process , If it is in the video recording, read it from the camera frame Write to video file
if self.opencameras==True and self.openvideo==True:
self.out.write(frame)
self.videoCameraBtn.setEnabled(False)
else:
print(self.openvideo)
self.openvideo=False
self.videoCameraBtn.setEnabled(True)
The following figure shows the process of video recording :
To stop recording, press closs Just turn off the camera . The function to close the key connection is as follows :
self.camera.release()# Release the occupied camera
if self.openvideo==True:
self.out.release()
self.openCameraBtn.setEnabled(True)
self.closeCameraBtn.setEnabled(False)# Turn off key enable
self.videoCameraBtn.setEnabled(True)# Enable key
self.showcamera.setStyleSheet("background:black;")# Set the style : The background is black
self.showcamera.setPixmap(QPixmap())# Set pixel
self.timer.stop()# The timer stops
self.opencameras=False
self.openvideo=False
You can see that the function contains several parts , One is to handle the camera , Free the memory occupied by the camera ; The second one is the button ui Handle , Even if you can open the button and video button , Disable the camera button ; The third is clock processing , Stop timer , The purpose is to stop displaying the images acquired by the camera , If you don't stop, an error will be reported , Because the memory of the camera has been released , therefore , The content of the image refreshed by the clock cannot be collected , All will be wrong .
The following is the source code of the project :
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import cv2
import sys
import os
import time
def chdir(path):
# Introduce modules
import os
# Remove the first space
path = path.strip()
# Remove the tail \ Symbol
path = path.rstrip("\\")
# Determine if the path exists
# There is True
# non-existent False
isExists = os.path.exists(path)
# Judge the result
if not isExists:
# Create a directory if it doesn't exist
# Create directory manipulation functions
print(path + ' directory does not exist ')
return False
else:
# Do not create if directory exists , And prompt that the directory already exists
print(path + ' directory already exists ')
return True
# Read the list of backup files
def read_filename(filePath):
import os
name = os.listdir(filePath)# obtain filepath List of files
print(name)
return name
class Example(QWidget):
def __init__(self):
super().__init__()
# Check and create folders
if chdir('pictures')==False:
os.mkdir('pictures')
if chdir('videos')==False:
os.mkdir('videos')
print(len(read_filename('pictures')))
# self.fourcc = cv2.VideoWriter_fourcc(*'XVID')#FourCC It's just one. 4 Bytecode , Used to determine the encoding format of video
self.fourcc = cv2.VideoWriter_fourcc(*'MJPG')
self.nowtimes=' '
self.opencameras=False
self.openvideo=False
self.count = int(len(read_filename('pictures')))
self.initUI()
self.initTimer()
def initTimer(self):
self.timer = QTimer(self)# Import timer
self.timer.timeout.connect(self.show_pic)# Timeout refresh function self.show_pic
def show_pic(self):
ret, img = self.camera.read()
if not ret:
print('read error!\n')
self.closeCamera()
csbox = QMessageBox(QMessageBox.Warning, self.tr(" Read failed "), self.tr(" Camera open failed , Please check the connection !"), QMessageBox.NoButton, self)
csbox.exec_()
return
# cv2.flip(img, 1, img)# Parameters : original image , Flip type , New image Flip type : level ( about ) Flip >0, vertical ( Up and down ) Flip =0, Flip horizontally and vertically <0
frame = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
print(frame.shape)#(480, 640, 3) Row number , Number of columns , Number of color channels ( namely RGB) img.shape[0] What you get is the height of the picture ,img.shape[1] The result is the width of the picture
heigt, width = frame.shape[:2]#[0] and [1]
pixmap = QImage(frame, width, heigt, QImage.Format_RGB888)# Read images
# print(pixmap)
pixmap = QPixmap.fromImage(pixmap)
self.showcamera.setPixmap(pixmap)# Set pixel
self.imgsave=img
if self.opencameras==True and self.openvideo==True:
self.out.write(frame)
self.videoCameraBtn.setEnabled(False)
else:
print(self.openvideo)
self.openvideo=False
self.videoCameraBtn.setEnabled(True)
def openCamera(self):
self.showcamera.setEnabled(True)
self.camera = cv2.VideoCapture(0) #'http://admin:[email protected]:8081'
# self.camera = cv2.VideoCapture('http://admin:[email protected]:8081')
self.openCameraBtn.setEnabled(False)# Close button
self.closeCameraBtn.setEnabled(True)# Enable key
self.timer.start(3)# timing 3 Start timing
self.opencameras=True
def closeCamera(self):
self.camera.release()# Release the occupied camera
if self.openvideo==True:
self.out.release()
self.openCameraBtn.setEnabled(True)
self.closeCameraBtn.setEnabled(False)# Turn off key enable
self.videoCameraBtn.setEnabled(True)# Enable key
self.showcamera.setStyleSheet("background:black;")# Set the style : The background is black
self.showcamera.setPixmap(QPixmap())# Set pixel
self.timer.stop()# The timer stops
self.opencameras=False
self.openvideo=False
def pictureCamera(self):
print('picture')
if self.opencameras==True:# The camera has been turned on
img_name = 'pictures/%d.jpg'%self.count
cv2.imwrite(img_name, self.imgsave) # Training set write path
self.count += 1
cv2.imshow("camera", self.imgsave)
def videoCamera(self):
print('video')
if self.opencameras==True:# The camera has been turned on
self.nowtimes = time.strftime("%Y-%m-%d_%H_%M_%S_%p",time.localtime())+"_"+time.strftime("%u",time.localtime())
videos='./videos/'+self.nowtimes+'.avi'
print(videos)
self.out = cv2.VideoWriter(videos,self.fourcc, 20.0, (640,480))# Create a video file
self.openvideo=True # Open the tag of the video file
self.videoCameraBtn.setEnabled(False)
def initUI(self):
self.openCameraBtn = QPushButton('open')
self.openCameraBtn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) # Set the control in the layout (layout) Inside the size change attribute QSizePolicy.Fixed: Fixed size , Do not stretch or compress
self.openCameraBtn.clicked.connect(self.openCamera)
self.closeCameraBtn = QPushButton('close')
self.closeCameraBtn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
self.closeCameraBtn.clicked.connect(self.closeCamera)
self.pictureCameraBtn = QPushButton(' Taking pictures ')
self.pictureCameraBtn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) # Set the control in the layout (layout) Inside the size change attribute QSizePolicy.Fixed: Fixed size , Do not stretch or compress
self.pictureCameraBtn.clicked.connect(self.pictureCamera)
self.videoCameraBtn = QPushButton(' videotape ')
self.videoCameraBtn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
self.videoCameraBtn.clicked.connect(self.videoCamera)
self.openCameraBtn.setEnabled(True)
self.closeCameraBtn.setEnabled(False)
self.showcamera = QLabel(self)
self.showcamera.resize(640, 480)
self.hbox = QHBoxLayout(self)# Horizontal layout
self.hbox.addWidget(self.showcamera)# Add controls based on horizontal layout addwidget() Method to add a control to a layout
self.vbox = QVBoxLayout(self)# Vertical layout
self.vbox.addWidget(self.openCameraBtn)
self.vbox.addWidget(self.closeCameraBtn)
self.vbox.addWidget(self.pictureCameraBtn)
self.vbox.addWidget(self.videoCameraBtn)
self.hbox.addLayout(self.vbox)
self.setLayout(self.hbox)#setLayout Is to apply the set layout to the control
self.showcamera.setStyleSheet("background:black;")# Set the style : The background is black
self.showcamera.setPixmap(QPixmap())# Set pixel
# self.move(300, 300)
self.setWindowTitle('camera')
self.setGeometry(600, 200, 760, 510)
self.show()
def closeEvent(self, event):
reply = QMessageBox.question(self, ' Tips ', " Are you sure to quit? ?", QMessageBox.Yes |QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
event.accept()
else:
event.ignore()
if __name__=='__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
Here is the running video :
【cameras- Bili, Bili 】 https://b23.tv/DY6bOAM
cameras
边栏推荐
- Varnish foundation overview 2
- Mysql 监控1
- App test related tools
- C语言 数组元素循环右移问题
- js返回内容被unicode编码
- What should I do when I feel confused after graduation from university?
- AI落地制造业:智能机器人应具备这4种能力
- [machine learning Q & A] accuracy, accuracy, recall, ROC and AUC
- Circular right shift of array elements in C language
- 对深度网络模型量化工作的总结
猜你喜欢

Thinking carefully and fearfully: a software can be transmitted online to monitor whether employees want to "run away"

C语言 数素数

城市规划馆在设计制作上需要注意什么
![[pytorch actual combat] generate confrontation network Gan: generate cartoon character avatars](/img/8f/c0cc1c8d19060a60d92c0d72f8b93d.png)
[pytorch actual combat] generate confrontation network Gan: generate cartoon character avatars

Chiffrement des cookies 8

【机器学习Q&A】数据抽样和模型验证方法、超参数调优以及过拟合和欠拟合问题

Cookie加密12

当大学毕业感到迷茫怎么办?
![【图神经网络】图分类学习研究综述[3]:图分类方法评价及未来研究方向](/img/b1/2afa73a14b2f41b7a65c4c2d261e6a.png)
【图神经网络】图分类学习研究综述[3]:图分类方法评价及未来研究方向

JS reverse request parameter encryption:
随机推荐
Scala基础【入门及安装】
js逆向请求参数加密:
Error reporting in Luban H5 installation
JS reverse request parameter encryption:
Varnish foundation overview 5
Cookie encryption 11
win10子系统 WSL如果root和其他用户的密码都忘记的修复方法
想转行,但不知道自己要做什么工作比较好?
207. curriculum - graph theory, depth traversal
[mrctf2020]ezpop-1 | PHP serialization
Varnish 基础概览2
Want to change careers, but don't know what you want to do?
假离婚变成真离婚,财产怎么办
什么是幂等性?四种接口幂等性方案详解!
搞透AQS原理(流程圖及同步隊列圖解)
js内容混淆,返回内容加密
Fake divorce turns into real divorce. What about property
Embedded exit (review and release)
Varnish 基础概览5
Understand AQS principle (flow chart and synchronous queue diagram)