Converting numpy image to QPixmap

后端 未结 1 790
离开以前
离开以前 2021-01-23 00:33

I am student of Computer-Sciences and I am learning image processing using OpenCv with Python. I am working on gender detection us

1条回答
  •  执笔经年
    2021-01-23 01:21

    You must use the QImage::Format_Indexed8 format to convert the numpy array to QImage. I have implemented a method that converts some types of numpy arrays to QImage

    def numpyQImage(image):
        qImg = QtGui.QImage()
        if image.dtype == np.uint8:
            if len(image.shape) == 2:
                channels = 1
                height, width = image.shape
                bytesPerLine = channels * width
                qImg = QtGui.QImage(
                    image.data, width, height, bytesPerLine, QtGui.QImage.Format_Indexed8
                )
                qImg.setColorTable([QtGui.qRgb(i, i, i) for i in range(256)])
            elif len(image.shape) == 3:
                if image.shape[2] == 3:
                    height, width, channels = image.shape
                    bytesPerLine = channels * width
                    qImg = QtGui.QImage(
                        image.data, width, height, bytesPerLine, QtGui.QImage.Format_RGB888
                    )
                elif image.shape[2] == 4:
                    height, width, channels = image.shape
                    bytesPerLine = channels * width
                    fmt = QtGui.QImage.Format_ARGB32
                    qImg = QtGui.QImage(
                        image.data, width, height, bytesPerLine, QtGui.QImage.Format_ARGB32
                    )
        return qImg
    

    So in your case it should be:

    def crop(self):
        if not self.work_IMAGE:
            return
        img = cv2.imread(self.work_IMAGE, cv2.IMREAD_GRAYSCALE)
        if img is None:
            return
        height, width = img.shape[:2]
        start_row, strt_col = int(height * 0.40), int(width * 0.15)
        end_row, end_col = int(height * 0.60), int(width * 0.90)
        croped = img[start_row:end_row, strt_col:end_col].copy()
        qImg = numpyQImage(croped)
        pixmap = QtGui.QPixmap.fromImage(qImg)
        pixmap = pixmap.scaled(self.roi_label.size(), QtCore.Qt.KeepAspectRatio)
        self.roi_label.setPixmap(pixmap)
        self.roi_label.setAlignment(QtCore.Qt.AlignCenter)
    

    0 讨论(0)
提交回复
热议问题