我想用PIL加载图像,应用一些过滤然后在GUI上显示图像。
我写了一些示例应用程序:
from PyQt4 import QtCore, QtGui
from PIL import Image, ImageQt
class TwoDToThreeD(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
layout = QtGui.QGridLayout()
self.btnOpen = self.createButton("Open File", self.open)
layout.addWidget(self.btnOpen, 4, 0)
self.imageLabel = QtGui.QLabel()
self.imageLabel.setBackgroundRole(QtGui.QPalette.Base)
self.imageLabel.setSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored)
self.imageLabel.setScaledContents(True)
layout.addWidget(self.imageLabel, 0, 2, 4, 1)
layout.setColumnStretch(1, 10)
layout.setColumnStretch(2, 20)
self.setLayout(layout)
def createButton(self, text, member):
button = QtGui.QPushButton(text)
button.clicked.connect(member)
return button
def open(self):
fileName = (QtGui.QFileDialog.getOpenFileName(self, "Open File", QtCore.QDir.currentPath()))
if fileName:
print (fileName)
self.imgPil = Image.open(str(fileName))
# print (PIL.VERSION)
print (self.imgPil.format, self.imgPil.size, self.imgPil.mode)
# imgPil.show()
img_tmp = ImageQt.ImageQt(self.imgPil)
image = QtGui.QImage(img_tmp)
if image.isNull():
QtGui.QMessageBox.information(self, "Image Viewer", "Cannot load %s." % fileName)
return
self.imageLabel.setPixmap(QtGui.QPixmap.fromImage(image))
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
dialog = TwoDToThreeD()
dialog.show()
sys.exit(app.exec_())
加载* .png效果很好。但是当我尝试加载* .jpg python时崩溃:
python.exe has stopped working
A problem caused the program to stop working correctly.
Windows will close the program and notify you if a solution is
available.
我在Windows 8.1 64Bit上使用python 2.7 64bit,python 2.7 32bit和python 3.4 64bit尝试了相同的源代码。
对于所有3个版本,我得到相同的结果。
是否有人遇到类似问题或知道解决方案? 我甚至无法调试代码,因为它直到" end"然后崩溃:(
答案 0 :(得分:0)
基于github
的示例def pil2pixmap(self,im):
if im.mode == "RGB":
pass
elif im.mode == "L":
im = im.convert("RGBA")
data = im.convert("RGBA").tostring("raw", "RGBA")
qim = QtGui.QImage(data, im.size[0], im.size[1], QtGui.QImage.Format_ARGB32)
pixmap = QtGui.QPixmap.fromImage(qim)
return pixmap
def open(self):
fileName = (QtGui.QFileDialog.getOpenFileName(self, "Open File", QtCore.QDir.currentPath()))
if fileName:
imgPil = Image.open(str(fileName))
# do your work then convert
self.imageLabel.setPixmap(self.pil2pixmap(imgPil))
答案 1 :(得分:0)
在PyQt5
和Python 3.8中,这不再起作用。我将如下编写pil2pixmap
函数。
import io
from PyQt5.QtGui import QImage, QPixmap
from PIL import Image
def pil2pixmap(image):
bytes_img = io.BytesIO()
image.save(bytes_img, format='JPEG')
qimg = QImage()
qimg.loadFromData(bytes_img.getvalue())
return QPixmap.fromImage(qimg)
其中参数image
例如是image = Image.open('path_to_a_picture')
注意:要使用QGuiApplication必须运行的功能