Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I used opencv to convert a picture to grayscale,how to display the picture on pyqt4?

This is the action to open the file :

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 

and I use the opencv to convert the image:

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

This is the code I write to show the image:

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

how can I show the img_gray on the label2?

like image 386
Thera Avatar asked Jan 28 '26 22:01

Thera


1 Answers

Your code is not really complete, so I have attached a self-contained example which might help:

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_())
like image 192
tfv Avatar answered Feb 02 '26 23:02

tfv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!