gpt4 book ai didi

python - Pillow (PIL) 到 QImage 的转换 -> python.exe 已停止工作

转载 作者:行者123 更新时间:2023-11-28 19:19:50 25 4
gpt4 key购买 nike

我想用 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 64 位上使用 python 2.7 64 位、python 2.7 32 位和 python 3.4 64 位尝试了完全相同的源。

对于所有 3 个版本,我得到相同的结果。

有没有人遇到过类似的问题或者知道解决办法?我什至无法调试代码,因为它运行到“结束”然后崩溃:(

最佳答案

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)

例如参数 imageimage = Image.open('path_to_a_picture')

注意:要使用 QGuiApplication 必须运行的函数

关于python - Pillow (PIL) 到 QImage 的转换 -> python.exe 已停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28086613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com