python图形界面GUI——pyqt5(&图像处理课程作业)

时间:2024-05-22 10:04:49

#图像处理作业最终的展示需要,用到的部分就够

 


 

安装

anaconda-navigator搜索pyqt安装pyqt5即可。

 

 

一个最简单的窗口

import sys
 
#这里我们提供必要的引用。基本控件位于pyqt5.qtwidgets模块中。
from PyQt5.QtWidgets import QApplication, QWidget
 
 
if __name__ == '__main__':
    #每一pyqt5应用程序必须创建一个应用程序对象。sys.argv参数是一个列表,从命令行输入参数。
    app = QApplication(sys.argv)
    #QWidget部件是pyqt5所有用户界面对象的基类。他为QWidget提供默认构造函数。默认构造函数没有父类。
    w = QWidget()
    #resize()方法调整窗口的大小。这离是250px宽150px高
    w.resize(250, 150)
    #move()方法移动窗口在屏幕上的位置到x = 300,y = 300坐标。
    w.move(800, 400)
    #设置窗口的标题
    w.setWindowTitle('Simple')
    #显示在屏幕上
    w.show()
    
    #系统exit()方法确保应用程序干净的退出
    #的exec_()方法有下划线。因为执行是一个Python关键词。因此,exec_()代替
    sys.exit(app.exec_())

python图形界面GUI——pyqt5(&图像处理课程作业)

 

Messagebox消息框



import sys
from PyQt5.QtWidgets import QWidget, QMessageBox, QApplication
from PyQt5.QtGui import QFont 
 
class Example(QWidget):     #继承自父类Qwidget创建实例example
     
    def __init__(self):     #初始化
        super().__init__()
         
        self.initUI()       #创建UI
         
         
    def initUI(self):              
         
        self.setGeometry(300, 300, 250, 150)       #弹窗的坐标,尺寸
        self.setWindowTitle('Message box')          
        self.show()
         
         
    def closeEvent(self, event):
         
        reply = QMessageBox.question(self, 'Message', "Are you sure to quit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        #标题名;提示文本;按钮合集;默认选择项
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()       
         
         
if __name__ == '__main__':
     
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

python图形界面GUI——pyqt5(&图像处理课程作业)

 

 

布局管理

 

绝对位置布局

就是生成的时候定义位置

 

框布局Boxlayout

我们使用QHBoxLayout和QVBoxLayout,来分别创建横向布局和纵向布局。

下面使用HBoxLayout和QVBoxLayout并添加伸展因子,在窗口的右下角显示两个按钮。

import sys
from PyQt5.QtWidgets import (QWidget, QPushButton,
    QHBoxLayout, QVBoxLayout, QApplication)
 
 
class Example(QWidget):
     
    def __init__(self):
        super().__init__()
         
        self.initUI()
         
         
    def initUI(self):
         
        okButton = QPushButton("OK")
        cancelButton = QPushButton("Cancel")
 
        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(okButton)
        hbox.addWidget(cancelButton)
 
        vbox = QVBoxLayout()
        vbox.addStretch(1)
        vbox.addLayout(hbox)
         
        self.setLayout(vbox)   
         
        self.setGeometry(500, 400, 400, 350)
        self.setWindowTitle('Buttons')   
        self.show()
         
         
if __name__ == '__main__':
     
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

hbox部分设置的是水平布局,vbox则是设置垂直布局。其中addStretch(1)是添加伸展因子,在hbox部分添加时,可以使按钮向右推动,对应的vbox则是向下底部对其。这样形成的布局,无论窗口大小怎么变,按钮均在右下方。

 

python图形界面GUI——pyqt5(&图像处理课程作业)

 

 

鼠标点击触发事件

直接设置两个按钮,布局好,对应每个按钮设置其触发事件,触发事件暂时为打印字符,后续将编好的图像处理程序放到事件中就大功告成了。代码如下:

# -*- coding: utf-8 -*-

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class work(QWidget):
    def __init__(self):
        super().__init__()
        self.title = "图像处理课程作业"
        self.left = 300
        self.top = 300
        self.width = 820
        self.height = 500
        self.initUI()

    def initUI(self):
        #主窗口
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        #各按钮显示设计
        button_display = QPushButton("显示图片", self)
        button_display.resize(100,50)
        button_display.move(30, 30)
        button_2gray = QPushButton("转成灰度图", self)
        button_2gray.resize(100,50)
        button_2gray.move(30, 110)
        """按钮与鼠标点击事件相关联"""
        button_display.clicked.connect(self.display)
        button_2gray.clicked.connect(self.rgb2gray)
        
        self.show()
    
    #功能设计
    def display(self):
        #sender = self.sender()
        #self.statusBar().showMessage(sender.text() + ' was pressed')
        print("在这里图片读取")
        
        
    def rgb2gray(self):
        print("在这里进行转化")    
     

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = work()
    sys.exit(app.exec_())



结果:

python图形界面GUI——pyqt5(&图像处理课程作业)

到此为止就足够应付作业的展示了。

 

图像处理作业GUI页面及完成代码(未搭建车辆检测): 

# -*- coding: utf-8 -*-

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
import cv2 as cv
import numpy as np
import time
from matplotlib import pyplot as plt


    
class work(QWidget):
    def __init__(self):
        super().__init__()
        self.title = "图像处理课程作业"
        self.left = 300
        self.top = 300
        self.width = 820
        self.height = 500
        self.initUI()

    def initUI(self):
        #主窗口
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        
        #小图标皮一下
        self.setWindowIcon(QIcon('/py/pic/BlueCup.jpg')) 
        
        #各按钮显示设计
        button_display = QPushButton("显示图片", self)
        button_display.resize(100,50)
        button_display.move(30, 40)
        
        button_2gray = QPushButton("转成灰度图", self)
        button_2gray.resize(100,50)
        button_2gray.move(30, 120)
        
        button_histogram = QPushButton("绘制直方图", self)
        button_histogram.resize(100,50)
        button_histogram.move(30, 200)
        
        button_equalizeHist = QPushButton("直方图均衡", self)
        button_equalizeHist.resize(100,50)
        button_equalizeHist.move(30, 280)
                
        button_gradient_sharpening = QPushButton("梯度锐化", self)
        button_gradient_sharpening.resize(100,50)
        button_gradient_sharpening.move(170, 40)
        
        button_laplace_sharpening = QPushButton("Laplace锐化", self)
        button_laplace_sharpening.resize(100,50)
        button_laplace_sharpening.move(170, 120)
        
        button_canny = QPushButton("canny边缘检测", self)
        button_canny.resize(100,50)
        button_canny.move(170, 200)
        
        button_filter = QPushButton("图像滤波", self)
        button_filter.resize(100,50)
        button_filter.move(170, 280)
        
        """按钮与鼠标点击事件相关联"""
        button_display.clicked.connect(self.display)
        button_2gray.clicked.connect(self.rgb2gray)
        button_histogram.clicked.connect(self.histogram)
        button_equalizeHist.clicked.connect(self.equalizeHist)
        button_gradient_sharpening.clicked.connect(self.gradient_sharpening)
        button_laplace_sharpening.clicked.connect(self.laplace_sharpening)
        button_canny.clicked.connect(self.canny)
        button_filter.clicked.connect(self.filter)
        
        self.show()
    
    
    #功能设计
    def display(self):
        #print("图片显示")
        load_pic(img)
         
    def rgb2gray(self):
        #print("RGB图读取转换为灰度图")
        rgb_2_gray(img)
            
    def histogram(self):
        #print("绘制直方图")
        draw_histogram(img)

    def equalizeHist(self):
        #print('直方图均衡')
        EqualizeHist(img)
        
    def gradient_sharpening(self):
        #print('梯度锐化')
        Gradient_sharpening(img)
        
    def laplace_sharpening(self):
        #print('Laplace锐化')
        Laplace_sharpening(img)
        
    def canny(self):
        #print('canny边缘检测')
        Canny(img)
        
    def filter(self):
        #print('图像滤波')
        Filter_display(img)
        
#————————————————函数实现——————————————————————————————————————————————————————————————————————————————       
           
#print("图片显示")
def load_pic(img):    
    cv.imshow(u"pic",img)
    cv.waitKey(0)
    cv.destroyAllWindows()

#print("RGB图读取转换为灰度图")
def rgb_2_gray(img):
    start=time.time()
    if flag==0:
        print('Grayscale cannot be transfromed!')
    else:
        dst=img.copy()
        for i in range(rows):
            for j in range(cols):
                b=img.item(i,j,0)
                g=img.item(i,j,1)
                r=img.item(i,j,2)
                dst[i,j]=0.11*r+0.58*g+0.29*b
        end=time.time()
        print("spend time:",end-start,"s")
        cv.imshow("RGB to Grayscale",dst)
        cv.waitKey(0) 
        cv.destroyAllWindows()    
    
#print("绘制直方图")   
def draw_histogram(img):
    if flag==1:
        print('pic will be convert to Grayscale!')
        img_=cv.imread(path,0)
        plt.hist(img_.ravel(),256,[0,256])
        plt.show()

    else:
        plt.hist(img.ravel(),256,[0,256])
        plt.show()

#print('直方图均衡')
def EqualizeHist(img):
    if flag==1:
        print('pic will be convert to Grayscale!')
        img_=cv.imread(path,0)
        equ = cv.equalizeHist(img_)
        res = np.hstack((img_,equ))
        cv.imshow("EqualizeHist",res)
        cv.waitKey(0) 
        cv.destroyAllWindows()  
    else:
        equ = cv.equalizeHist(img)
        res = np.hstack((img,equ))
        cv.imshow(u"EqualizeHist",res)
        cv.waitKey(0) 
        cv.destroyAllWindows()  

#print('梯度锐化')
def Gradient_sharpening(img):
    dst=img.copy()
    if flag==0:
        for i in range(rows-1):
            for j in range(cols-1):
                dst[i,j]=img[i,j]-abs(img[i+1,j]-img[i,j])+abs(img[i,j+1]-img[i,j])
        cv.imshow("Gradient_sharpening",dst)
        cv.waitKey(0) 
        cv.destroyAllWindows()  
    else:
        print('please input a Grayscale!')
        
#print('Lplace锐化')
def Laplace_sharpening(img):
    dst=img.copy()
    if flag==0:
        for i in range(1,rows-1):
            for j in range(1,cols-1):
                dst[i,j]=5*img[i,j]-abs(img[i+1,j])-abs(img[i,j+1])-abs(img[i-1,j])-abs(img[i,j-1])
        cv.imshow("Laplace_ sharpening",dst)
        cv.waitKey(0) 
        cv.destroyAllWindows()  
    else:
        print('please input a Grayscale!')

#print('canny边缘检测')
def Canny(img):
    gaussian = cv.GaussianBlur(img,(5,5),0)
    edges = cv.Canny(gaussian,100,200)
    cv.imshow("canny edge detection",edges)
    cv.waitKey(0) 
    cv.destroyAllWindows()
    
def Filter_display(img):
    mean = cv.blur(img,(5,5))
    gaussian = cv.GaussianBlur(img,(5,5),0)
    median = cv.medianBlur(img,5)
    cv.imshow(u"mean filtering",mean)
    cv.imshow(u"gaussian filtering",gaussian)
    cv.imshow(u"median filtering",median)
    cv.waitKey(0) 
    cv.destroyAllWindows()  


if __name__ == '__main__':
    path='/py/pic/lena.jpg'
    flag=0
    img=cv.imread(path,flag)
    rows=img.shape[0]
    cols=img.shape[1]
    app = QApplication(sys.argv)
    ex = work()
    sys.exit(app.exec_())



图形界面:

python图形界面GUI——pyqt5(&图像处理课程作业)

可以将qt构建的GUI图标替换一下变成左边的小杯子,以后常设置,很有趣。

每个模块的按钮鼠标触发,可以完成对应操作(图略)。

(注意一下:读取路径的问题,只用名字,不加后缀,另一篇博客opencv笔记有记载)