当前位置:网站首页>Pyqt5+opencv project practice: microcirculator pictures, video recording and manual comparison software (with source code)
Pyqt5+opencv project practice: microcirculator pictures, video recording and manual comparison software (with source code)
2022-07-02 11:44:00 【hwd00001】
List of articles
This is a use of PYQT5 Based on openCV Image and video capture software .
Source code :
link :https://pan.baidu.com/s/1BtLGvmnfWBqo3tPlRmBQNQ?pwd=74s6
Extraction code :74s6
1. The main function
Play the real-time video of microcirculation microscope , You can save pictures and short videos to your local hard disk ; The saved pictures are numbered + Date time naming ; When checking records , View in a similar way to Explorer , You can compare at will 2 A picture .
1.1 Main interface description

Key function description :
① Open the video : When the video is not opened , Press down “ Open the video ”, Open live image , The button text changes to “ Turn off the video ”; Then press this button , Turn off live images .
② Taking pictures : Capture the real-time picture to the location where the picture is saved .
③ Save the picture : Number the pictures taken + After time naming , Save to hard disk .
④ View records : open “ Check back interface ”.
⑤ New number : Add names that are not in the list , If it is already in the list , You can select... From the drop-down list .
1.2 Description of the back check record interface

On the left side of the back check interface is a 2 Level file management list , Pictured above is an example ,de01、de02 Wait is the number , Numbered sub lists are pictures , Picture with Number + Date time naming , When you click the picture name , Pictures appear in browsing pictures ; Double click the picture name , The picture appears in the comparison picture .
2. Detailed explanation of main interface functions
2.1 Camera operation
The principle of real-time display of camera image is to read more than... In one second 24 Frame and display . The specific operation is to set a 40ms( One second 25 frame , Or less ) Timer for , Every time 40ms Read the picture of the camera once , Display in the fixed area , In this way, you can see the smooth video .
Read a frame of image from the camera and display the code
def show_pic(self):
# 1. Read a frame of image
success, frame=self.cap.read()
if success:
# 2. Get the current time , Select the font
datet = (datetime.datetime.now()).strftime("%Y-%m-%d_%H:%M:%S")
font = cv.FONT_HERSHEY_SIMPLEX
# 3. The resolution of the microcirculator is 600 x 480, Enlarge the picture to 720 x 540
Image = cv.resize(frame,(720,540),interpolation=cv.INTER_CUBIC)
# 4. Time stamp the picture
Image= cv.putText(Image, datet, (10, 540-10), font, 0.5, (0, 0, 255), 1, cv.LINE_AA)
show = cv.cvtColor(Image, cv.COLOR_BGR2RGB)
# 5. stay PYQT5 Show , We need to convert to QPixmap Format
self.showImage = QImage(show.data, show.shape[1], show.shape[0], QImage.Format_RGB888)
self.vediolabel.setPixmap(QPixmap.fromImage(self.showImage))
# 6. Whether to record video
if self.IsVedioRecord:
# 6.1 Write frames to the video file
self.aviout.write(frame)
# 6.2 Only a few seconds can be recorded
if time.time() > self.recordStartTime:
self.IsVedioRecord = False
self.label_tip.setText(" The video is over ! "+datet)
# 6.3 Be sure to release the camera
self.aviout.release()
2.2 Photo function
Press down “ Taking pictures ” Key , Just save the current image temporarily ( Not written to the hard disk ), The name is 《 Number + date + Time .png》.
“ Taking pictures ” The code corresponding to the key :
def show_picA(self):
# 1. Variable self.showImage Store the latest images in , Save the current picture temporarily , Display in the area of the photographed picture
self.label.setPixmap(QPixmap.fromImage(self.showImage))
self.recordImage = self.showImage
datet = (datetime.datetime.now()).strftime("%Y-%m-%d_%H:%M:%S")
self.label_tip.setText(" Photo taken successfully ! "+datet)
datet = (datetime.datetime.now()).strftime("%Y-%m-%d_%H-%M-%S")
# 2. Generate picture name
self.saveName = self.nameBox.currentText() +'_'+ datet + '.png'
2.3 Save the picture
After taking pictures , I think this picture is worth saving , Press down “ Save the picture ” Key , Save the picture to your hard disk .
“ Save the picture ” The code corresponding to the key :
def save_pic_to_userfolder(self):
if len(self.saveName) == 0:
return
datet = (datetime.datetime.now()).strftime("%Y-%m-%d_%H:%M:%S")
self.label_tip.setText(" Picture saved successfully ! "+datet)
self.savePath = self.Code51_dir+'/ymtdata/'+self.nameBox.currentText()+'/'+self.saveName
self.recordImage.save(self.savePath, 'PNG')
2.4 Record a short video
The code for recording video is 2.1 Camera operation ,“ Video shoot ” The function of the key is : Create a video stream object , Set the recording duration , Turn on the recording switch .
“ Video shoot ” The code corresponding to the key :
def start_vedio_record(self):
# 1. Set video encoding format
FRAME_WIDTH = 640
FRAME_HEIGHT = 480
FPS = 10
if not self.IsVedioRecord:
# 2. Generate the name of the video file to be saved
datet = (datetime.datetime.now()).strftime("%Y-%m-%d_%H-%M-%S")
self.vedioName = self.Code51_dir+'/ymtdata/'+self.nameBox.currentText()+'/' \
+self.nameBox.currentText()+'_'+datet+'.avi'
# 3. Create a video stream object
fourcc = cv.VideoWriter_fourcc(*'XVID')
self.aviout = cv.VideoWriter(self.vedioName, fourcc, FPS, (int(FRAME_WIDTH), int(FRAME_HEIGHT)))
# 4. Start the recording switch
self.IsVedioRecord = True
# 5. Set the recording duration to 5 second
self.recordStartTime = time.time()+5.0
self.label_tip.setText(" The video begins ! "+datet)
pass
Recorded video instances :
hwd_2021-10-19_09-19-46
de01_2021-10-19_09-34-49
2.5 View records
The directory where the software is located has 《ymtdata》, The subfolders with each number are stored below , Subfolders store pictures or videos .“ View records ” Press the key to open a new window ( Sub interface ), The code of the sub interface is described in the next chapter .
“ View records ” The code corresponding to the key :
def open_ViewDialog(self):
# 1. Open the sub window for viewing pictures , Need to turn off the camera , After exiting, you need to open it manually
if self.IsTimerStart:
self.timer_camera.stop()
self.OpenCamera.setText(" Turn on the camera ")
self.IsTimerStart = False
Dlg = ViewDlg(self)
# 2. Display window
Dlg.exec_()
2.6 New name
Create a new number , This number will appear in the drop-down bar , A subfolder will also be created .
“ New name ” The code corresponding to the key :
def input_name(self):
#1. Create folder
text, ok = QInputDialog.getText(self, ' Enter a name ', ' Enter a name :')
if ok:
datet = (datetime.datetime.now()).strftime("%Y-%m-%d_%H:%M:%S")
self.label_tip.setText(str(text)+datet)
self.savePath = self.Code51_dir+'/ymtdata'+'/'+str(text)
#2. Determine whether the folder already exists , If it is , Do not create
if not os.path.exists(self.savePath):
os.mkdir(self.savePath) # establish Empty folder
#3. Add to nameBox
self.nameBox.addItem(text)
#4. take New item As Options
self.nameBox.setCurrentIndex(self.nameBox.count()-1)
3. Detailed explanation of sub interface functions
Open sub interface , A 2 Level file management list , There are two areas in the picture display area , On the left is browsing pictures , When clicked , Pictures or videos are statically displayed in this area ; Double click on the file , If it's a picture file , Then it will be displayed in the contrast image area on the right , If it's video , Then play the video on the left .
3.1 Create a file management list
Traverse 《ymtdata》 The following subfolders and files , The structure is relatively simple .
def __init__(self, parent=None):
super(ViewDlg, self).__init__(parent)
self.setupUi(self)
......
#2.1 Root name
root1=QTreeWidgetItem(self.tree)
root1.setText(0,' Picture view ')
if os.path.exists(self.rootDir):
self.CreateTree( os.listdir(self.rootDir),root1 ,self.rootDir )
# Only expand the first level
self.tree.expandToDepth(0)
.......
pass
def CreateTree(self, dirs, root, path):
for i in dirs:
path_new = path + '/' + i
if os.path.isdir(path_new):
child = QTreeWidgetItem(root)
child.setText(0,i)
child.setIcon(0,QIcon(":/{0}.png".format("Folder")))
dirs_new = os.listdir(path_new)
self.CreateTree(dirs_new, child, path_new)
else:
if '.png' in i or '.avi' in i:
child = QTreeWidgetItem(root)
child.setText(0,i)
if '.png' in i:
child.setIcon(0,QIcon(":/{0}.png".format("jpg32")))
elif '.avi' in i:
child.setIcon(0,QIcon(":/{0}.png".format("vedio32")))
3.2 Click file
def onClicked(self, item):
item=self.tree.currentItem()
if '.png' in item.text(0) : #1. If it's a picture , It shows... On the left
self.fileName =self.rootDir +'/'+item.parent().text(0)+'/'+ item.text(0)
self.label_view.setPixmap(QPixmap(self.fileName))
elif '.avi' in item.text(0) : #2. If it's video , Read only the first frame Show
self.fileName =self.rootDir +'/'+item.parent().text(0)+'/'+ item.text(0)
self.cap = cv.VideoCapture(self.fileName)
success, frame = self.cap.read()
if success:
Image = cv.resize(frame,(720,540),interpolation=cv.INTER_CUBIC)
show = cv.cvtColor(Image, cv.COLOR_BGR2RGB)
showImage = QImage(show.data, show.shape[1], show.shape[0], QImage.Format_RGB888)
self.label_view.setPixmap(QPixmap.fromImage(showImage))
self.cap.release()
3.3 Double click on the file
def onTreeDoubleClicked(self,qmodeLindex): # Double click the file in the project list
item=self.tree.currentItem()
if '.png' in item.text(0) : #1. If it's a picture , It shows... On the right
self.fileName =self.rootDir +'/'+item.parent().text(0)+'/'+ item.text(0)
self.label_cmp.setPixmap(QPixmap(self.fileName))
elif '.avi' in item.text(0) : #2. If it's video , Play video on the left
self.fileName =self.rootDir +'/'+item.parent().text(0)+'/'+ item.text(0)
self.cap = cv.VideoCapture(self.fileName)
# Open the video , Turn on timer
self.timer_camera = QTimer(self)
self.timer_camera.timeout.connect(self.show_pic)
self.timer_camera.start(30)
self.isTimerOn=True
边栏推荐
- SQLite modify column type
- Seriation in R: How to Optimally Order Objects in a Data Matrice
- Summary of flutter problems
- Supermarket (heap overload
- 抖音海外版TikTok:正与拜登政府敲定最终数据安全协议
- PYQT5+openCV项目实战:微循环仪图片、视频记录和人工对比软件(附源码)
- map集合赋值到数据库
- Writing contract test cases based on hardhat
- [multithreading] the main thread waits for the sub thread to finish executing, and records the way to execute and obtain the execution result (with annotated code and no pit)
- Is it safe to open a stock account online? I'm a novice, please guide me
猜你喜欢

The selected cells in Excel form have the selection effect of cross shading

Compilation errors and printout garbled problems caused by Chinese content in vs2019 code

The computer screen is black for no reason, and the brightness cannot be adjusted.

Always report errors when connecting to MySQL database

ESP32音频框架 ESP-ADF 添加按键外设流程代码跟踪

Map set assignment to database

Multi line display and single line display of tqdm

Never forget, there will be echoes | hanging mirror sincerely invites you to participate in the opensca user award research

ImportError: cannot import name ‘Digraph‘ from ‘graphviz‘

Tdsql | difficult employment? Tencent cloud database micro authentication to help you
随机推荐
liftOver进行基因组坐标转换
Xiao Sha's pain (double pointer
Basic usage of MySQL in centos8
The difference between SQL left join main table restrictions written after on and where
How to Easily Create Barplots with Error Bars in R
Some suggestions for young people who are about to enter the workplace in the graduation season
Eight sorting summaries
Cluster Analysis in R Simplified and Enhanced
Attribute acquisition method and operation notes of C # multidimensional array
Is it safe to open a stock account through the QR code of the securities manager? Or is it safe to open an account in a securities company?
C file and folder operation
CentOS8之mysql基本用法
MySQL basic statement
MySQL comparison operator in problem solving
Astparser parsing class files with enum enumeration methods
Jenkins installation
Homer forecast motif
How to Create a Nice Box and Whisker Plot in R
Mmrotate rotation target detection framework usage record
揭露数据不一致的利器 —— 实时核对系统