Search code examples
pythonpython-2.7opencvpyqt4qpixmap

How to use Qstring for cv2.imread PyQT4


I am new in python. I am building my first application. My problem probably quite simple but I do need help. I have 2 labels and 2 buttons.

The 1st button calls function browse and will browse the image files and set the image on label 1. Then, the 2nd button calls the function applyBrowsedImage and will take the image from label 1 and set it to cv2.imread, so it can be used for image processing.

But the program shows error:

TypeError: expected string or Unicode object, QString found


def browse(self, path):
    filePath = QtGui.QFileDialog.getOpenFileName(self, 'a file','*.jpg')
    self.path = filePath
    fileHandle = open(filePath, 'r')
    pixmap = QPixmap(filePath)
    self.label1.setPixmap(pixmap)

def ApplyBrowsedImage(self):
    ##a = cv2.imread('image.jpg')   it works here
    a = cv2.imread(self.path) ##but does not work here
    pixmap = QPixmap(a)
    self.label2.setPixmap(pixmap)
    print("not yet")

I am open to any reference or method.

Thanks in advance.


Solution

  • Qt provides some of its own types for things like strings because Qt is a C++ library and apparently these things are hard in C++. When using PyQt, you have the option of either using Qt strings (QString) or Python native strings. Old versions of PyQt (PyQt4) use QString by default where as new versions (PyQt5) use Python strings.

    The best option in my opinion is to use native Python types, which allows you to easily integrate with other libraries that also expect native Python types without doing a whole bunch of annoying conversions.

    To do this, prior to importing PyQt (so put it at the top the python script you launch), add the following code:

    # do this BEFORE importing PyQt for the first time
    import sip
    for name in ["QDate", "QDateTime", "QString", "QTextStream", "QTime", "QUrl", "QVariant"]:
        sip.setapi(name, 2)
    # now you can import PyQt...
    

    This ensures that you use native Python types instead of the types listed above, and your error will vanish.