Python QT与Opencv(二)

一.使用QFileDialog加载并保存Opencv图像

①Qt designer
在这里插入图片描述
②loadandsave.ui -> loadandsave.py

# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'loadandsave.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(682, 576)
        self.imagelabel = QtWidgets.QLabel(Dialog)
        self.imagelabel.setGeometry(QtCore.QRect(80, 90, 511, 421))
        self.imagelabel.setText("")
        self.imagelabel.setObjectName("imagelabel")
        self.widget = QtWidgets.QWidget(Dialog)
        self.widget.setGeometry(QtCore.QRect(40, 40, 581, 30))
        self.widget.setObjectName("widget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.widget)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.loadButton = QtWidgets.QPushButton(self.widget)
        self.loadButton.setObjectName("loadButton")
        self.horizontalLayout.addWidget(self.loadButton)
        self.saveButton = QtWidgets.QPushButton(self.widget)
        self.saveButton.setObjectName("saveButton")
        self.horizontalLayout.addWidget(self.saveButton)
        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)
        
    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.loadButton.setText(_translate("Dialog", "Load Image"))
        self.saveButton.setText(_translate("Dialog", "Save Image"))

③ main_code

import sys
import cv2
from PyQt5 import QtCore
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtGui import QImage,QPixmap
from PyQt5.QtWidgets import QDialog,QApplication,QFileDialog
from PyQt5.uic import loadUi
from loadandsave import Ui_Dialog

class Life2Coding(QDialog,Ui_Dialog):
    def __init__(self, parent=None):
        super(QDialog,self).__init__(parent)
        self.setupUi(self)
        
        self.image = None
        self.loadButton.clicked.connect(self.loadClicked)
        self.saveButton.clicked.connect(self.saveClicked)
        
    @pyqtSlot()
    def loadClicked(self):
        fname, filter = QFileDialog.getOpenFileName(self, "Open File", "E:\\youtu_image", "Image Files (*.jpg)")
        if fname:
            self.loadImage(fname)
        else:
            print("Invalid Image!!!Check!!!")
            
    @pyqtSlot()
    def saveClicked(self):
        fname, filter = QFileDialog.getSaveFileName(self, "Save File", "E:\\youtu_image", "Image Files (*.jpg)")
        if fname:
            cv2.imwrite(fname, self.image)
        else:
            print("Error!!!")
            
    def loadImage(self,fname):
        # self.image = cv2.imread(fname)
        self.image = cv2.imread(fname, cv2.IMREAD_COLOR)      #图片彩色读取
        # self.image = cv2.imread(fname,cv2.IMREAD_GRAYSCALE) #图片灰度读取
        self.displayImage()
        
    def displayImage(self):
        qformat = QImage.Format_Indexed8
        if len(self.image.shape) == 3: #rows->shape[0],cols_>shape[1],channels->shape[2]
            if(self.image.shape[2]) == 4:
                qformat = QImage.Format_RGBA8888
            else:
                qformat = QImage.Format_RGB888
        img = QImage(self.image,self.image.shape[1],self.image.shape[0],self.image.strides[0],qformat)
        # BGR->RGB
        img = img.rgbSwapped()
        self.imagelabel.setPixmap(QPixmap.fromImage(img))
        self.imagelabel.setAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
        
app = QApplication(sys.argv)
window = Life2Coding()
window.show()
sys.exit(app.exec_())

效果:
在这里插入图片描述

二.Opencv GUI与Canny边缘检测算法

①Qt designer
在这里插入图片描述
②loadandsave.ui -> loadandsave.py

# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'loadandsave.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(824, 576)
        self.imagelabel = QtWidgets.QLabel(Dialog)
        self.imagelabel.setGeometry(QtCore.QRect(41, 91, 341, 431))
        self.imagelabel.setObjectName("imagelabel")
        self.processedlabel = QtWidgets.QLabel(Dialog)
        self.processedlabel.setGeometry(QtCore.QRect(419, 91, 321, 431))
        self.processedlabel.setObjectName("processedlabel")
        self.widget = QtWidgets.QWidget(Dialog)
        self.widget.setGeometry(QtCore.QRect(40, 30, 751, 30))
        self.widget.setObjectName("widget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.widget)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.loadButton = QtWidgets.QPushButton(self.widget)
        self.loadButton.setObjectName("loadButton")
        self.horizontalLayout.addWidget(self.loadButton)
        self.saveButton = QtWidgets.QPushButton(self.widget)
        self.saveButton.setObjectName("saveButton")
        self.horizontalLayout.addWidget(self.saveButton)
        self.cannyButton = QtWidgets.QPushButton(self.widget)
        self.cannyButton.setObjectName("cannyButton")
        self.horizontalLayout.addWidget(self.cannyButton)
        
        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)
        
    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.imagelabel.setText(_translate("Dialog", "imagelabel"))
        self.processedlabel.setText(_translate("Dialog", "processedlabel"))
        self.loadButton.setText(_translate("Dialog", "Load Image"))
        self.saveButton.setText(_translate("Dialog", "Save Image"))
        self.cannyButton.setText(_translate("Dialog", "Canny"))

③ main_code

import sys
import cv2
from PyQt5 import QtCore
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtGui import QImage,QPixmap
from PyQt5.QtWidgets import QDialog,QApplication,QFileDialog
from PyQt5.uic import loadUi
from loadandsave import Ui_Dialog

class Life2Coding(QDialog,Ui_Dialog):
    def __init__(self, parent=None):
        super(QDialog,self).__init__(parent)
        self.setupUi(self)
        
        self.image = None
        self.loadButton.clicked.connect(self.loadClicked)
        self.saveButton.clicked.connect(self.saveClicked)
        self.cannyButton.clicked.connect(self.cannyClicked)
        
    @pyqtSlot()
    def cannyClicked(self):
        gray = cv2.cvtColor(self.image,cv2.COLOR_BGR2GRAY) if len(self.image.shape)>=3 else self.image
        self.image = cv2.Canny(gray,100,200)
        self.displayImage(2)
        
    @pyqtSlot()
    def loadClicked(self):
        fname, filter = QFileDialog.getOpenFileName(self, "Open File", "E:\\youtu_image", "Image Files (*.jpg)")
        if fname:
            self.loadImage(fname)
        else:
            print("Invalid Image!!!Check!!!")
            
    @pyqtSlot()
    def saveClicked(self):
        fname, filter = QFileDialog.getSaveFileName(self, "Save File", "E:\\youtu_image", "Image Files (*.jpg)")
        if fname:
            cv2.imwrite(fname, self.image)
        else:
            print("Error!!!")
            
    def loadImage(self,fname):
        # self.image = cv2.imread(fname)
        self.image = cv2.imread(fname, cv2.IMREAD_COLOR)      #图片彩色读取
        # self.image = cv2.imread(fname,cv2.IMREAD_GRAYSCALE) #图片灰度读取
        self.displayImage(1)
        
    def displayImage(self,window=1):
        qformat = QImage.Format_Indexed8
        if len(self.image.shape) == 3: #rows->shape[0],cols_>shape[1],channels->shape[2]
            if(self.image.shape[2]) == 4:
                qformat = QImage.Format_RGBA8888
            else:
                qformat = QImage.Format_RGB888
        img = QImage(self.image,self.image.shape[1],self.image.shape[0],self.image.strides[0],qformat)
        # BGR->RGB
        img = img.rgbSwapped()
        if window == 1:
            self.imagelabel.setPixmap(QPixmap.fromImage(img))
            self.imagelabel.setAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
        if window == 2:
            self.processedlabel.setPixmap(QPixmap.fromImage(img))
            self.processedlabel.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
            
app = QApplication(sys.argv)
window = Life2Coding()
window.show()
sys.exit(app.exec_())

效果:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

三.在PyQt上创建滑动条来调整图像的canny算子

①Qt designer
在这里插入图片描述
②loadandsave.ui -> loadandsave.py

# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'loadandsave.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(824, 576)
        self.imagelabel = QtWidgets.QLabel(Dialog)
        self.imagelabel.setGeometry(QtCore.QRect(42, 120, 341, 431))
        self.imagelabel.setObjectName("imagelabel")
        self.processedlabel = QtWidgets.QLabel(Dialog)
        self.processedlabel.setGeometry(QtCore.QRect(420, 120, 321, 431))
        self.processedlabel.setObjectName("processedlabel")
        self.hSlider = QtWidgets.QSlider(Dialog)
        self.hSlider.setGeometry(QtCore.QRect(30, 60, 741, 22))
        self.hSlider.setOrientation(QtCore.Qt.Horizontal)
        self.hSlider.setTickInterval(10)
        self.hSlider.setObjectName("hSlider")
        self.widget = QtWidgets.QWidget(Dialog)
        self.widget.setGeometry(QtCore.QRect(30, 10, 751, 30))
        self.widget.setObjectName("widget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.widget)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.loadButton = QtWidgets.QPushButton(self.widget)
        self.loadButton.setObjectName("loadButton")
        self.horizontalLayout.addWidget(self.loadButton)
        self.saveButton = QtWidgets.QPushButton(self.widget)
        self.saveButton.setObjectName("saveButton")
        self.horizontalLayout.addWidget(self.saveButton)
        self.cannyButton = QtWidgets.QPushButton(self.widget)
        self.cannyButton.setObjectName("cannyButton")
        self.horizontalLayout.addWidget(self.cannyButton)
        
        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)
        
    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.imagelabel.setText(_translate("Dialog", "imagelabel"))
        self.processedlabel.setText(_translate("Dialog", "processedlabel"))
        self.loadButton.setText(_translate("Dialog", "Load Image"))
        self.saveButton.setText(_translate("Dialog", "Save Image"))
        self.cannyButton.setText(_translate("Dialog", "Canny"))

③ main_code

import sys
import cv2
from PyQt5 import QtCore
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtGui import QImage,QPixmap
from PyQt5.QtWidgets import QDialog,QApplication,QFileDialog
from PyQt5.uic import loadUi
from loadandsave import Ui_Dialog

class Life2Coding(QDialog,Ui_Dialog):
    def __init__(self, parent=None):
        super(QDialog,self).__init__(parent)
        self.setupUi(self)
        
        self.image = None          # 左边imagelabel控件上的图像image
        self.processedImage = None #右边processedlabel控件上的图像processedImage
        
        self.loadButton.clicked.connect(self.loadClicked) #按钮Load Image
        self.saveButton.clicked.connect(self.saveClicked) #按钮Save Image
        self.cannyButton.clicked.connect(self.cannyClicked) #按钮Canny
        self.hSlider.valueChanged.connect(self.cannyDisplay) #滑动条控件
        
    @pyqtSlot()
    def cannyDisplay(self):
        gray = cv2.cvtColor(self.image,cv2.COLOR_BGR2GRAY) if len(self.image.shape) >=3 else self.image
        self.processedImage = cv2.Canny(gray,self.hSlider.value(),self.hSlider.value()*3)
        self.displayImage(2)
        
    @pyqtSlot()
    def cannyClicked(self):
        gray = cv2.cvtColor(self.image,cv2.COLOR_BGR2GRAY) if len(self.image.shape)>=3 else self.image
        self.processedImage = cv2.Canny(gray,100,200)
        self.displayImage(2)
        
    @pyqtSlot()
    def loadClicked(self):
        fname, filter = QFileDialog.getOpenFileName(self, "Open File", "E:\\youtu_image", "Image Files (*.jpg)")
        if fname:
            self.loadImage(fname)
        else:
            print("Invalid Image!!!Check!!!")
            
    @pyqtSlot()
    def saveClicked(self):
        fname, filter = QFileDialog.getSaveFileName(self, "Save File", "E:\\youtu_image", "Image Files (*.jpg)")
        if fname:
            cv2.imwrite(fname, self.image)
        else:
            print("Error!!!")
            
    def loadImage(self,fname):
        # self.image = cv2.imread(fname)
        self.image = cv2.imread(fname, cv2.IMREAD_COLOR)      #图片彩色读取
        # self.image = cv2.imread(fname,cv2.IMREAD_GRAYSCALE) #图片灰度读取
        self.processedImage = self.image.copy()
        self.displayImage(1)
        
    def displayImage(self,window=1):
        qformat = QImage.Format_Indexed8
        
        if len(self.processedImage.shape) == 3: #rows->shape[0],cols_>shape[1],channels->shape[2]
            if(self.processedImage.shape[2]) == 4:
                qformat = QImage.Format_RGBA8888
            else:
                qformat = QImage.Format_RGB888
        img = QImage(self.processedImage,self.processedImage.shape[1],self.processedImage.shape[0],self.processedImage.strides[0],qformat)
        # BGR->RGB
        img = img.rgbSwapped()
        if window == 1:
            self.imagelabel.setPixmap(QPixmap.fromImage(img))
            self.imagelabel.setAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
        if window == 2:
            self.processedlabel.setPixmap(QPixmap.fromImage(img))
            self.processedlabel.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
            
app = QApplication(sys.argv)
window = Life2Coding()
window.show()
sys.exit(app.exec_())

效果:
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

boss-dog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值