import sys from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QPushButton, QFileDialog import os import numpy as np import cv2 from skimage import filters class ImageFileViewer(QWidget): def __init__(self): super().__init__() self.setGeometry(100, 100, 500, 500) # 设置窗口大小和位置 self.setWindowTitle("图片打分工具") self.layout = QVBoxLayout() self.label = QLabel("暂无图片") self.button = QPushButton("请选择图片") self.button.clicked.connect(self.select_image) self.layout.addWidget(self.label) self.layout.addWidget(self.button) self.setLayout(self.layout) def _imageToMatrix(self, image): """ 根据名称读取图片对象转化矩阵 :param strName: :return: 返回矩阵 """ imgMat = np.matrix(image) return imgMat def preImgOps(self, img): """ 图像的预处理操作 :param img: 图像的而明朝 :return: 灰度化和resize之后的图片对象 """ # 预处理操作 try: reImg = cv2.resize(img, (300, 400), interpolation=cv2.INTER_CUBIC) # img2gray = cv2.cvtColor(reImg, cv2.COLOR_BGR2GRAY) # 将图片压缩为单通道的灰度图 return reImg,img2gray, True except Exception as e: return None, None, False def ReadImage(self, im_file): """ 读取图片 :param im_file: 图像的路径 :return: 利用opencv读取的完整图像img 托虫板内接四边形图像cutimg 内接四边形的坐标c[xmin,ymin,xmax,ymax] """ try: img = cv2.imdecode(np.fromfile(im_file, dtype=np.uint8), cv2.IMREAD_COLOR) ImgShape = img.shape center = [ImgShape[1]/2,ImgShape[0]/2] #圆盘中心 radius = int(ImgShape[0]/2) #圆盘半径 length = pow(2,0.5)*radius #圆的内接正方形边长 Size = int(length/2) xmin = int(center[0] - Size) xmax = int(center[0] + Size) ymin = int((center[1] - Size)*1.1) ymax = int(center[1] + Size) c = [xmin,ymin,xmax,ymax] cutimg = img[ymin:ymax,xmin:xmax] return img,cutimg,c, True except Exception as e: return None, None, None, False def getFileName(self, imageFile): url, FileName = os.path.split(imageFile) tamp = [] tamp.append(FileName) return tamp #图像清晰度检测 def predict(self, imageFile): """ 图像清晰度检测 Args: imageFile(dir or file):单张图片或者存放图片的文件夹 """ result = [] #存放清晰度评分 imgList = [] #存放识别后图片 if os.path.isfile(imageFile): img,cutimg,c, is_get = self.ReadImage(imageFile) if is_get: reImg, img2gray, is_imgs= self.preImgOps(cutimg) if is_imgs: f = self._imageToMatrix(img2gray) tmp = filters.sobel(f) source=np.sum(tmp**2) source=np.sqrt(source) result.append(source) imgList.append(img) return result def select_image(self): file_dialog = QFileDialog() image_file, _ = file_dialog.getOpenFileName(self, "选择图片", "", "支持图片格式 (*.png *.jpg *.jpeg)") if image_file: result = self.predict(image_file) self.label.setText(f"图片 {image_file.split('/')[-1]}:\n得分 {result[0]}") if __name__ == "__main__": app = QApplication(sys.argv) viewer = ImageFileViewer() viewer.show() sys.exit(app.exec_())