python之pyQt5实例:SAM交互式分割

1、显示逻辑

# -*- coding: utf-8 -*-
​
# Form implementation generated from reading ui file 'rmkm_for_SAM.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.
​
​
from PyQt5 import QtCore, QtGui, QtWidgets
​
​
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(694, 666)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.centralwidget)
        self.verticalLayout_5.setObjectName("verticalLayout_5")
        self.horizontalLayout_11 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_11.setObjectName("horizontalLayout_11")
        self.frame_2 = QtWidgets.QFrame(self.centralwidget)
        self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame_2.setObjectName("frame_2")
        self.verticalLayout_8 = QtWidgets.QVBoxLayout(self.frame_2)
        self.verticalLayout_8.setObjectName("verticalLayout_8")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.pushButton = QtWidgets.QPushButton(self.frame_2)
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout_2.addWidget(self.pushButton)
        self.label_7 = QtWidgets.QLabel(self.frame_2)
        self.label_7.setObjectName("label_7")
        self.horizontalLayout_2.addWidget(self.label_7)
        self.verticalLayout_8.addLayout(self.horizontalLayout_2)
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.pushButton_6 = QtWidgets.QPushButton(self.frame_2)
        self.pushButton_6.setObjectName("pushButton_6")
        self.horizontalLayout_3.addWidget(self.pushButton_6)
        self.label_8 = QtWidgets.QLabel(self.frame_2)
        self.label_8.setObjectName("label_8")
        self.horizontalLayout_3.addWidget(self.label_8)
        self.verticalLayout_8.addLayout(self.horizontalLayout_3)
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.label_12 = QtWidgets.QLabel(self.frame_2)
        self.label_12.setObjectName("label_12")
        self.horizontalLayout_4.addWidget(self.label_12)
        self.label_numImage = QtWidgets.QLabel(self.frame_2)
        self.label_numImage.setObjectName("label_numImage")
        self.horizontalLayout_4.addWidget(self.label_numImage)
        self.verticalLayout_8.addLayout(self.horizontalLayout_4)
        self.horizontalLayout_11.addWidget(self.frame_2)
        self.line_9 = QtWidgets.QFrame(self.centralwidget)
        self.line_9.setFrameShape(QtWidgets.QFrame.VLine)
        self.line_9.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_9.setObjectName("line_9")
        self.horizontalLayout_11.addWidget(self.line_9)
        self.verticalLayout_9 = QtWidgets.QVBoxLayout()
        self.verticalLayout_9.setObjectName("verticalLayout_9")
        self.pushButton_last = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_last.setObjectName("pushButton_last")
        self.verticalLayout_9.addWidget(self.pushButton_last)
        self.pushButton_next = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_next.setObjectName("pushButton_next")
        self.verticalLayout_9.addWidget(self.pushButton_next)
        self.horizontalLayout_11.addLayout(self.verticalLayout_9)
        self.line_8 = QtWidgets.QFrame(self.centralwidget)
        self.line_8.setFrameShape(QtWidgets.QFrame.VLine)
        self.line_8.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_8.setObjectName("line_8")
        self.horizontalLayout_11.addWidget(self.line_8)
        self.pushButton_roi = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_roi.setObjectName("pushButton_roi")
        self.horizontalLayout_11.addWidget(self.pushButton_roi)
        self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_4.setObjectName("pushButton_4")
        self.horizontalLayout_11.addWidget(self.pushButton_4)
        self.line_7 = QtWidgets.QFrame(self.centralwidget)
        self.line_7.setFrameShape(QtWidgets.QFrame.VLine)
        self.line_7.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_7.setObjectName("line_7")
        self.horizontalLayout_11.addWidget(self.line_7)
        self.horizontalLayout_11.setStretch(0, 4)
        self.horizontalLayout_11.setStretch(2, 1)
        self.horizontalLayout_11.setStretch(4, 2)
        self.horizontalLayout_11.setStretch(6, 2)
        self.verticalLayout_5.addLayout(self.horizontalLayout_11)
        self.line_2 = QtWidgets.QFrame(self.centralwidget)
        self.line_2.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_2.setObjectName("line_2")
        self.verticalLayout_5.addWidget(self.line_2)
        self.horizontalLayout_9 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_9.setObjectName("horizontalLayout_9")
        self.line_13 = QtWidgets.QFrame(self.centralwidget)
        self.line_13.setFrameShape(QtWidgets.QFrame.VLine)
        self.line_13.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_13.setObjectName("line_13")
        self.horizontalLayout_9.addWidget(self.line_13)
        self.pushButton_5 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_5.setObjectName("pushButton_5")
        self.horizontalLayout_9.addWidget(self.pushButton_5)
        self.line_10 = QtWidgets.QFrame(self.centralwidget)
        self.line_10.setFrameShape(QtWidgets.QFrame.VLine)
        self.line_10.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_10.setObjectName("line_10")
        self.horizontalLayout_9.addWidget(self.line_10)
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setObjectName("pushButton_2")
        self.horizontalLayout_9.addWidget(self.pushButton_2)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.horizontalLayout_9.addLayout(self.horizontalLayout)
        self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_3.setObjectName("pushButton_3")
        self.horizontalLayout_9.addWidget(self.pushButton_3)
        self.horizontalLayout_9.setStretch(1, 3)
        self.horizontalLayout_9.setStretch(3, 3)
        self.horizontalLayout_9.setStretch(5, 3)
        self.verticalLayout_5.addLayout(self.horizontalLayout_9)
        self.line = QtWidgets.QFrame(self.centralwidget)
        self.line.setFrameShape(QtWidgets.QFrame.HLine)
        self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line.setObjectName("line")
        self.verticalLayout_5.addWidget(self.line)
        self.horizontalLayout_6 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_6.setObjectName("horizontalLayout_6")
        self.label_9 = QtWidgets.QLabel(self.centralwidget)
        self.label_9.setObjectName("label_9")
        self.horizontalLayout_6.addWidget(self.label_9)
        self.label_10 = QtWidgets.QLabel(self.centralwidget)
        self.label_10.setObjectName("label_10")
        self.horizontalLayout_6.addWidget(self.label_10)
        self.verticalLayout_5.addLayout(self.horizontalLayout_6)
        self.line_3 = QtWidgets.QFrame(self.centralwidget)
        self.line_3.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_3.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_3.setObjectName("line_3")
        self.verticalLayout_5.addWidget(self.line_3)
        self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.label_roi = QtWidgets.QLabel(self.centralwidget)
        self.label_roi.setFrameShadow(QtWidgets.QFrame.Plain)
        self.label_roi.setObjectName("label_roi")
        self.horizontalLayout_5.addWidget(self.label_roi)
        self.line_5 = QtWidgets.QFrame(self.centralwidget)
        self.line_5.setFrameShape(QtWidgets.QFrame.VLine)
        self.line_5.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_5.setObjectName("line_5")
        self.horizontalLayout_5.addWidget(self.line_5)
        self.label_ad = QtWidgets.QLabel(self.centralwidget)
        self.label_ad.setObjectName("label_ad")
        self.horizontalLayout_5.addWidget(self.label_ad)
        self.line_6 = QtWidgets.QFrame(self.centralwidget)
        self.line_6.setFrameShape(QtWidgets.QFrame.VLine)
        self.line_6.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_6.setObjectName("line_6")
        self.horizontalLayout_5.addWidget(self.line_6)
        self.horizontalLayout_5.setStretch(0, 1)
        self.horizontalLayout_5.setStretch(1, 1)
        self.horizontalLayout_5.setStretch(2, 1)
        self.horizontalLayout_5.setStretch(3, 1)
        self.verticalLayout_5.addLayout(self.horizontalLayout_5)
        self.line_4 = QtWidgets.QFrame(self.centralwidget)
        self.line_4.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_4.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_4.setObjectName("line_4")
        self.verticalLayout_5.addWidget(self.line_4)
        self.horizontalLayout_12 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_12.setObjectName("horizontalLayout_12")
        self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setColumnCount(5)
        self.tableWidget.setRowCount(2)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(1, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(1, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(2, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(3, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(4, item)
        self.horizontalLayout_12.addWidget(self.tableWidget)
        spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_12.addItem(spacerItem)
        self.verticalLayout_4 = QtWidgets.QVBoxLayout()
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        self.pushButton_insertnew = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_insertnew.setObjectName("pushButton_insertnew")
        self.verticalLayout_4.addWidget(self.pushButton_insertnew)
        self.pushButton_insertold = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_insertold.setObjectName("pushButton_insertold")
        self.verticalLayout_4.addWidget(self.pushButton_insertold)
        self.pushButton_caurm = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_caurm.setObjectName("pushButton_caurm")
        self.verticalLayout_4.addWidget(self.pushButton_caurm)
        self.pushButton_clear = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_clear.setObjectName("pushButton_clear")
        self.verticalLayout_4.addWidget(self.pushButton_clear)
        self.horizontalLayout_12.addLayout(self.verticalLayout_4)
        self.horizontalLayout_12.setStretch(0, 3)
        self.horizontalLayout_12.setStretch(2, 1)
        self.verticalLayout_5.addLayout(self.horizontalLayout_12)
        self.verticalLayout_5.setStretch(6, 4)
        self.verticalLayout_5.setStretch(8, 2)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 694, 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.label_7.setText(_translate("MainWindow", "“图片读取位置”"))
        self.pushButton_6.setText(_translate("MainWindow", "选择保存路径"))
        self.label_8.setText(_translate("MainWindow", "“图片保存位置”"))
        self.label_12.setText(_translate("MainWindow", "“图片数量”"))
        self.label_numImage.setText(_translate("MainWindow", "0"))
        self.pushButton_last.setText(_translate("MainWindow", "上一张"))
        self.pushButton_next.setText(_translate("MainWindow", "下一张"))
        self.pushButton_roi.setText(_translate("MainWindow", "截取ROI"))
        self.pushButton_4.setText(_translate("MainWindow", "选择提示点"))
        self.pushButton_5.setText(_translate("MainWindow", "分割计算"))
        self.pushButton_2.setText(_translate("MainWindow", "另存图片"))
        self.pushButton_3.setText(_translate("MainWindow", "批量处理"))
        self.label_9.setText(_translate("MainWindow", "ROI图像:"))
        self.label_10.setText(_translate("MainWindow", "刃面轮廓:"))
        self.label_roi.setText(_translate("MainWindow", "roi"))
        self.label_ad.setText(_translate("MainWindow", "outcome"))
        item = self.tableWidget.verticalHeaderItem(0)
        item.setText(_translate("MainWindow", "新钻"))
        item = self.tableWidget.verticalHeaderItem(1)
        item.setText(_translate("MainWindow", "磨损后"))
        item = self.tableWidget.horizontalHeaderItem(0)
        item.setText(_translate("MainWindow", "1"))
        item = self.tableWidget.horizontalHeaderItem(1)
        item.setText(_translate("MainWindow", "2"))
        item = self.tableWidget.horizontalHeaderItem(2)
        item.setText(_translate("MainWindow", "3"))
        item = self.tableWidget.horizontalHeaderItem(3)
        item.setText(_translate("MainWindow", "4"))
        item = self.tableWidget.horizontalHeaderItem(4)
        item.setText(_translate("MainWindow", "5"))
        self.pushButton_insertnew.setText(_translate("MainWindow", "插入新钻结果"))
        self.pushButton_insertold.setText(_translate("MainWindow", "插入磨损后结果"))
        self.pushButton_caurm.setText(_translate("MainWindow", "计算磨损率"))
        self.pushButton_clear.setText(_translate("MainWindow", "清空结果"))

2、业务逻辑

import sys
import os
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QMessageBox,QStatusBar,QTableWidgetItem,QWidget,QLabel
from PyQt5.QtGui import QPixmap, QImage,QPainter, QPen
from PyQt5.QtCore import Qt, QRect,QPoint,pyqtSignal
from rmkm_for_SAM import Ui_MainWindow
import cv2
import numpy as np
from segment_anything import sam_model_registry, SamPredictor
sys.path.append("..")
#path for sam
sam_checkpoint = r"D:\BaiduNetdiskDownload\segment-anything-main2\segment-anything-main\models\sam_vit_b_01ec64.pth"
model_type = "vit_b"
​
device = "cpu"  # or  "cuda"
​
sam = sam_model_registry[model_type](checkpoint=sam_checkpoint)
sam.to(device=device)
​
predictor = SamPredictor(sam)
​
from segment_anything import sam_model_registry, SamPredictor
'''
1、点击选择提示点按钮反应太慢
'''
​
class rm(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setWindowTitle("刃面磨损量化计算")
        self.statusBar=QStatusBar()
        self.setStatusBar(self.statusBar)
        self.img=0
        self.area=0
        self.imagesPath = ""
        self.savePath = ""
        self.images = []
        self.imgID = 0
        self.bbox = [0,0,0,0]
        self.flag = 0
        self.RoiImage = ""
        self.img = 0
        self.tmp=[]
        self.tmp1 = []
        self.output=[]
        self.mask=[]
        self.outcone={}
        self.new=[]
        self.ni=0
        self.old=[]
        self.oi=0
        self.roiLeftTop = None
        self.roiRightBottom = None
        self.selected_points = []  # 保存选中的点坐标
        self.pos=[]
        self.ui.pushButton.clicked.connect(self.chooseImagesPath)#选择读取路径
        self.ui.pushButton_2.clicked.connect(self.pushButton2_clicked)#另存结果
        self.ui.pushButton_roi.clicked.connect(self.pushButton_roi_clicked)#截取ROI
        self.ui.pushButton_5.clicked.connect(self.pushButton5_clicked)#分割计算
        self.ui.pushButton_6.clicked.connect(self.chooseSavePath)#选择保存路径
        self.ui.pushButton_next.clicked.connect(self.nextImage)
        self.ui.pushButton_last.clicked.connect(self.lastImage)
        self.ui.pushButton_3.clicked.connect(self.pushButton3_clicked)#批量处理
        self.ui.pushButton_4.clicked.connect(self.pushButton4_clicked)  # 选择提示点
        self.ui.pushButton_insertnew.clicked.connect(self.pushButton_insertnew_clicked)
        self.ui.pushButton_insertold.clicked.connect(self.pushButton_insertold_clicked)
        self.ui.pushButton_caurm.clicked.connect(self.pushButton_caurm_clicked)
        self.ui.pushButton_clear.clicked.connect(self.pushButton_clear_clicked)
        self.ui.label_roi.mousePressEvent = self.mousePressEvent
        self.ui.label_roi.setMouseTracking(False)
    def chooseImagesPath(self):
        self.imagesPath =QFileDialog.getExistingDirectory(self,"选取一个文件夹","./")  # 起始路径、读取文件夹
        self.ui.label_7.setText(self.imagesPath)
        # 获取路径下的所有图像内容
        self.images = []
        if (self.imagesPath != ""):
            imgDict = [".jpg", ".png", ".jpeg", ".tiff", ".bmp"]
            for name in os.listdir(self.imagesPath):
                if os.path.splitext(name)[1] in imgDict:
                    self.images.append(name)
                    continue
            self.ui.label_12.setText("图片数量")
            self.ui.label_numImage.setText(str(len(self.images)))
    def chooseSavePath(self):
        self.savePath =QFileDialog.getExistingDirectory(self,"选取一个文件夹","./")  # 起始路径、读取文件夹
        self.ui.label_8.setText(self.savePath)
        pass
    def pushButton_insertnew_clicked(self):
        newitem=QTableWidgetItem(str(self.area))
        self.ui.tableWidget.setItem(0, self.ni, newitem)
        self.ni+=1
        self.new.append(self.area)
    def pushButton_insertold_clicked(self):
        newitem = QTableWidgetItem(str(self.area))
        self.ui.tableWidget.setItem(1, self.oi, newitem)
        self.oi+=1
        self.old.append(self.area)
    def pushButton_caurm_clicked(self):
        rm=(sum(self.old)/len(self.old))/(sum(self.new)/len(self.new))*100
        QMessageBox.information(self, "计算结果", f"刃面磨损率为:{rm}%", QMessageBox.Yes)
    def pushButton_clear_clicked(self):
        self.ui.tableWidget.clearContents()
        self.new = []
        self.ni = 0
        self.old = []
        self.oi = 0
    def pushButton2_clicked(self):#save as
        cv2.imwrite(os.path.join(self.savePath, self.images[self.imgID]), self.output)
    def pushButton_roi_clicked(self):#roi
        if self.judgeFirst() == 0:
            return 0
        if len(self.images) == 0:
            QMessageBox.information(self, "提示", "没有图片可以处理",QMessageBox.Yes)
            return 0
        self.ui.label_12.setText("状态")
        self.ui.label_numImage.setText("截取图像中")
        try:
            if self.img == 0:
                imagePath = os.path.join(self.imagesPath, self.images[self.imgID])
                self.statusBar.showMessage(f"当前处理的图片是:{self.images[self.imgID]}", 5000)
                self.img = cv2.imread(imagePath)
        except:
            pass
        self.flag = 0
        # 弹出新窗口显示图片并截取ROI
        self.imageWindow = ImageWindow()
        shrink = cv2.cvtColor(self.img, cv2.COLOR_BGR2RGB)
        QtImg = QImage(shrink.data,
                       shrink.shape[1],
                       shrink.shape[0],
                       shrink.shape[1] * 3,
                       QImage.Format_RGB888)
        self.imageWindow.image=QPixmap(QtImg)
        self.imageWindow.roiSelected.connect(self.displayROI)
        self.imageWindow.show()
    def displayROI(self, rect):
        # 截取完成后,关闭新窗口并将ROI图像显示在QLabel控件中
        self.imageWindow.close()
        # 记录矩形框左上角和右下角点的坐标
        self.bbox[0]=rect.topLeft().x()
        self.bbox[1]=rect.topLeft().y()
        self.bbox[2]=rect.bottomRight().x()
        self.bbox[3]=rect.bottomRight().y()
        self.RoiImage = self.img[self.bbox[1]:self.bbox[3], self.bbox[0]:self.bbox[2]]
        self.show_cv_img(self.RoiImage, self.ui.label_roi)
        self.flag = 1
        self.ui.label_numImage.setText("截取完毕")
    def show_cv_img(self, img,label):
        shrink = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        QtImg = QImage(shrink.data,
                             shrink.shape[1],
                             shrink.shape[0],
                             shrink.shape[1] * 3,
                             QImage.Format_RGB888)
        jpg_out = QPixmap(QtImg).scaled(
            label.width(), label.height())
        label.setPixmap(jpg_out)
    def pushButton5_clicked(self):#分割计算
        self.ui.label_roi.setMouseTracking(False)
        # tmp=self.RoiImage.copy()
        # cv2.circle(tmp,(self.pos[0][0], self.pos[0][1]),4,(0,0,255),thickness=-1)
        # cv2.circle(tmp,(self.pos[1][0], self.pos[1][1]),4,(0,0,255),thickness=-1)
        # cv2.imwrite('1.jpg', tmp)
        # set tips point and its label
        input_point = np.array([[self.pos[0][0], self.pos[0][1]], [self.pos[1][0], self.pos[1][1]]])  # 标记点
        input_label = np.array([1, 1])
        masks, scores, logits = predictor.predict(
            point_coords=input_point,
            point_labels=input_label,
            multimask_output=True,
        )
        a = masks[2].reshape(-1, )
        b = np.where(a == True)
        self.area = np.shape(b)[1]
        mask_3d = np.zeros_like(self.RoiImage)
        mask_3d[masks[2]]=(0,0,255)
        merged_image=cv2.addWeighted(self.RoiImage,0.7,mask_3d,0.3,0)
        self.show_cv_img(merged_image, self.ui.label_ad)
        QMessageBox.information(self, "计算结果", f"刃面面积为:{self.area} pixels",QMessageBox.Yes)
        # 最后的Yes表示弹框的按钮显示为Yes,默认按钮显示为OK,不填QMessageBox.Yes即为默认
    def pushButton3_clicked(self):#批量处理
        pass
    def pushButton4_clicked(self):  # 选择提示点
        self.ui.label_roi.setMouseTracking(True)
        self.pos=[]
        predictor.set_image(self.RoiImage)
        QMessageBox.information(self, "提示", "请用鼠标左键点击目标区域获取2个提示点",QMessageBox.Yes)
    def nextImage(self):
        if self.judgeFirst() == 0:
            return 0
        self.imgID += 1
        if self.imgID >len(self.images)-1 :
            self.imgID -= 1
            return 0
        if self.imgID == len(self.images)-1:
            QMessageBox.information(self, "提示", "后面已经没有图片了!",QMessageBox.Yes)
        imagePath = os.path.join(self.imagesPath, self.images[self.imgID])
        self.statusBar.showMessage(f"当前处理的图片是:{self.images[self.imgID]}",5000)
        self.ui.label_numImage.setText(f"第{self.imgID+1}张/总{len(self.images)}张")
        img = cv2.imread(imagePath)
        self.img = cv2.medianBlur(img,5)
    def lastImage(self):
        if self.judgeFirst() == 0:
            return 0
        self.imgID -= 1
        if self.imgID <0 :
            self.imgID += 1
            return 0
        if (self.imgID == 0):
            QMessageBox.information(self, "提示", "上面没有图片了!",QMessageBox.Yes)
        imagePath = os.path.join(self.imagesPath, self.images[self.imgID])
        self.statusBar.showMessage(f"当前处理的图片是:{self.images[self.imgID]}",5000)
        self.ui.label_numImage.setText(f"第{self.imgID + 1}张/总{len(self.images)}张")
        # print(self.imgID)
        img = cv2.imread(imagePath)
        self.img = cv2.medianBlur(img,5)
    # 判断是否选择路径
    def judgeFirst(self):
        if self.imagesPath == "" or self.savePath == "":
            QMessageBox.information(self, "提示", "请选择读取文件路径后继续",QMessageBox.Yes)
            return 0
        return 1
    # 添加一个退出的提示事件
    def closeEvent(self, event):
        """我们创建了一个消息框,上面有俩按钮:Yes和No.第一个字符串显示在消息框的标题栏,第二个字符串显示在对话框,
                    第三个参数是消息框的俩按钮,最后一个参数是默认按钮,这个按钮是默认选中的。返回值在变量reply里。"""
​
        reply=QMessageBox.question(self,'Message',"Are you sure to quit?",QMessageBox.Yes|QMessageBox.No,QMessageBox.No)
        # 判断返回值,如果点击的是Yes按钮,我们就关闭组件和应用,否则就忽略关闭事件
        if reply == QMessageBox.Yes:
            cv2.destroyAllWindows()
            event.accept()
        else:
            event.ignore()
    def mousePressEvent(self, event):
        if event.buttons() == Qt.LeftButton:
            pos = event.pos()  # 获取鼠标点击位置
            self.add_marker(pos)  # 标记点的函数
    def add_marker(self, pos):
        # 将坐标从label坐标系转换为图片坐标系
        img_point = self.ui.label_roi.mapToGlobal(pos) - self.ui.label_roi.mapToGlobal(self.ui.label_roi.rect().topLeft())
        scale_x=self.RoiImage.shape[1]/self.ui.label_roi.width()
        scale_y=self.RoiImage.shape[0]/self.ui.label_roi.height()
        x_img=int(pos.x()*scale_x)
        y_img=int(pos.y()*scale_y)
        self.pos.append([x_img,y_img])
        # 在图片上绘制标记点
        self.draw_marker(img_point)
    def draw_marker(self, point):
        pixmap = self.ui.label_roi.pixmap()
        painter = QPainter(pixmap)
        painter.setPen(QPen(Qt.red, 5))
        painter.drawPoint(point)
        self.ui.label_roi.setPixmap(pixmap)
class ImageWindow(QWidget):
    roiSelected = QtCore.pyqtSignal(QRect)  # 自定义信号
​
    def __init__(self):
        super().__init__()
        self.setWindowTitle("图片窗口")
        self.resize(600,600)
        self.image = []  # 您可以根据实际情况更改图片文件路径
        self.roi = None
        self.setMouseTracking(True)
        self.setFocusPolicy(Qt.StrongFocus)
        self.dragging = False  # 是否正在拖动鼠标
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.scale(0.5,0.5)
        painter.drawPixmap(0,0,self.image)
        if self.roi is not None:
            pen = QPen(Qt.red)
            pen.setWidth(2)
            painter.setPen(pen)
            painter.drawRect(self.roi)
    def keyPressEvent(self, event):
        if event.key() in [Qt.Key_Return, Qt.Key_Space]:
            if self.roi is not None:
                self.roiSelected.emit(self.roi.normalized())
            self.close()
    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.roi = QRect(2*event.pos(), 2*event.pos())
            self.dragging = True
    def mouseMoveEvent(self, event):
        if self.dragging:
            self.roi.setBottomRight(2*event.pos())
            self.update()
    def mouseReleaseEvent(self, event):
        if self.dragging:
            self.roi.setBottomRight(2*event.pos())
            self.update()
            self.dragging = False
if __name__ == "__main__":
    app = QApplication(sys.argv)
    mainWindow = rm()
    mainWindow.show()
    sys.exit(app.exec_())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值