一、安装Python
下载安装到这个目录
G:\Python38-32
安装完成有这些工具,后面备用:
G:\Python38-32\Scripts\pyrcc5.exe
G:\Python38-32\Scripts\pyuic5.exe
二、PyQt环境配置
pip install PyQt5
pip install pyqt5-tools
建议使用国内源,进行快速安装:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pyqt5
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pyqt5-tools
安装QT,安装到 E:\Qt5.12.6 目录下;
从这个目录下打开qtcreator.exe
E:\Qt5.12.6\Tools\QtCreator\bin
三、用QTCreator设计界面
Qt Designer 是通过拖拽的方式放置控件,并实时查看控件效果进行快速UI设计。
这里只需要 MainWindow.ui 文件
最终生成.ui文件(实质上是XML格式的文件),可以通过pyuic5工具转换成.py文件。
ui文件到 py文件:pyuic5.exe xxx.ui -o xxx.py
pyuic5.exe主要是把Qt Designer生成的.ui文件换成.py文件。
pyrcc5.exe主要是把编写的.qrc资源文件换成.py文件。
需要把按钮事件绑定到槽函数:
self.pushButton.clicked.connect(self.PropertyClicked)
完成后的代码如下
testMVCam.py
python">import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QMainWindow
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import mvsdk
from MainWindow import Ui_MainWindow color = Falseclass MyWidget(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(MyWidget, self).__init__(parent) self.setupUi(self) # 枚举相机DevList = mvsdk.CameraEnumerateDevice()nDev = len(DevList)if nDev < 1:print("No camera was found!")returnfor i, DevInfo in enumerate(DevList):print("{}: {} {}".format(i, DevInfo.GetFriendlyName(), DevInfo.GetPortType()))i = 0 if nDev == 1 else int(input("Select camera: "))DevInfo = DevList[i]print(DevInfo)# 打开相机global hCamera# hCamera = 0try:hCamera = mvsdk.CameraInit(DevInfo, -1, -1)except mvsdk.CameraException as e:print("CameraInit Failed({}): {}".format(e.error_code, e.message))QMessageBox.question(self, '本程序', '初始化相机失败!')returnglobal capcap = mvsdk.CameraGetCapability(hCamera)if cap.sIspCapacity.bMonoSensor:mvsdk.CameraSetIspOutFormat(hCamera, mvsdk.CAMERA_MEDIA_TYPE_MONO8)color = Falseelse:mvsdk.CameraSetIspOutFormat(hCamera, mvsdk.CAMERA_MEDIA_TYPE_RGB8)color = True# 相机模式切换成连续采集mvsdk.CameraSetTriggerMode(hCamera, 0)# 自动曝光# mvsdk.CameraSetAeState(hCamera, 1)mvsdk.CameraCreateSettingPage(hCamera, 0, DevInfo.acFriendlyName, 0, 0, 0)# 让SDK内部取图线程开始工作mvsdk.CameraPlay(hCamera)# Mindvision线程self.MVthread = MindvisionThread()self.MVthread.signal.connect(self.image_callback)self.MVthread.start()self.pushButton.clicked.connect(self.PropertyClicked)#self.pushButton_9.clicked.connect(self.save_mindvision_image)def stop_thread(self):if self.MVthread is not None and self.MVthread.isRunning():self.MVthread.stop()def save_mindvision_image(self):global hCamerapRawData, FrameHead = mvsdk.CameraGetImageBuffer(hCamera, 2000)mvsdk.CameraImageProcess(hCamera, pRawData, pFrameBuffer, FrameHead)mvsdk.CameraReleaseImageBuffer(hCamera, pRawData)mvsdk.CameraSaveImage(hCamera, "./pic.bmp", pFrameBuffer, FrameHead, mvsdk.FILE_BMP, 80)def image_callback(self, image):pixmap = QPixmap.fromImage(image)# ratio = max(width / self.left_bottom_image.width(), height / self.left_bottom_image.height())self.label.setAlignment(Qt.AlignCenter)self.label.setScaledContents(True)self.label.setPixmap(pixmap)def PropertyClicked(self):mvsdk.CameraShowSettingPage(hCamera, True); # def initUI(self): # # 创建标签 # label = QLabel('Hello, PyQt!') # # 创建按钮 # button = QPushButton('Click me!') # button.clicked.connect(self.buttonClicked) # # 将标签和按钮添加到窗口中 # self.setCentralWidget(label) # self.setWidget(button) # def buttonClicked(self): # # 在这里编写按钮被点击时要执行的代码 # print('Button clicked!')
# 程序退出def closeEvent(self, event):reply = QMessageBox.question(self, '本程序', '是否要退出?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No)if reply == QMessageBox.Yes:global pFrameBufferevent.accept()self.stop_thread()mvsdk.CameraUnInit(hCamera)mvsdk.CameraAlignFree(pFrameBuffer)sys.exit(0)else:event.ignore() class MindvisionThread(QThread):signal = pyqtSignal(QImage)def __init__(self):super(MindvisionThread, self).__init__()self.is_running = True# 计算RGB buffer所需的大小,这里直接按照相机的最大分辨率来分配FrameBufferSize = cap.sResolutionRange.iWidthMax * cap.sResolutionRange.iHeightMax * 3 global pFrameBufferpFrameBuffer = mvsdk.CameraAlignMalloc(FrameBufferSize, 16) def run(self):while self.is_running:global capglobal hCameraglobal FrameHead# 分配RGB buffer,用来存放ISP输出的图像#global pFrameBuffer#pFrameBuffer = mvsdk.CameraAlignMalloc(FrameBufferSize, 16)try:pRawData, FrameHead = mvsdk.CameraGetImageBuffer(hCamera, 2000)mvsdk.CameraImageProcess(hCamera, pRawData, pFrameBuffer, FrameHead)# Windows 上下帧翻转mvsdk.CameraFlipFrameBuffer(pFrameBuffer, FrameHead, 1)mvsdk.CameraReleaseImageBuffer(hCamera, pRawData)# mvsdk.CameraSaveImage(hCamera, ".\\pic.bmp", pFrameBuffer, FrameHead, mvsdk.FILE_BMP, 80)# break#mat = QImage(pFrameBuffer, cap.sResolutionRange.iWidthMax, cap.sResolutionRange.iHeightMax, QImage.Format_RGB888 if True == color else QImage.Format_Indexed8 )if FrameHead.uiMediaType==mvsdk.CAMERA_MEDIA_TYPE_MONO8:#if(quit) breakimg = QImage(pFrameBuffer, FrameHead.iWidth, FrameHead.iHeight, QImage.Format_Indexed8)#img.setColorTable(grayColourTable);#emit captured(img);self.signal.emit(QImage(img))else:#if(quit) breakimg = QImage(pFrameBuffer, FrameHead.iWidth, FrameHead.iHeight, QImage.Format_RGB888)#emit captured(img);self.signal.emit(QImage(img))# self.signal.emit(QImage(mat))n = self.getTrgNum()# print( n )except mvsdk.CameraException as e:print("CameraGetImageBuffer failed({}): {}".format(e.error_code, e.message) )def stop(self):self.is_running = Falsedef getTrgNum(self):global hCamerac_Num = mvsdk.c_int()mvsdk.CameraSpecialControl(hCamera, 0x1000, 0x1000050C, mvsdk.addressof(c_Num))return c_Num.value if __name__ == '__main__': app = QApplication(sys.argv) widget = MyWidget() widget.show() sys.exit(app.exec_())
MainWindow.py
python"># -*- coding: utf-8 -*-# Form implementation generated from reading ui file 'MainWindow.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.from PyQt5 import QtCore, QtGui, QtWidgetsclass Ui_MainWindow(object):def setupUi(self, MainWindow):MainWindow.setObjectName("MainWindow")MainWindow.resize(800, 600)self.centralwidget = QtWidgets.QWidget(MainWindow)self.centralwidget.setObjectName("centralwidget")self.pushButton = QtWidgets.QPushButton(self.centralwidget)self.pushButton.setGeometry(QtCore.QRect(20, 20, 75, 23))self.pushButton.setObjectName("pushButton")self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)self.pushButton_2.setGeometry(QtCore.QRect(120, 20, 75, 23))self.pushButton_2.setObjectName("pushButton_2")self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)self.pushButton_3.setGeometry(QtCore.QRect(220, 20, 75, 23))self.pushButton_3.setObjectName("pushButton_3")self.label = QtWidgets.QLabel(self.centralwidget)self.label.setGeometry(QtCore.QRect(20, 60, 551, 421))self.label.setObjectName("label")MainWindow.setCentralWidget(self.centralwidget)self.menubar = QtWidgets.QMenuBar(MainWindow)self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))self.menubar.setObjectName("menubar")MainWindow.setMenuBar(self.menubar)self.statusbar = QtWidgets.QStatusBar(MainWindow)self.statusbar.setObjectName("statusbar")MainWindow.setStatusBar(self.statusbar)self.retranslateUi(MainWindow)QtCore.QMetaObject.connectSlotsByName(MainWindow)def retranslateUi(self, MainWindow):_translate = QtCore.QCoreApplication.translateMainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))self.pushButton.setText(_translate("MainWindow", "属性设置"))self.pushButton_2.setText(_translate("MainWindow", "PushButton"))self.pushButton_3.setText(_translate("MainWindow", "PushButton"))self.label.setText(_translate("MainWindow", "TextLabel"))
运行效果
(结束)