我使用opencv将图片转换为灰度,如何在pyqt4上显示图片?

时间:2016-05-17 18:54:21

标签: python opencv pyqt4

这是打开文件的操作:

def file_open(self):
    global img_raw

    filename = QtGui.QFileDialog.getOpenFileName(self,
                          self.tr("Open Image"), ".",
                          self.tr("Image Files (*.jpg;*.bmp;*.png);;All Files (*)"))
    #open the file 

    if not filename.isEmpty():
        cvfilename = filename.toLocal8Bit().data()
        #convert Qstrig to char*            
        img_raw = cv2.imread(cvfilename)
        #read image with opencv 

我使用opencv转换图像:

def rgb2gray(self):
    global img_gray, img_raw 
    img_gray = cv2.cvtColor(img_raw, cv2.COLOR_BGR2GRAY)
    #image: RGB2Gray

这是我编写的用于显示图像的代码:

    pixmap = QtGui.QPixmap.fromImage(image)
    scaled_pixmap = pixmap.scaled(self.label2.size())
    self.label2.setPixmap(scaled_pixmap)

如何在label2上显示img_gray?

1 个答案:

答案 0 :(得分:1)

您的代码并不完整,所以我附上了一个可能有用的自包含示例:

import cv2
import sys
from PySide import QtGui, QtCore
from threading import Thread


class MainWindow(QtGui.QMainWindow):
    def __init__(self, cam=0, parent=None):
        super(MainWindow, self).__init__(parent)

        self.title = "Image"

        widget = QtGui.QWidget()
        self.layout = QtGui.QBoxLayout(QtGui.QBoxLayout.LeftToRight)

        self.image = QtGui.QLabel()

        self.layout.addWidget(self.image)
        self.layout.addStretch()

        self.setCentralWidget(widget)
        widget.setLayout(self.layout)

        self.setMinimumSize(640, 480)
        self.frame = cv2.imread("image.jpg")

        try:
            self.height, self.width = self.frame.shape[:2]

            img = QtGui.QImage(self.frame, self.width, self.height, QtGui.QImage.Format_RGB888)
            img = QtGui.QPixmap.fromImage(img)
            self.image.setPixmap(img)

        except:
            pass

    def closeEvent(self, event):
        cv2.destroyAllWindows()
        event.accept()


if __name__ == "__main__":
    print cv2.__version__
    print (sys.version) 
    app = QtGui.QApplication(sys.argv)
    window = MainWindow(0)
    window.show()
    sys.exit(app.exec_())