帮我写一段代码基于python opencv的对图像集合做canny边缘检测需要一个ui界面用pyqt5实现
以下是一个基于Python OpenCV的Canny边缘检测代码,同时使用PyQt5实现UI界面。该代码需要安装OpenCV和PyQt5库。
import cv2
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QLabel
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('Canny Edge Detection')
self.setGeometry(100, 100, 800, 600)
self.label = QLabel(self)
self.label.setAlignment(Qt.AlignCenter)
self.setCentralWidget(self.label)
self.createMenuBar()
def createMenuBar(self):
menubar = self.menuBar()
fileMenu = menubar.addMenu('File')
openAction = fileMenu.addAction('Open')
openAction.triggered.connect(self.openFile)
edgeMenu = menubar.addMenu('Edge Detection')
cannyAction = edgeMenu.addAction('Canny')
cannyAction.triggered.connect(self.cannyEdgeDetection)
def openFile(self):
filePath, _ = QFileDialog.getOpenFileName(self, "Open Image", "", "Image Files (*.png *.jpg *.bmp)")
if filePath:
self.image = cv2.imread(filePath, cv2.IMREAD_GRAYSCALE)
self.displayImage()
def cannyEdgeDetection(self):
if hasattr(self, 'image'):
edges = cv2.Canny(self.image, 100, 200)
self.displayImage(edges)
def displayImage(self, image=None):
if image is None:
image = self.image
qImg = QPixmap.fromImage(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
self.label.setPixmap(qImg.scaled(self.label.width(), self.label.height(), Qt.KeepAspectRatio))
if __name__ == '__main__':
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
该代码创建了一个基于PyQt5的UI界面,其中包括一个用于显示图像的标签。菜单栏包含了“File”和“Edge Detection”两个菜单,分别用于打开图像文件和执行Canny边缘检测。在执行Canny边缘检测时,将在图像上显示检测结果。
要运行该代码,只需保存为.py文件并运行即可。在打开图像后,可以通过菜单栏中的“Edge Detection”执行Canny边缘检测
原文地址: https://www.cveoy.top/t/topic/cktf 著作权归作者所有。请勿转载和采集!