1、添加组件
首先,使用designer在mainwin.ui上添加两个QPushButton,分别命名为show_img和clear_img,保存并重新编译,效果如下图:
2、编写函数
2.1、绑定信号槽
def init_slot(self):
#开始绑定信号和槽
self.ui.show_img.clicked.connect(self.select_img)
self.ui.clear_img.clicked.connect(self.clear_img)
pass
2.2、选择图片并与show_img函数关联
def select_img(self):
img_name,_ = QtWidgets.QFileDialog.getOpenFileName(self,"选择图片","./img/","*.jpg;;*.png;;*.jpeg")
self.show_img(img_name,self.ui.label)
pass
2.3、编写show_img函数
这里使用了静态方法,并使用try-except处理异常情况,展示图片过程中保持了图片的原始的纵横比。
@staticmethod
def show_img(img_name,label):
try:
#读取图片
im = cv2.imread(img_name)
#获取高和宽
ih,iw ,_ = im.shape
#获取标签的长和高
w = label.geometry().width()
h = label.geometry().height()
#下面的目的是为了保持原始的纵横比
if iw/w >ih/h:
scal = w/iw
nw = w
nh = int(scal * ih)
im_new = cv2.resize(im,(nw,nh))
else:
scal = w/iw
nw = int(scal*iw)
nh = h
im_new = cv2.resize(im,(nw,nh))
frame = cv2.cvtColor(im_new,cv2.COLOR_BGR2RGB)
im = QImage(frame.data,frame.shape[1],frame.shape[0],frame.shape[2] * frame.shape[1],
QImage.Format_RGB888)
label.setPixmap(QPixmap.fromImage(im))
except Exception as e:
print(repr(e))
2.4、清空图片
这是最好理解的一段代码
def clear_img(self):
self.ui.label.clear()
pass
2.5、完整代码
from PySide6.QtWidgets import QApplication,QMainWindow
from PySide6 import QtWidgets
from PySide6.QtGui import QImage,QPixmap
from ui.Ui_mainwin import Ui_MainWindow
import sys
import cv2
class MainWin(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.show()
self.init_slot()
def init_slot(self):
#开始绑定信号和槽
self.ui.show_img.clicked.connect(self.select_img)
self.ui.clear_img.clicked.connect(self.clear_img)
pass
def select_img(self):
img_name,_ = QtWidgets.QFileDialog.getOpenFileName(self,"选择图片","./img/","*.jpg;;*.png;;*.jpeg")
self.show_img(img_name,self.ui.label)
pass
@staticmethod
def show_img(img_name,label):
try:
#读取图片
im = cv2.imread(img_name)
#获取高和宽
ih,iw ,_ = im.shape
#获取标签的长和高
w = label.geometry().width()
h = label.geometry().height()
#上述的目的是为了保持原始的纵横比
if iw/w >ih/h:
scal = w/iw
nw = w
nh = int(scal * ih)
im_new = cv2.resize(im,(nw,nh))
else:
scal = w/iw
nw = int(scal*iw)
nh = h
im_new = cv2.resize(im,(nw,nh))
frame = cv2.cvtColor(im_new,cv2.COLOR_BGR2RGB)
im = QImage(frame.data,frame.shape[1],frame.shape[0],frame.shape[2] * frame.shape[1],
QImage.Format_RGB888)
label.setPixmap(QPixmap.fromImage(im))
except Exception as e:
print(repr(e))
def clear_img(self):
self.ui.label.clear()
pass
if __name__=='__main__':
app = QApplication(sys.argv)
window = MainWin()
sys.exit(app.exec())
3、视频教程
欢迎大家关注我的B站@鲸可落,To Be Continue…