为什么我import PyQt5.QtWidgets后程序就退出了

我在使用PyQt5时,不能import PyQt5.QtWidgets,无论是

import PyQt
import PyQt5.QtWidgets

还是

from PyQt5 import QtWidgets

以及

from PyQt5.QtWidgets import (一个存在的东西)

都会直接退出程序

image.png

重装过了好多次了,都不好使
请问这应该怎么做

我突然发现了一个诡异的实时,在VSCode里运行就行不通,但在cmd里就行得通,有哪位大神能解答一下吗?

1个回答

weixin_45888599
CarlGao4 我发现在anaconda的base(3.7.6)就能正常运行,但我又创建了一个3.8.1的环境,就不行了。是3.8版本的PyQt有Bug吗?
大约 2 个月之前 回复
weixin_45888599
CarlGao4 对不起,我不明白您发这个链接是做什么,我的问题仍然没有解决
大约 2 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Python+OpenCV计算机视觉

Python+OpenCV计算机视觉

python pyqt5 怎样暂停和退出指定线程?

![图片说明](https://img-ask.csdn.net/upload/201810/05/1538742487_875554.png) 怎样在点击界面的按钮暂停 或 停止 来控制线程的暂停或停止 我写的代码如下,请大神们指导下添加什么方法来控制线程 ``` # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'test1.ui' # # Created by: PyQt5 UI code generator 5.11.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets import time import threading import sys import os class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(387, 288) self.listWidget = QtWidgets.QListWidget(Dialog) self.listWidget.setGeometry(QtCore.QRect(110, 30, 256, 192)) self.listWidget.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) self.listWidget.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) self.listWidget.setObjectName("listWidget") self.widget = QtWidgets.QWidget(Dialog) self.widget.setGeometry(QtCore.QRect(20, 40, 77, 83)) self.widget.setObjectName("widget") self.verticalLayout = QtWidgets.QVBoxLayout(self.widget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName("verticalLayout") self.pushButton = QtWidgets.QPushButton(self.widget) self.pushButton.setObjectName("pushButton") self.verticalLayout.addWidget(self.pushButton) self.pushButton_2 = QtWidgets.QPushButton(self.widget) self.pushButton_2.setObjectName("pushButton_2") self.verticalLayout.addWidget(self.pushButton_2) self.pushButton_3 = QtWidgets.QPushButton(self.widget) self.pushButton_3.setObjectName("pushButton_3") self.verticalLayout.addWidget(self.pushButton_3) self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Dialog")) self.pushButton.setText(_translate("Dialog", "开始")) self.pushButton_2.setText(_translate("Dialog", "暂停")) self.pushButton_3.setText(_translate("Dialog", "停止")) class Dialog(QtWidgets.QDialog): def closeEvent(self, event): reply = QtWidgets.QMessageBox.question(self, '本程序', "是否要退出程序?", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No) if reply == QtWidgets.QMessageBox.Yes: event.accept() os._exit(0) else: event.ignore() class myThread(threading.Thread): def __init__(self, ui): threading.Thread.__init__(self) self.ui = ui self.counter = 0 def run(self): a = 0 while True: a+=1 print(a) self.ui.listWidget.addItem(str(a)) time.sleep(1) def main(): """ 主函数,用于运行程序 :return: None """ app = QtWidgets.QApplication(sys.argv) dialog = Dialog() # 注意修改为了自己重写的Dialog类 ui = Ui_Dialog() ui.setupUi(dialog) dialog.show() # 显示了自己重写的Dialog类 thread1 = myThread(ui) thread1.start() sys.exit(app.exec_()) if __name__ == '__main__': main() ```

PyQt5关于QThread线程阻塞以及UI界面假死的问题

界面有两个按钮,一个启动QThread线程,一个启动threading.Thread线程,做的同样的工作,模拟耗时操作。代码如下: ``` import sys, os import threading import time import PyQt5.QtWidgets as qtw from PyQt5.QtCore import QThread from PyQT5.test import Ui_MainWindow class MyWindow(qtw.QMainWindow, Ui_MainWindow): def __init__(self): super().__init__() self.setupUi(self) self.btn_begin1.clicked.connect(startWork1) self.btn_begin2.clicked.connect (startWork2) self.show () class MyThread(QThread): # signal = pyqtSignal(int) def __init__(self): super().__init__() def __del__(self): self.wait() def run(self): print("run") work(15) def startWork1(): thread = MyThread() print ("start") thread.start () print ("start finish") def startWork2(): threading.Thread(target=work, args=(15,)).start() def work(n): print ("work") for i in range(1, n+1): print(str(i)+": do something...") time.sleep(1) if __name__ == "__main__": app = qtw.QApplication(sys.argv) w = MyWindow() app.exec_ () ``` 问题1:点击按钮1启动Qthread,5秒后UI界面出现假死,点击按钮2启动threading.Thread不会出现假死 问题2:在MyThread中把def __del__(self):self.wait()这个方法删除后,正常运行程序闪退,没有运行到run()方法,以debug方式运行,能正常运行,且点击按钮1时不会出现UI界面假死 我的环境为python3.6 pyqt5-5.13.0 pycharm2017.3 请教下是什么原因造成上述两个问题。

pyqt5的qmessagebox闪退求助

各位大神帮我看下是什么问题 造成只要输入不是数字 进入else语句的messagebox就闪退 若注视掉messagebox语句,下面的print能够执行 # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'change.ui' # # Created by: PyQt5 UI code generator 5.7 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets #from PyQt5.QtWidgets import QMessageBox import re class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(800, 600) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.lineEdit = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit.setGeometry(QtCore.QRect(320, 140, 113, 20)) self.lineEdit.setMinimumSize(QtCore.QSize(113, 20)) self.lineEdit.setObjectName("lineEdit") self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit_2.setGeometry(QtCore.QRect(320, 210, 113, 20)) self.lineEdit_2.setMinimumSize(QtCore.QSize(113, 20)) self.lineEdit_2.setObjectName("lineEdit_2") 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) self.lineEdit.editingFinished.connect(self.update) #self.lineEdit_2.connect(self.lineEdit, SIGNAL("editingFinished"), self.update) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) def update(self): try: text=self.lineEdit.text() value=re.compile(r'[0-9]+\.+[0-9]+$') result=value.match(text) if result: intnum=text.rsplit(".") #print (intnum) othernum="0"+"."+intnum[1] #print (othernum) minnum=int(float(othernum)*60) #print (minnum) secnum=int(float(othernum)*3600-minnum*60) #print(secnum) self.lineEdit_2.setText(intnum[0]+"°"+str(minnum)+"′"+str(secnum)+"″") else: QtGui.QMessageBox.warning(self,"Warning","输入数据错误,请重新输入!", QMessageBox.OK,QMessageBox.OK) print("输入错误") except: print(sys.exc_info)

这是一个关于 PYTHON 的PYQT5的相关问题

``` from PyQt5 import QtCore, QtGui, QtWidgets class 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(340, 430, 75, 23)) self.pushButton.setObjectName("pushButton") self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_2.setGeometry(QtCore.QRect(510, 430, 75, 23)) self.pushButton_2.setObjectName("pushButton_2") self.textEdit = QtWidgets.QTextEdit(self.centralwidget) self.textEdit.setGeometry(QtCore.QRect(280, 200, 411, 161)) self.textEdit.setObjectName("textEdit") self.lineEdit = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit.setGeometry(QtCore.QRect(210, 90, 113, 20)) self.lineEdit.setObjectName("lineEdit") self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit_2.setGeometry(QtCore.QRect(410, 90, 113, 20)) self.lineEdit_2.setObjectName("lineEdit_2") self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(80, 90, 54, 12)) self.label.setObjectName("label") self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_3.setGeometry(QtCore.QRect(600, 100, 75, 23)) self.pushButton_3.setObjectName("pushButton_3") self.lineEdit_3 = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit_3.setGeometry(QtCore.QRect(190, 430, 113, 20)) self.lineEdit_3.setObjectName("lineEdit_3") 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.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.pushButton.setText(_translate("MainWindow", "发送")) self.pushButton_2.setText(_translate("MainWindow", "关闭")) self.label.setText(_translate("MainWindow", "服务器")) self.pushButton_3.setText(_translate("MainWindow", "连接")) import sys from PyQt5 import QtWidgets import untitled import socket class Mywindow(QtWidgets.QMainWindow, untitled.Ui_MainWindow): quest=socket.socket(socket.AF_INET,socket.SOCK_STREAM) def __init__(self): super(Mywindow, self).__init__() self.setupUi(self) #继承于Ui_MainWindow self.pushButton_3.clicked.connect(self.lianjie) self.pushButton.clicked.connect(self.xiaoxi) def lianjie(self): self.quest.connect((self.lineEdit.Text(),int(self.lineEdit_2.Text()))) def xiaoxi(self): self.quest.send(self.lineEdit_3.Text().encode()) a=self.quest.recv(100).decode() self.textEdit.setText(a) self.quest.close() if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) window = Mywindow() window.show() sys.exit(app.exec_()) ``` 上面是客户机代码 ,代码和PYQT5联系在一起了 下面是服务器代码,没有和窗体联系在一起 ``` import socket service=socket.socket(socket.AF_INET,socket.SOCK_STREAM) service.bind(('127.0.0.1',6)) service.listen(3) tao,add=service.accept() data=tao.recv(100).decode() tao.send(data.encode()) tao.close() service.close() ``` 为什么我打开客户机,连接按钮 ,系统退出,产生错误呢?

pyqt5如何弹出多个界面心事多组不同的数据

我这里有多组数据需要展示,展示的界面是在alert.py中写的,现在我想弹出多个界面,其中每个界面展示一组数据。现在的结果是alert.py可以接收到传过来的数据,界面也能弹出,但是界面上没有显示出数据,而且我的弹框线程无法将数据和界面一一对应起来,我想请问一下这是什么原因? main.py ``` from PyQt5 import * from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * import sys import time from alert import Show_Text from change import Show_Change import winsound class Ui_Control_system(object): def setupUi(self, Control_system): Control_system.setObjectName("Control_system") Control_system.resize(1004, 722) Control_system.setFixedSize(1004, 722) Control_system.setWindowIcon(QIcon('images/icon.png')) Control_system.setStyleSheet("QMainWindow{border-image:url(images/background.jpg)}") self.centralwidget = QWidget(Control_system) self.centralwidget.setObjectName("centralwidget") self.pushButton_skip = QPushButton(self.centralwidget) self.pushButton_skip.setGeometry(QRect(70, 60, 121, 41)) self.pushButton_skip.setObjectName("pushButton_skip") Control_system.setCentralWidget(self.centralwidget) self.statusbar = QStatusBar(Control_system) self.statusbar.setObjectName("statusbar") Control_system.setStatusBar(self.statusbar) self.retranslateUi(Control_system) QMetaObject.connectSlotsByName(Control_system) def retranslateUi(self, Control_system): _translate = QCoreApplication.translate Control_system.setWindowTitle(_translate("Control_system", "实时监控系统")) self.pushButton_skip.setText(_translate("Control_system", "跳转")) class Control_system(QMainWindow, Ui_Control_system): #alarmQueue = queue.LifoQueue() def __init__(self, parent=None): super().__init__(parent) self.setupUi(self) self.add_data_list = "" self.pushButton_skip.clicked.connect(self.jump_to_alert) self._alerts = [] @pyqtSlot() def jump_to_alert(self): self.popup_window_thread = PopupWindow(self) self.popup_window_thread.popup.connect(self.goAlert) self.popup_window_thread.start() @pyqtSlot() def jump_to_change(self): self.change_window_thread = ChangeWindow(self) self.change_window_thread.change_signal.connect(self.goChange) self.change_window_thread.start() def goAlert(self): self.add_data_list = [["1","2","3"],["4","5","6"]] for term in self.add_data_list: alert = Alert() alert.some_room = term[0] alert.some_machine = term[1] alert.some_project = term[2] print(alert.some_project) alert.show() self._alerts.append(alert) class Alert(Show_Text): def __init__(self): super().__init__() #self.setupUi(self) def closeEvent(self, event): reply = QMessageBox.question(self, '警告', "是否要退出警告?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: event.accept() else: event.ignore() class PopupWindow(QThread): popup = pyqtSignal() def __init__(self, parent=None): super(PopupWindow, self).__init__() self.index = 0 def run(self): while self.index <= 1: self.index +=1 self.popup.emit() time.sleep(1) def stop(self): self.quit() self.wait() if __name__ == '__main__': if not QApplication.instance(): app = QApplication(sys.argv) else: app = QApplication.instance() w = Control_system() w.show() sys.exit(app.exec()) ``` alert.py ``` from PyQt5 import * from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * import time class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(557, 444) #Dialog.setStyleSheet("QDialog{border-image:url(images/background.jpg)}") Dialog.setWindowIcon(QIcon('images/icon.png')) self.textBrowser = QtWidgets.QTextBrowser(Dialog) self.textBrowser.setGeometry(QtCore.QRect(200, 80, 256, 41)) self.textBrowser.setObjectName("textBrowser") self.textBrowser_2 = QtWidgets.QTextBrowser(Dialog) self.textBrowser_2.setGeometry(QtCore.QRect(200, 170, 256, 41)) self.textBrowser_2.setObjectName("textBrowser_2") self.textBrowser_3 = QtWidgets.QTextBrowser(Dialog) self.textBrowser_3.setGeometry(QtCore.QRect(200, 260, 256, 41)) self.textBrowser_3.setObjectName("textBrowser_3") self.label = QtWidgets.QLabel(Dialog) self.label.setGeometry(QtCore.QRect(60, 80, 111, 31)) font = QtGui.QFont() font.setFamily("微软雅黑") font.setPointSize(20) font.setBold(True) font.setWeight(75) self.label.setFont(font) self.label.setStyleSheet("color: rgb(255, 0, 0);") self.label.setTextFormat(QtCore.Qt.AutoText) self.label.setObjectName("label") self.label_2 = QtWidgets.QLabel(Dialog) self.label_2.setGeometry(QtCore.QRect(60, 170, 111, 31)) font = QtGui.QFont() font.setFamily("微软雅黑") font.setPointSize(20) font.setBold(True) font.setWeight(75) self.label_2.setFont(font) self.label_2.setStyleSheet("color: rgb(255, 0, 0);") self.label_2.setTextFormat(QtCore.Qt.AutoText) self.label_2.setObjectName("label_2") self.alert = QtWidgets.QLabel(Dialog) self.alert.setGeometry(QtCore.QRect(60, 260, 111, 31)) font = QtGui.QFont() font.setFamily("微软雅黑") font.setPointSize(20) font.setBold(True) font.setWeight(75) self.alert.setFont(font) self.alert.setStyleSheet("color: rgb(255, 0, 0);") self.alert.setTextFormat(QtCore.Qt.AutoText) self.alert.setObjectName("alert") self.retranslateUi(Dialog) def retranslateUi(self, Dialog): _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "警告")) self.label.setText(_translate("Dialog", "报警车间")) self.label_2.setText(_translate("Dialog", "报警机器")) self.alert.setText(_translate("Dialog", "报警项目")) class Show_Text(QDialog, Ui_Dialog): def __init__(self, parent=None): super().__init__(parent) self.some_room = "" self.some_machine = "" self.some_project = "" print(self.some_room) print(self.some_machine) print(self.some_project) self.setupUi(self) self.show_text_thread = showtext_Thread(self.some_room,self.some_machine,self.some_project) self.show_text_thread.start() @pyqtSlot(str, str, str) def show_Data(self, room, machine, project):#数据更新 self.textBrowser.append(room) self.textBrowser_2.append(machine) self.textBrowser_3.append(project) class showtext_Thread(QtCore.QThread): trigger = QtCore.pyqtSignal(str,str,str) def __init__(self, room, machine, project, parent=None): super(showtext_Thread, self).__init__(parent) self.thread_room = room self.thread_machine = machine self.thread_project = project def run(self): print(self.thread_room) self.trigger.emit(self.thread_room,self.thread_machine,self.thread_project) time.sleep(1) def stop(self): self.quit() self.wait() ```

帮我运行一下PYQT5的界面代码,点击菜单中的打开,看是否弹出文件对话框

文件1: jiemian1.py ``` # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'jiemian1.ui' # # Created by: PyQt5 UI code generator 5.10.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(800, 600) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23)) self.menubar.setObjectName("menubar") self.menu_F = QtWidgets.QMenu(self.menubar) self.menu_F.setObjectName("menu_F") self.menu_E = QtWidgets.QMenu(self.menubar) self.menu_E.setObjectName("menu_E") self.menu_V = QtWidgets.QMenu(self.menubar) self.menu_V.setObjectName("menu_V") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.toolBar = QtWidgets.QToolBar(MainWindow) self.toolBar.setObjectName("toolBar") MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar) self.fileOpenAction = QtWidgets.QAction(MainWindow) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(":/tubiao/open.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.fileOpenAction.setIcon(icon) self.fileOpenAction.setObjectName("fileOpenAction") self.fileNewAction = QtWidgets.QAction(MainWindow) icon1 = QtGui.QIcon() icon1.addPixmap(QtGui.QPixmap(":/tubiao/new.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.fileNewAction.setIcon(icon1) self.fileNewAction.setObjectName("fileNewAction") self.fileCloseAction = QtWidgets.QAction(MainWindow) icon2 = QtGui.QIcon() icon2.addPixmap(QtGui.QPixmap(":/tubiao/close.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.fileCloseAction.setIcon(icon2) self.fileCloseAction.setObjectName("fileCloseAction") self.addWinaction = QtWidgets.QAction(MainWindow) self.addWinaction.setObjectName("addWinaction") self.menu_F.addAction(self.fileOpenAction) self.menu_F.addAction(self.fileNewAction) self.menu_F.addAction(self.fileCloseAction) self.menu_E.addSeparator() self.menubar.addAction(self.menu_F.menuAction()) self.menubar.addAction(self.menu_E.menuAction()) self.menubar.addAction(self.menu_V.menuAction()) self.toolBar.addAction(self.addWinaction) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "声学包数据库系统")) self.menu_F.setTitle(_translate("MainWindow", "文件(F)")) self.menu_E.setTitle(_translate("MainWindow", "编辑(E)")) self.menu_V.setTitle(_translate("MainWindow", "视图(V)")) self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar")) self.fileOpenAction.setText(_translate("MainWindow", "打开")) self.fileOpenAction.setShortcut(_translate("MainWindow", "Alt+O")) self.fileNewAction.setText(_translate("MainWindow", "新建")) self.fileNewAction.setShortcut(_translate("MainWindow", "Alt+C")) self.fileCloseAction.setText(_translate("MainWindow", "关闭")) self.fileCloseAction.setShortcut(_translate("MainWindow", "Alt+C")) self.addWinaction.setText(_translate("MainWindow", "添加窗体")) import ICON_rc ``` 文件2:calljiemian1.py ``` import sys from PyQt5.QtWidgets import * from jiemian1 import Ui_MainWindow class MainForm(QMainWindow,Ui_MainWindow): def __init__(self): super(MainForm,self).__init__() self.setupUi(self) self.fileCloseAction.triggered.connect(self.close) self.fileOpenAction.triggered.connect(self.openMsg) def openMsg(): print(1) file,ok= QFileDialog.getOpenFileName(self,"打开","E:\声学包数据库\声学包\界面测试数据","All Files (*);;Text Files (*.txt)") self.statusbar.showMessage(file) if __name__=="__main__": app= QApplication(sys.argv) win= MainForm() win.show() sys.exit(app.exec_()) ```

python+opencv+pyqt5 车牌批量识别报错

**单个儿车牌识别,代码运行成功,代码如下:** ``` from PyQt5 import QtCore,QtGui, QtWidgets from PyQt5.QtGui import * from PyQt5.QtCore import Qt from PyQt5.QtWidgets import * from Recognition import PlateRecognition import cv2 import sys, os, xlwt import numpy as np class Ui_MainWindow(object): def __init__(self): self.RowLength = 0 self.Data = [['文件名称', '录入时间', '车牌号码', '车牌类型', '识别耗时', '车牌信息']] def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(1213, 670) MainWindow.setFixedSize(1213, 670) # 设置窗体固定大小 MainWindow.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.scrollArea = QtWidgets.QScrollArea(self.centralwidget) self.scrollArea.setGeometry(QtCore.QRect(690, 10, 511, 491)) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName("scrollArea") self.scrollAreaWidgetContents = QtWidgets.QWidget() self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 509, 489)) self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents") self.label_0 = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.label_0.setGeometry(QtCore.QRect(10, 10, 111, 20)) font = QtGui.QFont() font.setPointSize(11) self.label_0.setFont(font) self.label_0.setObjectName("label_0") self.label = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.label.setGeometry(QtCore.QRect(10, 40, 481, 441)) self.label.setObjectName("label") self.label.setAlignment(Qt.AlignCenter) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.scrollArea_2 = QtWidgets.QScrollArea(self.centralwidget) self.scrollArea_2.setGeometry(QtCore.QRect(10, 10, 671, 631)) self.scrollArea_2.setWidgetResizable(True) self.scrollArea_2.setObjectName("scrollArea_2") self.scrollAreaWidgetContents_1 = QtWidgets.QWidget() self.scrollAreaWidgetContents_1.setGeometry(QtCore.QRect(0, 0, 669, 629)) self.scrollAreaWidgetContents_1.setObjectName("scrollAreaWidgetContents_1") self.label_1 = QtWidgets.QLabel(self.scrollAreaWidgetContents_1) self.label_1.setGeometry(QtCore.QRect(10, 10, 111, 20)) font = QtGui.QFont() font.setPointSize(11) self.label_1.setFont(font) self.label_1.setObjectName("label_1") self.tableWidget = QtWidgets.QTableWidget(self.scrollAreaWidgetContents_1) self.tableWidget.setGeometry(QtCore.QRect(10, 40, 651, 581)) # 581)) self.tableWidget.setObjectName("tableWidget") self.tableWidget.setColumnCount(6) self.tableWidget.setColumnWidth(0, 140) # 设置1列的宽度 self.tableWidget.setColumnWidth(1, 130) # 设置2列的宽度 self.tableWidget.setColumnWidth(2, 65) # 设置3列的宽度 self.tableWidget.setColumnWidth(3, 75) # 设置4列的宽度 self.tableWidget.setColumnWidth(4, 65) # 设置5列的宽度 self.tableWidget.setColumnWidth(5, 174) # 设置6列的宽度 self.tableWidget.setHorizontalHeaderLabels(["图片名称", "录入时间", "识别耗时", "车牌号码", "车牌类型", "车牌信息"]) self.tableWidget.setRowCount(self.RowLength) self.tableWidget.verticalHeader().setVisible(False) # 隐藏垂直表头) # self.tableWidget.setStyleSheet("selection-background-color:blue") # self.tableWidget.setAlternatingRowColors(True) self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers) self.tableWidget.raise_() self.scrollArea_2.setWidget(self.scrollAreaWidgetContents_1) self.scrollArea_3 = QtWidgets.QScrollArea(self.centralwidget) self.scrollArea_3.setGeometry(QtCore.QRect(690, 510, 341, 131)) self.scrollArea_3.setWidgetResizable(True) self.scrollArea_3.setObjectName("scrollArea_3") self.scrollAreaWidgetContents_3 = QtWidgets.QWidget() self.scrollAreaWidgetContents_3.setGeometry(QtCore.QRect(0, 0, 339, 129)) self.scrollAreaWidgetContents_3.setObjectName("scrollAreaWidgetContents_3") self.label_2 = QtWidgets.QLabel(self.scrollAreaWidgetContents_3) self.label_2.setGeometry(QtCore.QRect(10, 10, 111, 20)) font = QtGui.QFont() font.setPointSize(11) self.label_2.setFont(font) self.label_2.setObjectName("label_2") self.label_3 = QtWidgets.QLabel(self.scrollAreaWidgetContents_3) self.label_3.setGeometry(QtCore.QRect(10, 40, 321, 81)) self.label_3.setObjectName("label_3") self.scrollArea_3.setWidget(self.scrollAreaWidgetContents_3) self.scrollArea_4 = QtWidgets.QScrollArea(self.centralwidget) self.scrollArea_4.setGeometry(QtCore.QRect(1040, 510, 161, 131)) self.scrollArea_4.setWidgetResizable(True) self.scrollArea_4.setObjectName("scrollArea_4") self.scrollAreaWidgetContents_4 = QtWidgets.QWidget() self.scrollAreaWidgetContents_4.setGeometry(QtCore.QRect(0, 0, 159, 129)) self.scrollAreaWidgetContents_4.setObjectName("scrollAreaWidgetContents_4") self.pushButton_2 = QtWidgets.QPushButton(self.scrollAreaWidgetContents_4) self.pushButton_2.setGeometry(QtCore.QRect(20, 50, 121, 31)) self.pushButton_2.setObjectName("pushButton_2") self.pushButton = QtWidgets.QPushButton(self.scrollAreaWidgetContents_4) self.pushButton.setGeometry(QtCore.QRect(20, 90, 121, 31)) self.pushButton.setObjectName("pushButton") self.label_4 = QtWidgets.QLabel(self.scrollAreaWidgetContents_4) self.label_4.setGeometry(QtCore.QRect(10, 10, 111, 20)) font = QtGui.QFont() font.setPointSize(11) self.label_4.setFont(font) self.label_4.setObjectName("label_4") self.scrollArea_4.setWidget(self.scrollAreaWidgetContents_4) MainWindow.setCentralWidget(self.centralwidget) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) self.pushButton.clicked.connect(self.__openimage) # 设置点击事件 self.pushButton_2.clicked.connect(self.__writeFiles) # 设置点击事件 self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) self.ProjectPath = os.getcwd() # 获取当前工程文件位置 def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "车牌识别系统")) self.label_0.setText(_translate("MainWindow", "原始图片:")) self.label.setText(_translate("MainWindow", "")) self.label_1.setText(_translate("MainWindow", "识别结果:")) self.label_2.setText(_translate("MainWindow", "车牌区域:")) self.label_3.setText(_translate("MainWindow", "")) self.pushButton.setText(_translate("MainWindow", "打开文件")) self.pushButton_2.setText(_translate("MainWindow", "导出数据")) self.label_4.setText(_translate("MainWindow", "命令:")) self.scrollAreaWidgetContents_1.show() # 识别 def __vlpr(self, path): PR = PlateRecognition() result = PR.VLPR(path) return result def __show(self, result, FileName): # 显示表格 self.RowLength = self.RowLength + 1 if self.RowLength > 18: self.tableWidget.setColumnWidth(5, 157) self.tableWidget.setRowCount(self.RowLength) self.tableWidget.setItem(self.RowLength - 1, 0, QTableWidgetItem(FileName)) self.tableWidget.setItem(self.RowLength - 1, 1, QTableWidgetItem(result['InputTime'])) self.tableWidget.setItem(self.RowLength - 1, 2, QTableWidgetItem(str(result['UseTime']) + '秒')) self.tableWidget.setItem(self.RowLength - 1, 3, QTableWidgetItem(result['Number'])) self.tableWidget.setItem(self.RowLength - 1, 4, QTableWidgetItem(result['Type'])) if result['Type'] == '蓝色牌照': self.tableWidget.item(self.RowLength - 1, 4).setBackground(QBrush(QColor(3, 128, 255))) elif result['Type'] == '绿色牌照': self.tableWidget.item(self.RowLength - 1, 4).setBackground(QBrush(QColor(98, 198, 148))) elif result['Type'] == '黄色牌照': self.tableWidget.item(self.RowLength - 1, 4).setBackground(QBrush(QColor(242, 202, 9))) self.tableWidget.setItem(self.RowLength - 1, 5, QTableWidgetItem(result['From'])) # 显示识别到的车牌位置 size = (int(self.label_3.width()), int(self.label_3.height())) shrink = cv2.resize(result['Picture'], size, interpolation=cv2.INTER_AREA) shrink = cv2.cvtColor(shrink, cv2.COLOR_BGR2RGB) self.QtImg = QtGui.QImage(shrink[:], shrink.shape[1], shrink.shape[0], shrink.shape[1] * 3, QtGui.QImage.Format_RGB888) self.label_3.setPixmap(QtGui.QPixmap.fromImage(self.QtImg)) def __writexls(self, DATA, path): wb = xlwt.Workbook(); ws = wb.add_sheet('Data'); # DATA.insert(0, ['文件名称','录入时间', '车牌号码', '车牌类型', '识别耗时', '车牌信息']) for i, Data in enumerate(DATA): for j, data in enumerate(Data): ws.write(i, j, data) wb.save(path) QMessageBox.information(None, "成功", "数据已保存!", QMessageBox.Yes) def __writecsv(self, DATA, path): f = open(path, 'w') # DATA.insert(0, ['文件名称','录入时间', '车牌号码', '车牌类型', '识别耗时', '车牌信息']) for data in DATA: f.write((',').join(data) + '\n') f.close() QMessageBox.information(None, "成功", "数据已保存!", QMessageBox.Yes) def __writeFiles(self): path, filetype = QFileDialog.getSaveFileName(None, "另存为", self.ProjectPath, "Excel 工作簿(*.xls);;CSV (逗号分隔)(*.csv)") if path == "": # 未选择 return if filetype == 'Excel 工作簿(*.xls)': self.__writexls(self.Data, path) elif filetype == 'CSV (逗号分隔)(*.csv)': self.__writecsv(self.Data, path) def __openimage(self): path, filetype = QFileDialog.getOpenFileName(None, "选择文件", self.ProjectPath, "JPEG Image (*.jpg);;PNG Image (*.png);;JFIF Image (*.jfif)") # ;;All Files (*) if path == "": # 未选择文件 return filename = path.split('/')[-1] # 尺寸适配 size = cv2.imdecode(np.fromfile(path, dtype=np.uint8), cv2.IMREAD_COLOR).shape if size[0] / size[1] > 1.0907: w = size[1] * self.label.height() / size[0] h = self.label.height() jpg = QtGui.QPixmap(path).scaled(w, h) elif size[0] / size[1] < 1.0907: w = self.label.width() h = size[0] * self.label.width() / size[1] jpg = QtGui.QPixmap(path).scaled(w, h) else: jpg = QtGui.QPixmap(path).scaled(self.label.width(), self.label.height()) self.label.setPixmap(jpg) result = self.__vlpr(path) if result is not None: self.Data.append( [filename, result['InputTime'], result['Number'], result['Type'], str(result['UseTime']) + '秒', result['From']]) self.__show(result, filename) else: QMessageBox.warning(None, "Error", "无法识别此图像!", QMessageBox.Yes) # 重写MainWindow类 class MainWindow(QtWidgets.QMainWindow): def closeEvent(self, event): reply = QtWidgets.QMessageBox.question(self, '提示', "是否要退出程序?\n提示:退出后将丢失所有识别数据", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No) if reply == QtWidgets.QMessageBox.Yes: event.accept() else: event.ignore() if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) MainWindow = MainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) ``` **然后我在单个识别的基础上,增加了几行代码改成批量识别,红色框的是新添加的,其余代码没有改变** ![图片说明](https://img-ask.csdn.net/upload/202003/19/1584629478_989190.png) ![图片说明](https://img-ask.csdn.net/upload/202003/19/1584629493_573295.png) **程序报错:Process finished with exit code -1073740791 (0xC0000409)** ![图片说明](https://img-ask.csdn.net/upload/202003/19/1584629516_819110.png) 大佬们帮帮小白吧,这个增加批量识别的代码是否正确,这个错怎么改。感激不尽!

pyqt5中如何通过OpenCV读取一帧图像喂入网络呢?

我想通过pyqt5制作一个UI界面封装google object detection api的示例代码,源代码中是识别单张图片,我想通过摄像头输入一帧的图像然后进行识别显示。整个程序如下: ``` # coding:utf-8 ''' V3.0A版本,尝试实现摄像头识别 ''' import numpy as np import cv2 import os import os.path import six.moves.urllib as urllib import sys import tarfile import tensorflow as tf import zipfile import pylab from distutils.version import StrictVersion from collections import defaultdict from io import StringIO from matplotlib import pyplot as plt from PIL import Image from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * class UiForm(): openfile_name_pb = '' openfile_name_pbtxt = '' openpic_name = '' num_class = 0 def setupUi(self, Form): Form.setObjectName("Form") Form.resize(600, 690) Form.setMinimumSize(QtCore.QSize(600, 690)) Form.setMaximumSize(QtCore.QSize(600, 690)) self.frame = QtWidgets.QFrame(Form) self.frame.setGeometry(QtCore.QRect(20, 20, 550, 100)) self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame.setFrameShadow(QtWidgets.QFrame.Raised) self.frame.setObjectName("frame") self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.frame) self.horizontalLayout_2.setObjectName("horizontalLayout_2") # 加载模型文件按钮 self.btn_add_file = QtWidgets.QPushButton(self.frame) self.btn_add_file.setObjectName("btn_add_file") self.horizontalLayout_2.addWidget(self.btn_add_file) # 加载pbtxt文件按钮 self.btn_add_pbtxt = QtWidgets.QPushButton(self.frame) self.btn_add_pbtxt.setObjectName("btn_add_pbtxt") self.horizontalLayout_2.addWidget(self.btn_add_pbtxt) # 输入检测类别数目按钮 self.btn_enter = QtWidgets.QPushButton(self.frame) self.btn_enter.setObjectName("btn_enter") self.horizontalLayout_2.addWidget(self.btn_enter) # 打开摄像头 self.btn_opencam = QtWidgets.QPushButton(self.frame) self.btn_opencam.setObjectName("btn_objdec") self.horizontalLayout_2.addWidget(self.btn_opencam) # 开始识别按钮 self.btn_objdec = QtWidgets.QPushButton(self.frame) self.btn_objdec.setObjectName("btn_objdec") self.horizontalLayout_2.addWidget(self.btn_objdec) # 退出按钮 self.btn_exit = QtWidgets.QPushButton(self.frame) self.btn_exit.setObjectName("btn_exit") self.horizontalLayout_2.addWidget(self.btn_exit) # 显示识别后的画面 self.lab_rawimg_show = QtWidgets.QLabel(Form) self.lab_rawimg_show.setGeometry(QtCore.QRect(50, 140, 500, 500)) self.lab_rawimg_show.setMinimumSize(QtCore.QSize(500, 500)) self.lab_rawimg_show.setMaximumSize(QtCore.QSize(500, 500)) self.lab_rawimg_show.setObjectName("lab_rawimg_show") self.lab_rawimg_show.setStyleSheet(("border:2px solid red")) self.retranslateUi(Form) # 这里将按钮和定义的动作相连,通过click信号连接openfile槽? self.btn_add_file.clicked.connect(self.openpb) # 用于打开pbtxt文件 self.btn_add_pbtxt.clicked.connect(self.openpbtxt) # 用于用户输入类别数 self.btn_enter.clicked.connect(self.enter_num_cls) # 打开摄像头 self.btn_opencam.clicked.connect(self.opencam) # 开始识别 # ~ self.btn_objdec.clicked.connect(self.object_detection) # 这里是将btn_exit按钮和Form窗口相连,点击按钮发送关闭窗口命令 self.btn_exit.clicked.connect(Form.close) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "目标检测")) self.btn_add_file.setText(_translate("Form", "加载模型文件")) self.btn_add_pbtxt.setText(_translate("Form", "加载pbtxt文件")) self.btn_enter.setText(_translate("From", "指定识别类别数")) self.btn_opencam.setText(_translate("Form", "打开摄像头")) self.btn_objdec.setText(_translate("From", "开始识别")) self.btn_exit.setText(_translate("Form", "退出")) self.lab_rawimg_show.setText(_translate("Form", "识别效果")) def openpb(self): global openfile_name_pb openfile_name_pb, _ = QFileDialog.getOpenFileName(self.btn_add_file,'选择pb文件','/home/kanghao/','pb_files(*.pb)') print('加载模型文件地址为:' + str(openfile_name_pb)) def openpbtxt(self): global openfile_name_pbtxt openfile_name_pbtxt, _ = QFileDialog.getOpenFileName(self.btn_add_pbtxt,'选择pbtxt文件','/home/kanghao/','pbtxt_files(*.pbtxt)') print('加载标签文件地址为:' + str(openfile_name_pbtxt)) def opencam(self): self.camcapture = cv2.VideoCapture(0) self.timer = QtCore.QTimer() self.timer.start() self.timer.setInterval(100) # 0.1s刷新一次 self.timer.timeout.connect(self.camshow) def camshow(self): global camimg _ , camimg = self.camcapture.read() print(_) camimg = cv2.resize(camimg, (512, 512)) camimg = cv2.cvtColor(camimg, cv2.COLOR_BGR2RGB) print(type(camimg)) #strcamimg = camimg.tostring() showImage = QtGui.QImage(camimg.data, camimg.shape[1], camimg.shape[0], QtGui.QImage.Format_RGB888) self.lab_rawimg_show.setPixmap(QtGui.QPixmap.fromImage(showImage)) def enter_num_cls(self): global num_class num_class, okPressed = QInputDialog.getInt(self.btn_enter,'指定训练类别数','你的目标有多少类?',1,1,28,1) if okPressed: print('识别目标总类为:' + str(num_class)) def img2pixmap(self, image): Y, X = image.shape[:2] self._bgra = np.zeros((Y, X, 4), dtype=np.uint8, order='C') self._bgra[..., 0] = image[..., 2] self._bgra[..., 1] = image[..., 1] self._bgra[..., 2] = image[..., 0] qimage = QtGui.QImage(self._bgra.data, X, Y, QtGui.QImage.Format_RGB32) pixmap = QtGui.QPixmap.fromImage(qimage) return pixmap def object_detection(self): sys.path.append("..") from object_detection.utils import ops as utils_ops if StrictVersion(tf.__version__) < StrictVersion('1.9.0'): raise ImportError('Please upgrade your TensorFlow installation to v1.9.* or later!') from utils import label_map_util from utils import visualization_utils as vis_util # Path to frozen detection graph. This is the actual model that is used for the object detection. PATH_TO_FROZEN_GRAPH = openfile_name_pb # List of the strings that is used to add correct label for each box. PATH_TO_LABELS = openfile_name_pbtxt NUM_CLASSES = num_class detection_graph = tf.Graph() with detection_graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='') category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True) def load_image_into_numpy_array(image): (im_width, im_height) = image.size return np.array(image.getdata()).reshape( (im_height, im_width, 3)).astype(np.uint8) # For the sake of simplicity we will use only 2 images: # image1.jpg # image2.jpg # If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS. TEST_IMAGE_PATHS = camimg print(TEST_IMAGE_PATHS) # Size, in inches, of the output images. IMAGE_SIZE = (12, 8) def run_inference_for_single_image(image, graph): with graph.as_default(): with tf.Session() as sess: # Get handles to input and output tensors ops = tf.get_default_graph().get_operations() all_tensor_names = {output.name for op in ops for output in op.outputs} tensor_dict = {} for key in [ 'num_detections', 'detection_boxes', 'detection_scores', 'detection_classes', 'detection_masks' ]: tensor_name = key + ':0' if tensor_name in all_tensor_names: tensor_dict[key] = tf.get_default_graph().get_tensor_by_name( tensor_name) if 'detection_masks' in tensor_dict: # The following processing is only for single image detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0]) detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0]) # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size. real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32) detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1]) detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1]) detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks( detection_masks, detection_boxes, image.shape[0], image.shape[1]) detection_masks_reframed = tf.cast( tf.greater(detection_masks_reframed, 0.5), tf.uint8) # Follow the convention by adding back the batch dimension tensor_dict['detection_masks'] = tf.expand_dims( detection_masks_reframed, 0) image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0') # Run inference output_dict = sess.run(tensor_dict, feed_dict={image_tensor: np.expand_dims(image, 0)}) # all outputs are float32 numpy arrays, so convert types as appropriate output_dict['num_detections'] = int(output_dict['num_detections'][0]) output_dict['detection_classes'] = output_dict[ 'detection_classes'][0].astype(np.uint8) output_dict['detection_boxes'] = output_dict['detection_boxes'][0] output_dict['detection_scores'] = output_dict['detection_scores'][0] if 'detection_masks' in output_dict: output_dict['detection_masks'] = output_dict['detection_masks'][0] return output_dict #image = Image.open(TEST_IMAGE_PATHS) # the array based representation of the image will be used later in order to prepare the # result image with boxes and labels on it. image_np = load_image_into_numpy_array(TEST_IMAGE_PATHS) # Expand dimensions since the model expects images to have shape: [1, None, None, 3] image_np_expanded = np.expand_dims(image_np, axis=0) # Actual detection. output_dict = run_inference_for_single_image(image_np, detection_graph) # Visualization of the results of a detection. vis_util.visualize_boxes_and_labels_on_image_array( image_np, output_dict['detection_boxes'], output_dict['detection_classes'], output_dict['detection_scores'], category_index, instance_masks=output_dict.get('detection_masks'), use_normalized_coordinates=True, line_thickness=8) plt.figure(figsize=IMAGE_SIZE) plt.imshow(image_np) #plt.savefig(str(TEST_IMAGE_PATHS)+".jpg") ## 用于显示ui界面的命令 if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) Window = QtWidgets.QWidget() # ui为根据类Ui_From()创建的实例 ui = UiForm() ui.setupUi(Window) Window.show() sys.exit(app.exec_()) ``` 但是运行提示: ![图片说明](https://img-ask.csdn.net/upload/201811/30/1543567054_511116.png) 求助

为什么点击按钮后直接关闭窗口了,没有弹出对话框呢?

**为什么点击按钮后直接关闭窗口了,没有弹出对话框呢?** ``` # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'frmMain.ui' # # Created by: PyQt5 UI code generator 5.5.1 # # WARNING! All changes made in this file will be lost! import sys from PyQt5.QtWidgets import QApplication , QMainWindow from PyQt5 import QtCore, QtGui, QtWidgets class Ui_frmMain(object): def setupUi(self, frmMain): frmMain.setObjectName("frmMain") frmMain.resize(415, 265) self.centralwidget = QtWidgets.QWidget(frmMain) self.centralwidget.setObjectName("centralwidget") self.btnFirst = QtWidgets.QPushButton(self.centralwidget) self.btnFirst.setGeometry(QtCore.QRect(150, 70, 75, 23)) self.btnFirst.setObjectName("btnFirst") frmMain.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(frmMain) self.menubar.setGeometry(QtCore.QRect(0, 0, 415, 23)) self.menubar.setObjectName("menubar") frmMain.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(frmMain) self.statusbar.setObjectName("statusbar") frmMain.setStatusBar(self.statusbar) self.retranslateUi(frmMain) self.btnFirst.clicked.connect(self.btnFirstClike) QtCore.QMetaObject.connectSlotsByName(frmMain) def retranslateUi(self, frmMain): _translate = QtCore.QCoreApplication.translate frmMain.setWindowTitle(_translate("frmMain", "我的第一个窗口")) self.btnFirst.setText(_translate("frmMain", "第一个按钮")) def btnFirstClike(self): QtWidgets.QMessageBox.about(self,"测试","点击弹出窗口成功") if __name__ == '__main__': ''' 主函数 ''' app = QApplication(sys.argv) mainWindow = QMainWindow() ui = Ui_frmMain() ui.setupUi(mainWindow) mainWindow.show() sys.exit(app.exec_()) ```

Qt designer设计菜单,打开文件对话框,编写好逻辑后,点击打开文件,没弹出对话框,且程序退出

界面文件: # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'jiemian1.ui' # # Created by: PyQt5 UI code generator 5.10.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(800, 600) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23)) self.menubar.setObjectName("menubar") self.menu_F = QtWidgets.QMenu(self.menubar) self.menu_F.setObjectName("menu_F") self.menu_E = QtWidgets.QMenu(self.menubar) self.menu_E.setObjectName("menu_E") self.menu_V = QtWidgets.QMenu(self.menubar) self.menu_V.setObjectName("menu_V") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.toolBar = QtWidgets.QToolBar(MainWindow) self.toolBar.setObjectName("toolBar") MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar) self.fileOpenAction = QtWidgets.QAction(MainWindow) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(":/tubiao/open.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.fileOpenAction.setIcon(icon) self.fileOpenAction.setObjectName("fileOpenAction") self.fileNewAction = QtWidgets.QAction(MainWindow) icon1 = QtGui.QIcon() icon1.addPixmap(QtGui.QPixmap(":/tubiao/new.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.fileNewAction.setIcon(icon1) self.fileNewAction.setObjectName("fileNewAction") self.fileCloseAction = QtWidgets.QAction(MainWindow) icon2 = QtGui.QIcon() icon2.addPixmap(QtGui.QPixmap(":/tubiao/close.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.fileCloseAction.setIcon(icon2) self.fileCloseAction.setObjectName("fileCloseAction") self.addWinaction = QtWidgets.QAction(MainWindow) self.addWinaction.setObjectName("addWinaction") self.menu_F.addAction(self.fileOpenAction) self.menu_F.addAction(self.fileNewAction) self.menu_F.addAction(self.fileCloseAction) self.menu_E.addSeparator() self.menubar.addAction(self.menu_F.menuAction()) self.menubar.addAction(self.menu_E.menuAction()) self.menubar.addAction(self.menu_V.menuAction()) self.toolBar.addAction(self.addWinaction) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "声学包数据库系统")) self.menu_F.setTitle(_translate("MainWindow", "文件(F)")) self.menu_E.setTitle(_translate("MainWindow", "编辑(E)")) self.menu_V.setTitle(_translate("MainWindow", "视图(V)")) self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar")) self.fileOpenAction.setText(_translate("MainWindow", "打开")) self.fileOpenAction.setShortcut(_translate("MainWindow", "Alt+O")) self.fileNewAction.setText(_translate("MainWindow", "新建")) self.fileNewAction.setShortcut(_translate("MainWindow", "Alt+C")) self.fileCloseAction.setText(_translate("MainWindow", "关闭")) self.fileCloseAction.setShortcut(_translate("MainWindow", "Alt+C")) self.addWinaction.setText(_translate("MainWindow", "添加窗体")) import ICON_rc 逻辑文件: import sys from PyQt5.QtWidgets import * from jiemian1 import Ui_MainWindow class MainForm(QMainWindow,Ui_MainWindow): def __init__(self): super(MainForm,self).__init__() self.setupUi(self) self.fileCloseAction.triggered.connect(self.close) self.fileOpenAction.triggered.connect(self.openMsg) def openMsg(): file,ok= QFileDialog.getOpenFileName(self,"打开","E:\声学包数据库\声学包\界面测试数据","All Files (*);;Text Files (*.txt)") self.statusbar.showMessage(file) if __name__=="__main__": app= QApplication(sys.argv) win= MainForm() win.show() sys.exit(app.exec_())

为什么这段代码运行后显示:进程已结束,退出代码0,却没有我设计的窗口出现,求解决??

# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'jinhang.ui' # # Created by: PyQt5 UI code generator 5.13.0 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(800, 600) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(30, 40, 71, 31)) self.label.setObjectName("label") self.label_2 = QtWidgets.QLabel(self.centralwidget) self.label_2.setGeometry(QtCore.QRect(30, 100, 91, 21)) self.label_2.setObjectName("label_2") self.label_3 = QtWidgets.QLabel(self.centralwidget) self.label_3.setGeometry(QtCore.QRect(30, 140, 61, 21)) self.label_3.setObjectName("label_3") self.label_4 = QtWidgets.QLabel(self.centralwidget) self.label_4.setGeometry(QtCore.QRect(180, 140, 61, 16)) self.label_4.setObjectName("label_4") self.label_5 = QtWidgets.QLabel(self.centralwidget) self.label_5.setGeometry(QtCore.QRect(30, 180, 51, 21)) self.label_5.setObjectName("label_5") self.label_6 = QtWidgets.QLabel(self.centralwidget) self.label_6.setGeometry(QtCore.QRect(30, 210, 71, 31)) self.label_6.setObjectName("label_6") self.label_7 = QtWidgets.QLabel(self.centralwidget) self.label_7.setGeometry(QtCore.QRect(190, 210, 71, 31)) self.label_7.setObjectName("label_7") self.label_8 = QtWidgets.QLabel(self.centralwidget) self.label_8.setGeometry(QtCore.QRect(30, 250, 71, 21)) self.label_8.setObjectName("label_8") self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(80, 490, 75, 23)) self.pushButton.setObjectName("pushButton") self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_2.setGeometry(QtCore.QRect(220, 490, 75, 23)) self.pushButton_2.setObjectName("pushButton_2") self.textEdit = QtWidgets.QTextEdit(self.centralwidget) self.textEdit.setGeometry(QtCore.QRect(100, 40, 71, 31)) self.textEdit.setObjectName("textEdit") self.textEdit_2 = QtWidgets.QTextEdit(self.centralwidget) self.textEdit_2.setGeometry(QtCore.QRect(180, 40, 71, 31)) self.textEdit_2.setObjectName("textEdit_2") self.textEdit_3 = QtWidgets.QTextEdit(self.centralwidget) self.textEdit_3.setGeometry(QtCore.QRect(260, 40, 71, 31)) self.textEdit_3.setObjectName("textEdit_3") self.textEdit_4 = QtWidgets.QTextEdit(self.centralwidget) self.textEdit_4.setGeometry(QtCore.QRect(90, 130, 71, 31)) self.textEdit_4.setObjectName("textEdit_4") self.textEdit_5 = QtWidgets.QTextEdit(self.centralwidget) self.textEdit_5.setGeometry(QtCore.QRect(240, 130, 71, 31)) self.textEdit_5.setObjectName("textEdit_5") self.textEdit_6 = QtWidgets.QTextEdit(self.centralwidget) self.textEdit_6.setGeometry(QtCore.QRect(100, 210, 71, 31)) self.textEdit_6.setObjectName("textEdit_6") self.textEdit_7 = QtWidgets.QTextEdit(self.centralwidget) self.textEdit_7.setGeometry(QtCore.QRect(260, 210, 71, 31)) self.textEdit_7.setObjectName("textEdit_7") self.plainTextEdit = QtWidgets.QPlainTextEdit(self.centralwidget) self.plainTextEdit.setGeometry(QtCore.QRect(380, 0, 351, 551)) self.plainTextEdit.setObjectName("plainTextEdit") self.plainTextEdit_2 = QtWidgets.QPlainTextEdit(self.centralwidget) self.plainTextEdit_2.setGeometry(QtCore.QRect(30, 270, 341, 211)) self.plainTextEdit_2.setObjectName("plainTextEdit_2") self.verticalScrollBar = QtWidgets.QScrollBar(self.centralwidget) self.verticalScrollBar.setGeometry(QtCore.QRect(710, 0, 16, 551)) self.verticalScrollBar.setOrientation(QtCore.Qt.Vertical) self.verticalScrollBar.setObjectName("verticalScrollBar") 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.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.label.setText(_translate("MainWindow", "aa号:")) self.label_2.setText(_translate("MainWindow", "时间段:")) self.label_3.setText(_translate("MainWindow", "开始时间:")) self.label_4.setText(_translate("MainWindow", "结束时间:")) self.label_5.setText(_translate("MainWindow", "bb段:")) self.label_6.setText(_translate("MainWindow", "开始点:")) self.label_7.setText(_translate("MainWindow", "结束点:")) self.label_8.setText(_translate("MainWindow", "分析结果:")) self.pushButton.setText(_translate("MainWindow", "清 除")) self.pushButton_2.setText(_translate("MainWindow", "开始分析")) if __name__ == "MainWindow": import sys app = QtWidgets.QApplication(sys.argv) widget = QtWidgets.QWidget() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())

python运行出来的界面与Qt designer预览的不一致

刚接触python,如题,python designer设计出的页面与用python 调用后显示的不一致,求问大神这个是什么问题,怎么解决。 #1. Qt designed预览界面 ![图片说明](https://img-ask.csdn.net/upload/202006/25/1593084413_259104.png) 转化后的window.py文件见后文 # 2.python 运行main.py文件如图 ![图片说明](https://img-ask.csdn.net/upload/202006/25/1593084788_255092.png) # 3.main.py的代码 其中QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)这一句注释掉也一个效果 ``` # -*- coding: utf-8 -*- import sys from PyQt5.QtWidgets import QApplication, QMainWindow from PyQt5 import QtCore #导入designer工具生成的window模块 from window import Ui_Form #定义一个主窗口类,继承了QMainWindow及Ui_Form class MainWindow(QMainWindow, Ui_Form): def __init__(self, parent = None): super(MainWindow, self).__init__(parent) self.setupUi(self) if __name__ == '__main__': QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling) # 固定的,PyQt5程序都需要QApplication对象。sys.argv是命令行参数列表,确保程序可以双击运行 movieDownLoadApp = QApplication(sys.argv) mainWindow = MainWindow() mainWindow.show() # 程序运行,sys.exit方法确保程序完整退出。 sys.exit(movieDownLoadApp.exec_()) ``` # 4.window.py的文件是ui转过来的 ``` from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(690, 552) self.verticalLayout_5 = QtWidgets.QVBoxLayout(Form) self.verticalLayout_5.setObjectName("verticalLayout_5") self.gridLayout = QtWidgets.QGridLayout() self.gridLayout.setObjectName("gridLayout") self.MovieDownload_2 = QtWidgets.QSplitter(Form) self.MovieDownload_2.setOrientation(QtCore.Qt.Horizontal) self.MovieDownload_2.setObjectName("MovieDownload_2") self.label_13 = QtWidgets.QLabel(self.MovieDownload_2) self.label_13.setObjectName("label_13") self.layoutWidget_3 = QtWidgets.QWidget(self.MovieDownload_2) self.layoutWidget_3.setObjectName("layoutWidget_3") self.verticalLayout_6 = QtWidgets.QVBoxLayout(self.layoutWidget_3) self.verticalLayout_6.setContentsMargins(0, 0, 0, 0) self.verticalLayout_6.setObjectName("verticalLayout_6") self.gridLayout_5 = QtWidgets.QGridLayout() self.gridLayout_5.setObjectName("gridLayout_5") self.label_14 = QtWidgets.QLabel(self.layoutWidget_3) self.label_14.setObjectName("label_14") self.gridLayout_5.addWidget(self.label_14, 0, 0, 1, 1) self.lineEdit_9 = QtWidgets.QLineEdit(self.layoutWidget_3) self.lineEdit_9.setObjectName("lineEdit_9") self.gridLayout_5.addWidget(self.lineEdit_9, 1, 1, 1, 1) self.label_15 = QtWidgets.QLabel(self.layoutWidget_3) self.label_15.setObjectName("label_15") self.gridLayout_5.addWidget(self.label_15, 1, 0, 1, 1) self.lineEdit_10 = QtWidgets.QLineEdit(self.layoutWidget_3) self.lineEdit_10.setObjectName("lineEdit_10") self.gridLayout_5.addWidget(self.lineEdit_10, 0, 1, 1, 1) self.verticalLayout_6.addLayout(self.gridLayout_5) self.horizontalLayout_5 = QtWidgets.QHBoxLayout() self.horizontalLayout_5.setObjectName("horizontalLayout_5") self.pushButton_9 = QtWidgets.QPushButton(self.layoutWidget_3) self.pushButton_9.setObjectName("pushButton_9") self.horizontalLayout_5.addWidget(self.pushButton_9) self.pushButton_10 = QtWidgets.QPushButton(self.layoutWidget_3) self.pushButton_10.setObjectName("pushButton_10") self.horizontalLayout_5.addWidget(self.pushButton_10) self.verticalLayout_6.addLayout(self.horizontalLayout_5) self.gridLayout.addWidget(self.MovieDownload_2, 0, 0, 1, 1) self.line = QtWidgets.QFrame(Form) self.line.setFrameShape(QtWidgets.QFrame.HLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName("line") self.gridLayout.addWidget(self.line, 1, 0, 1, 1) self.line_2 = QtWidgets.QFrame(Form) self.line_2.setFrameShape(QtWidgets.QFrame.HLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName("line_2") self.gridLayout.addWidget(self.line_2, 2, 0, 1, 1) self.MovieDownload = QtWidgets.QSplitter(Form) self.MovieDownload.setOrientation(QtCore.Qt.Horizontal) self.MovieDownload.setObjectName("MovieDownload") self.label_4 = QtWidgets.QLabel(self.MovieDownload) self.label_4.setObjectName("label_4") self.layoutWidget = QtWidgets.QWidget(self.MovieDownload) self.layoutWidget.setObjectName("layoutWidget") self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.layoutWidget) self.verticalLayout_2.setContentsMargins(0, 0, 0, 0) self.verticalLayout_2.setObjectName("verticalLayout_2") self.gridLayout_3 = QtWidgets.QGridLayout() self.gridLayout_3.setObjectName("gridLayout_3") self.label_8 = QtWidgets.QLabel(self.layoutWidget) self.label_8.setObjectName("label_8") self.gridLayout_3.addWidget(self.label_8, 0, 0, 1, 1) self.lineEdit_5 = QtWidgets.QLineEdit(self.layoutWidget) self.lineEdit_5.setObjectName("lineEdit_5") self.gridLayout_3.addWidget(self.lineEdit_5, 1, 1, 1, 1) self.label_9 = QtWidgets.QLabel(self.layoutWidget) self.label_9.setObjectName("label_9") self.gridLayout_3.addWidget(self.label_9, 1, 0, 1, 1) self.lineEdit_6 = QtWidgets.QLineEdit(self.layoutWidget) self.lineEdit_6.setObjectName("lineEdit_6") self.gridLayout_3.addWidget(self.lineEdit_6, 0, 1, 1, 1) self.verticalLayout_2.addLayout(self.gridLayout_3) self.horizontalLayout_3 = QtWidgets.QHBoxLayout() self.horizontalLayout_3.setObjectName("horizontalLayout_3") self.pushButton_5 = QtWidgets.QPushButton(self.layoutWidget) self.pushButton_5.setObjectName("pushButton_5") self.horizontalLayout_3.addWidget(self.pushButton_5) self.pushButton_6 = QtWidgets.QPushButton(self.layoutWidget) self.pushButton_6.setObjectName("pushButton_6") self.horizontalLayout_3.addWidget(self.pushButton_6) self.verticalLayout_2.addLayout(self.horizontalLayout_3) self.gridLayout.addWidget(self.MovieDownload, 3, 0, 1, 1) self.verticalLayout = QtWidgets.QVBoxLayout() self.verticalLayout.setObjectName("verticalLayout") self.label = QtWidgets.QLabel(Form) self.label.setObjectName("label") self.verticalLayout.addWidget(self.label) self.textBrowser = QtWidgets.QTextBrowser(Form) self.textBrowser.setObjectName("textBrowser") self.verticalLayout.addWidget(self.textBrowser) self.gridLayout.addLayout(self.verticalLayout, 4, 0, 1, 1) self.verticalLayout_5.addLayout(self.gridLayout) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "MovieDownloadAndTrans")) self.label_13.setText(_translate("Form", "<html><head/><body><p align=\"center\"><span style=\" font-size:20pt; font-weight:600;\">视频下载</span></p></body></html>")) self.label_14.setText(_translate("Form", "视频地址")) self.label_15.setText(_translate("Form", "保存目录")) self.pushButton_9.setText(_translate("Form", "PushButton")) self.pushButton_10.setText(_translate("Form", "PushButton")) self.label_4.setText(_translate("Form", "<html><head/><body><p align=\"center\"><span style=\" font-size:20pt; font-weight:600;\">格式转换</span></p></body></html>")) self.label_8.setText(_translate("Form", "文件路径")) self.label_9.setText(_translate("Form", "输出路径")) self.pushButton_5.setText(_translate("Form", "PushButton")) self.pushButton_6.setText(_translate("Form", "PushButton")) self.label.setText(_translate("Form", "<html><head/><body><p align=\"center\"><span style=\" font-size:20pt; font-weight:600;\">状态</span></p></body></html>")) ```

QtCore调用冲突的问题

``` objc[13122]: Class QMacAutoReleasePoolTracker is implemented in both /usr/local/lib/python3.7/site-packages/cv2/.dylibs/QtCore (0x117007700) and /usr/local/lib/python3.7/site-packages/PyQt5/Qt/lib/QtCore.framework/Versions/5/QtCore (0x12f986030). One of the two will be used. Which one is undefined. ``` 之前程序运行一直正常,今天安装了opencv-contrib-python包后就显示上述问题,意思就是现在有两个QtCore,程序不知道使用哪一个,有没有大神出来指点一下。 我安装opencv-contrib-python的原因是 cv2.face.LBPHFaceRecognizer_create()抛出异常,网上说是需要安装opencv-contrib-python包。

python调用摄像头动态更新三维灰度分布图

我想python调用摄像头动态更新三维灰度分布图,但发现在绘制的时候,前面绘制的图像不会被擦掉,而是重叠在一起,这要怎么改呢? ``` from DataDisplayUI import Ui_MainWindow from PyQt5.QtWidgets import QApplication,QMainWindow,QGridLayout from PyQt5.QtCore import QTimer import sys,time import cv2 import numpy as np import cv2 as cv from mpl_toolkits.mplot3d import Axes3D from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure from matplotlib.lines import Line2D import matplotlib import matplotlib.cbook as cbook class Figure_Canvas(FigureCanvas): def __init__(self,parent=None,width=3.9,height=2.7,dpi=100): self.fig=Figure(figsize=(width,height),dpi=50) #创建画布 super(Figure_Canvas,self).__init__(self.fig) # self.ax=self.fig.add_subplot() #创建子图 class ImgDisp(QMainWindow,Ui_MainWindow): def __init__(self,parent=None): super(ImgDisp,self).__init__(parent) self.setupUi(self) self.Init_Widgets() self.video_start() self.timer=QTimer() #QTimer定时器 self.timer.start(1000) #timer方法,开始执行,1代表循环周期 self.timer.timeout.connect(self.SurfUpdate) #连接到槽UpdateImgs,循环函数体 def Init_Widgets(self): self.PrepareSamples() self.PrepareSurfaceCanvas() def PrepareSamples(self): self.x = np.arange(-4, 4, 0.02) self.y = np.arange(-4, 4, 0.02) self.X, self.Y = np.meshgrid(self.x, self.y) self.z = np.sin(self.x) self.R = np.sqrt(self.X ** 2 + self.Y ** 2) self.Z = np.sin(self.R) def PrepareSurfaceCanvas(self): self.SurfFigure = Figure_Canvas() self.SurfFigureLayout = QGridLayout(self.SurfaceDisplayGB) self.SurfFigureLayout.addWidget(self.SurfFigure) self.SurfFigure.ax.remove() self.ax3d = self.SurfFigure.fig.gca(projection='3d') def video_start(self): self.cap = cv2.VideoCapture(0) # 打开摄像头,0代表的是设备id,如果有多个摄像头,可以设置其他数值 self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280) # 调节视频分辨率 self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) self.cap.set(cv2.CAP_PROP_SATURATION, 10) # 调节曝光 def SurfUpdate(self): ret, frame = self.cap.read() # 读取摄像头,它能返回两个参数,第一个参数是bool型的ret,其值为True或False,代表有没有读到图片;第二个参数是frame,是当前截取一帧的图片 img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # 转灰度图 img= cv2.GaussianBlur(img, (5, 5), 0) #高斯滤波 img_date = np.array(img) # 每一帧存入循环数组 # 准备数据 sp = img_date.shape h = int(sp[0]) w = int(sp[1]) X = np.arange(0, w, 1) Y = np.arange(0, h, 1) X, Y = np.meshgrid(X, Y) Z = img_date self.Surf = self.ax3d.plot_surface(X, Y, Z, cmap='rainbow') self.SurfFigure.draw() if __name__=='__main__': app=QApplication(sys.argv) #创建一个应用程序对象 ui=ImgDisp() ui.show() sys.exit(app.exec_()) #退出 ```

用qtdesign弄出来gui怎么接入功能?

# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'C:\Users\yantao\PycharmProjects\untitled14\venv\untitled.ui' # # Created by: PyQt5 UI code generator 5.12 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_mainWindow(object): def setupUi(self, mainWindow): mainWindow.setObjectName("mainWindow") mainWindow.resize(796, 598) self.centralwidget = QtWidgets.QWidget(mainWindow) self.centralwidget.setObjectName("centralwidget") self.listView = QtWidgets.QListView(self.centralwidget) self.listView.setGeometry(QtCore.QRect(290, 300, 481, 192)) self.listView.setObjectName("listView") self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(290, 280, 91, 16)) self.label.setObjectName("label") self.label_2 = QtWidgets.QLabel(self.centralwidget) self.label_2.setGeometry(QtCore.QRect(10, 100, 54, 12)) self.label_2.setObjectName("label_2") self.label_3 = QtWidgets.QLabel(self.centralwidget) self.label_3.setGeometry(QtCore.QRect(10, 140, 54, 12)) self.label_3.setObjectName("label_3") self.textBrowser = QtWidgets.QTextBrowser(self.centralwidget) self.textBrowser.setGeometry(QtCore.QRect(70, 90, 81, 31)) self.textBrowser.setObjectName("textBrowser") self.textBrowser_2 = QtWidgets.QTextBrowser(self.centralwidget) self.textBrowser_2.setGeometry(QtCore.QRect(70, 130, 81, 31)) self.textBrowser_2.setObjectName("textBrowser_2") self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(290, 510, 91, 41)) self.pushButton.setObjectName("pushButton") self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_2.setGeometry(QtCore.QRect(20, 290, 75, 23)) self.pushButton_2.setObjectName("pushButton_2") self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_3.setGeometry(QtCore.QRect(20, 490, 75, 23)) self.pushButton_3.setObjectName("pushButton_3") self.openGLWidget = QtWidgets.QOpenGLWidget(self.centralwidget) self.openGLWidget.setGeometry(QtCore.QRect(290, -10, 471, 281)) self.openGLWidget.setObjectName("openGLWidget") self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_4.setGeometry(QtCore.QRect(210, 110, 75, 23)) self.pushButton_4.setObjectName("pushButton_4") self.radioButton = QtWidgets.QRadioButton(self.centralwidget) self.radioButton.setGeometry(QtCore.QRect(10, 50, 125, 16)) self.radioButton.setObjectName("radioButton") self.radioButton_2 = QtWidgets.QRadioButton(self.centralwidget) self.radioButton_2.setGeometry(QtCore.QRect(10, 20, 119, 16)) self.radioButton_2.setObjectName("radioButton_2") self.horizontalSlider = QtWidgets.QSlider(self.centralwidget) self.horizontalSlider.setGeometry(QtCore.QRect(120, 390, 141, 22)) self.horizontalSlider.setOrientation(QtCore.Qt.Horizontal) self.horizontalSlider.setObjectName("horizontalSlider") self.label_4 = QtWidgets.QLabel(self.centralwidget) self.label_4.setGeometry(QtCore.QRect(30, 380, 41, 31)) self.label_4.setObjectName("label_4") mainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(mainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 796, 23)) self.menubar.setObjectName("menubar") self.menufile = QtWidgets.QMenu(self.menubar) self.menufile.setObjectName("menufile") self.menu_2 = QtWidgets.QMenu(self.menubar) self.menu_2.setObjectName("menu_2") self.menu_3 = QtWidgets.QMenu(self.menubar) self.menu_3.setObjectName("menu_3") self.menu_4 = QtWidgets.QMenu(self.menubar) self.menu_4.setObjectName("menu_4") self.menu_5 = QtWidgets.QMenu(self.menubar) self.menu_5.setObjectName("menu_5") mainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(mainWindow) self.statusbar.setObjectName("statusbar") mainWindow.setStatusBar(self.statusbar) self.actionopen = QtWidgets.QAction(mainWindow) self.actionopen.setObjectName("actionopen") self.actionExit = QtWidgets.QAction(mainWindow) self.actionExit.setObjectName("actionExit") self.action_7 = QtWidgets.QAction(mainWindow) self.action_7.setObjectName("action_7") self.action_8 = QtWidgets.QAction(mainWindow) self.action_8.setObjectName("action_8") self.action_10 = QtWidgets.QAction(mainWindow) self.action_10.setObjectName("action_10") self.menufile.addAction(self.actionopen) self.menufile.addAction(self.action_7) self.menufile.addAction(self.action_8) self.menufile.addSeparator() self.menufile.addAction(self.action_10) self.menubar.addAction(self.menufile.menuAction()) self.menubar.addAction(self.menu_2.menuAction()) self.menubar.addAction(self.menu_3.menuAction()) self.menubar.addAction(self.menu_4.menuAction()) self.menubar.addAction(self.menu_5.menuAction()) self.retranslateUi(mainWindow) QtCore.QMetaObject.connectSlotsByName(mainWindow) def retranslateUi(self, mainWindow): _translate = QtCore.QCoreApplication.translate mainWindow.setWindowTitle(_translate("mainWindow", "三维可视化")) self.label.setText(_translate("mainWindow", "Action Logs")) self.label_2.setText(_translate("mainWindow", "组织数:")) self.label_3.setText(_translate("mainWindow", "组织数:")) self.pushButton.setText(_translate("mainWindow", "显示函数值")) self.pushButton_2.setText(_translate("mainWindow", "上色")) self.pushButton_3.setText(_translate("mainWindow", "去色")) self.pushButton_4.setText(_translate("mainWindow", "输出画面")) self.radioButton.setText(_translate("mainWindow", "面绘制")) self.radioButton_2.setText(_translate("mainWindow", "体绘制")) self.label_4.setText(_translate("mainWindow", "透明度:")) self.menufile.setTitle(_translate("mainWindow", "文件")) self.menu_2.setTitle(_translate("mainWindow", "编辑")) self.menu_3.setTitle(_translate("mainWindow", "格式")) self.menu_4.setTitle(_translate("mainWindow", "查看")) self.menu_5.setTitle(_translate("mainWindow", "帮助")) self.actionopen.setText(_translate("mainWindow", "打开")) self.actionExit.setText(_translate("mainWindow", "Exit")) self.action_7.setText(_translate("mainWindow", "保存")) self.action_8.setText(_translate("mainWindow", "另存为")) self.action_10.setText(_translate("mainWindow", "退出")) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) mainWindow = QtWidgets.QMainWindow() ui = Ui_mainWindow() ui.setupUi(mainWindow) mainWindow.show() sys.exit(app.exec_()) ![图片说明](https://img-ask.csdn.net/upload/202004/09/1586427335_857155.png) ``` 功能一体绘制 ```import vtk from vtk.util.misc import vtkGetDataRoot # Create the renderer, the render window, and the interactor. The renderer # draws into the render window, the interactor enables mouse- and # keyboard-based interaction with the scene. ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # The following reader is used to read a series of 2D slices (images) # that compose the volume. The slice dimensions are set, and the # pixel spacing. The data Endianness must also be specified. The reader # usese the FilePrefix in combination with the slice number to construct # filenames using the format FilePrefix.%d. (In this case the FilePrefix # is the root name of the file: quarter.) # v16 = vtk.vtkVolume16Reader() # v16.SetDataDimensions(64, 64) # v16.SetImageRange(1, 93) # v16.SetDataByteOrderToLittleEndian() # v16.SetFilePrefix("D:/dicom_image/headsq/quarter") # v16.SetDataSpacing(3.2, 3.2, 1.5) v16 = vtk.vtkDICOMImageReader() # v16.SetDirectoryName('D:/dicom_image/vtkDicomRender-master/sample') v16.SetDirectoryName('C:\\Users\\yantao\\PycharmProjects\\untitled14\\Examples\\CT') # The volume will be displayed by ray-cast alpha compositing. # A ray-cast mapper is needed to do the ray-casting, and a # compositing function is needed to do the compositing along the ray. volumeMapper = vtk.vtkGPUVolumeRayCastMapper() volumeMapper.SetInputConnection(v16.GetOutputPort()) volumeMapper.SetBlendModeToComposite() # The color transfer function maps voxel intensities to colors. # It is modality-specific, and often anatomy-specific as well. # The goal is to one color for flesh (between 500 and 1000) # and another color for bone (1150 and over). volumeColor = vtk.vtkColorTransferFunction() volumeColor.AddRGBPoint(0, 0.0, 0.0, 0.0) volumeColor.AddRGBPoint(500, 1.0, 0.5, 0.3) volumeColor.AddRGBPoint(1000, 1.0, 0.5, 0.3) volumeColor.AddRGBPoint(1150, 1.0, 1.0, 0.9) # The opacity transfer function is used to control the opacity # of different tissue types. volumeScalarOpacity = vtk.vtkPiecewiseFunction() volumeScalarOpacity.AddPoint(0, 0.00) volumeScalarOpacity.AddPoint(500, 0.15) volumeScalarOpacity.AddPoint(1000, 0.15) volumeScalarOpacity.AddPoint(1150, 0.85) # The gradient opacity function is used to decrease the opacity # in the "flat" regions of the volume while maintaining the opacity # at the boundaries between tissue types. The gradient is measured # as the amount by which the intensity changes over unit distance. # For most medical data, the unit distance is 1mm. volumeGradientOpacity = vtk.vtkPiecewiseFunction() volumeGradientOpacity.AddPoint(0, 0.0) volumeGradientOpacity.AddPoint(90, 0.5) volumeGradientOpacity.AddPoint(100, 1.0) # The VolumeProperty attaches the color and opacity functions to the # volume, and sets other volume properties. The interpolation should # be set to linear to do a high-quality rendering. The ShadeOn option # turns on directional lighting, which will usually enhance the # appearance of the volume and make it look more "3D". However, # the quality of the shading depends on how accurately the gradient # of the volume can be calculated, and for noisy data the gradient # estimation will be very poor. The impact of the shading can be # decreased by increasing the Ambient coefficient while decreasing # the Diffuse and Specular coefficient. To increase the impact # of shading, decrease the Ambient and increase the Diffuse and Specular. volumeProperty = vtk.vtkVolumeProperty() volumeProperty.SetColor(volumeColor) volumeProperty.SetScalarOpacity(volumeScalarOpacity) # volumeProperty.SetGradientOpacity(volumeGradientOpacity) volumeProperty.SetInterpolationTypeToLinear() volumeProperty.ShadeOn() volumeProperty.SetAmbient(0.9) volumeProperty.SetDiffuse(0.9) volumeProperty.SetSpecular(0.9) # The vtkVolume is a vtkProp3D (like a vtkActor) and controls the position # and orientation of the volume in world coordinates. volume = vtk.vtkVolume() volume.SetMapper(volumeMapper) volume.SetProperty(volumeProperty) # Finally, add the volume to the renderer ren.AddViewProp(volume) # Set up an initial view of the volume. The focal point will be the # center of the volume, and the camera position will be 400mm to the # patient's left (which is our right). camera = ren.GetActiveCamera() c = volume.GetCenter() camera.SetFocalPoint(c[0], c[1], c[2]) camera.SetPosition(c[0] + 400, c[1], c[2]) camera.SetViewUp(0, 0, -1) # Increase the size of the render window renWin.SetSize(640, 480) # Interact with the data. iren.Initialize() renWin.Render() iren.Start() 功能二面绘制 # 抽取轮廓(等值面)的操作对象是标量数据。mianhuizhi2 import vtk # source—filter——mapper——actor——render——renderwindow——interactor aRenderer = vtk.vtkRenderer() # 渲染器 renWin = vtk.vtkRenderWindow() # 渲染窗口,创建窗口 renWin.AddRenderer(aRenderer) # 渲染窗口 # renWin.Render() iren = vtk.vtkRenderWindowInteractor() # 窗口交互 iren.SetRenderWindow(renWin) # The following reader is used to read a series of 2D slices(images) # that compose the volume.Theslicedimensions are set, and the # pixel spacing.The data Endianness must also be specified.The reader # uses the FilePrefix in combination with the slice number to construct # filenames using the format FilePrefix. % d.(In this case the FilePrefix # is the root name of the file. v16 = vtk.vtkDICOMImageReader() # v16.SetDirectoryName('D:/dicom_image/V') v16.SetDirectoryName('C:\\Users\\yantao\\PycharmProjects\\untitled14\\Examples\\CT') # An isosurface, or contour value of 500 is known to correspond to the # skin of the patient.Once generated, a vtkPolyDataNormals filter is # used to create normals for smooth surface shading during rendering. skinExtractor = vtk.vtkContourFilter() skinExtractor.SetInputConnection(v16.GetOutputPort()) skinExtractor.SetValue(0, -10) # skinExtractor.GenerateValues(2, 100, 110) skinNormals = vtk.vtkPolyDataNormals() skinNormals.SetInputConnection(skinExtractor.GetOutputPort()) skinNormals.SetFeatureAngle(60.0) skinMapper = vtk.vtkPolyDataMapper() # 映射器 skinMapper.SetInputConnection(skinNormals.GetOutputPort()) skinMapper.ScalarVisibilityOff() skin = vtk.vtkActor() # 设置颜色RGB颜色系统就是由三个颜色分量:红色(R)、绿色(G)和蓝色(B)的组合表示, # 在VTK里这三个分量的取值都是从0到1,(0, 0, 0)表示黑色,(1, 1, 1)表示白色。 # vtkProperty::SetColor(r,g, b)采用的就是RGB颜色系统设置颜色属性值。 #skin.GetProperty().SetColor(0, 0, 1) skin.SetMapper(skinMapper) skin.GetProperty().SetDiffuseColor(1, .49, .25) skin.GetProperty().SetSpecular(.5) skin.GetProperty().SetSpecularPower(20) # skin.GetProperty().SetRepresentationToSurface() # 构建图形的方框 outlineData = vtk.vtkOutlineFilter() outlineData.SetInputConnection(v16.GetOutputPort()) mapOutline = vtk.vtkPolyDataMapper() mapOutline.SetInputConnection(outlineData.GetOutputPort()) outline = vtk.vtkActor() outline.SetMapper(mapOutline) outline.GetProperty().SetColor(0, 0, 0) # 构建舞台的相机 aCamera = vtk.vtkCamera() aCamera.SetViewUp(0, 0, -1) aCamera.SetPosition(0, 1, 0) aCamera.SetFocalPoint(0, 0, 0) aCamera.ComputeViewPlaneNormal() # Actors are added to the renderer.An initial camera view is created. # The Dolly() method moves the camera towards the Focal Point, # thereby enlarging the image. aRenderer.AddActor(outline) aRenderer.AddActor(skin) aRenderer.SetActiveCamera(aCamera) # 将相机的焦点移动至中央,The camera will reposition itself to view the center point of the actors, # and move along its initial view plane normal aRenderer.ResetCamera() # aCamera.Dolly(1.5) # aCamera.Roll(180) # aCamera.Yaw(60) aRenderer.SetBackground(250, 250, 250) # renWin.SetSize(640, 480) # 该方法是从vtkRenderWindow的父类vtkWindow继承过来的,用于设置窗口的大小,以像素为单位。 renWin.SetSize(500, 500) aRenderer.ResetCameraClippingRange() style = vtk.vtkInteractorStyleTrackballCamera() iren.SetInteractorStyle(style) iren.Initialize() iren.Start() ``` ```

2019 Python开发者日-培训

2019 Python开发者日-培训

150讲轻松搞定Python网络爬虫

150讲轻松搞定Python网络爬虫

设计模式(JAVA语言实现)--20种设计模式附带源码

设计模式(JAVA语言实现)--20种设计模式附带源码

YOLOv3目标检测实战:训练自己的数据集

YOLOv3目标检测实战:训练自己的数据集

java后台+微信小程序 实现完整的点餐系统

java后台+微信小程序 实现完整的点餐系统

三个项目玩转深度学习(附1G源码)

三个项目玩转深度学习(附1G源码)

初级玩转Linux+Ubuntu(嵌入式开发基础课程)

初级玩转Linux+Ubuntu(嵌入式开发基础课程)

2019 AI开发者大会

2019 AI开发者大会

玩转Linux:常用命令实例指南

玩转Linux:常用命令实例指南

一学即懂的计算机视觉(第一季)

一学即懂的计算机视觉(第一季)

4小时玩转微信小程序——基础入门与微信支付实战

4小时玩转微信小程序——基础入门与微信支付实战

Git 实用技巧

Git 实用技巧

Python数据清洗实战入门

Python数据清洗实战入门

使用TensorFlow+keras快速构建图像分类模型

使用TensorFlow+keras快速构建图像分类模型

实用主义学Python(小白也容易上手的Python实用案例)

实用主义学Python(小白也容易上手的Python实用案例)

程序员的算法通关课:知己知彼(第一季)

程序员的算法通关课:知己知彼(第一季)

MySQL数据库从入门到实战应用

MySQL数据库从入门到实战应用

机器学习初学者必会的案例精讲

机器学习初学者必会的案例精讲

手把手实现Java图书管理系统(附源码)

手把手实现Java图书管理系统(附源码)

极简JAVA学习营第四期(报名以后加助教微信:eduxy-1)

极简JAVA学习营第四期(报名以后加助教微信:eduxy-1)

.net core快速开发框架

.net core快速开发框架

玩转Python-Python3基础入门

玩转Python-Python3基础入门

Python数据挖掘简易入门

Python数据挖掘简易入门

微信公众平台开发入门

微信公众平台开发入门

程序员的兼职技能课

程序员的兼职技能课

Windows版YOLOv4目标检测实战:训练自己的数据集

Windows版YOLOv4目标检测实战:训练自己的数据集

HoloLens2开发入门教程

HoloLens2开发入门教程

微信小程序开发实战

微信小程序开发实战

Java8零基础入门视频教程

Java8零基础入门视频教程

Python可以这样学(第一季:Python内功修炼)

Python可以这样学(第一季:Python内功修炼)

C++语言基础视频教程

C++语言基础视频教程

Python可以这样学(第四季:数据分析与科学计算可视化)

Python可以这样学(第四季:数据分析与科学计算可视化)

网络工程师小白入门--【思科CCNA、华为HCNA等网络工程师认证】

网络工程师小白入门--【思科CCNA、华为HCNA等网络工程师认证】

相关热词 c#跨线程停止timer c#批量写入sql数据库 c# 自动安装浏览器 c#语言基础考试题 c# 偏移量打印是什么 c# 绘制曲线图 c#框体中的退出函数 c# 按钮透明背景 c# idl 混编出错 c#在位置0处没有任何行
立即提问