灰度图像裁剪并转换为QPixmap

时间:2019-02-20 18:06:06

标签: python python-3.x pyqt pyqt5 opencv3.0

我试图创建一个窗口,该窗口根据给定的百分比值裁剪灰度图像,并在QLabel中显示输出。我的代码有两个问题:

  1. 裁切的图像有些倒转或模糊,具体取决于 输入值
  2. 裁剪功能对更高的百分比无效 值

我尝试引用:PyQt5 QImage from Numpy Array,但是当我的图像必须作为灰度处理时,我无法完全理解它们之间的差异。

使用Qt-designer创建的我的Ui文件在此处给出:https://pastebin.com/n7jpv9dS

import Ui_ImageCrop_Test
import numpy as np
import cv2, sys, math, re
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtCore import Qt

class ImageCrop(Ui_ImageCrop_Test.Ui_MainWindow, QMainWindow):
    def __init__(self, parent=None):
        super(ImageCrop, self).__init__()
        self.setupUi(self)
        self.pushButton_1.clicked.connect(self.show_button)
        self.pushButton_2.clicked.connect(self.crop_button)

    def show_button(self):
        image = QImage("myImage.jpg")
        image = image.convertToFormat(QImage.Format_ARGB8565_Premultiplied)
        pixmap = QPixmap(image)
        w = int(self.label_1.width() - 4.0)
        h = int(self.label_1.height() - 4.0)
        smaller_pixmap = pixmap.scaled(w, h, Qt.IgnoreAspectRatio, Qt.FastTransformation)
        self.label_1.setPixmap(smaller_pixmap)
        self.label_1.setScaledContents(True)

    def crop_button(self):
        self.label_1.clear()
        img = cv2.imread("myImage.jpg",
                         cv2.IMREAD_GRAYSCALE)

        string_percent = self.lineEdit_1.text()
        string_percent = re.sub("\D", "", string_percent)
        percent = float(string_percent)

        image = crop_img(img, percent)
        image = np.asarray(image).copy()
        qimage = QImage(image, image.shape[1], image.shape[0], QImage.Format_Grayscale8)
        pixmap = QPixmap(qimage)
        w = int(self.label_1.width() - 4.0)
        h = int(self.label_1.height() - 4.0)
        smaller_pixmap = pixmap.scaled(w, h, Qt.IgnoreAspectRatio, Qt.FastTransformation)
        self.label_1.setPixmap(smaller_pixmap)
        self.label_1.setScaledContents(True)


def crop_img(img, percent):
    x1, y1 = 0, 0
    x2, y2 = img.shape[1], img.shape[0]
    w, h = x2 - x1, y2 - y1   
    w_curr, h_curr = int(w * math.sqrt(percent * 0.01)), int(h * math.sqrt(percent * 0.01))
    kx, ky = (w - w_curr) * 0.5, (h - h_curr) * 0.5
    x3, y3 = int(x1 + kx), int(y1 + ky)    
    img_cropped = img[int(y3):int(y3 + h_curr), int(x3):int(x3 + w_curr)]
    return img_cropped

def main():
    app = QApplication(sys.argv)
    form1 = ImageCrop()
    form1.show()
    app.exec_()    

if __name__ == '__main__': main()

0 个答案:

没有答案
相关问题