简体   繁体   English

如何将Qstring用于cv2.imread PyQT4

[英]How to use Qstring for cv2.imread PyQT4

I am new in python. 我是python的新手。 I am building my first application. 我正在构建我的第一个应用程序。 My problem probably quite simple but I do need help. 我的问题可能很简单,但我确实需要帮助。 I have 2 labels and 2 buttons. 我有2个标签和2个按钮。

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. 第一个按钮调用browse功能,将浏览图像文件并将图像设置在标签1上。然后,第二个按钮调用函数applyBrowsedImage并将图像从标签1提取并将其设置为cv2.imread,因此可以使用它用于图像处理。

But the program shows error: 但是程序显示错误:

TypeError: expected string or Unicode object, QString found TypeError:预期的字符串或Unicode对象,找到QString


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. 提前致谢。

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++. Qt为诸如字符串之类的东西提供了一些自己的类型,因为Qt是一个C ++库,显然这些东西在C ++中很难。 When using PyQt, you have the option of either using Qt strings ( QString ) or Python native strings. 使用PyQt时,您可以选择使用Qt字符串( QString )或Python本机字符串。 Old versions of PyQt (PyQt4) use QString by default where as new versions (PyQt5) use Python strings. 默认情况下,旧版本的PyQt(PyQt4)使用QString ,而新版本(PyQt5)使用Python字符串。

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. 我认为最好的选择是使用本机Python类型,这使您可以轻松地与也期望本机Python类型的其他库集成,而无需进行大量烦人的转换。

To do this, prior to importing PyQt (so put it at the top the python script you launch), add the following code: 为此, 在导入PyQt之前 (因此将其放在您启动的python脚本的顶部),添加以下代码:

# 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. 这样可以确保您使用本机Python类型而不是上面列出的类型,并且错误将消失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM