我从应用程序后端收到了一份应该是 jpeg 文件的文件列表。然而我一生都无法将它们转换为 PIL 图像对象。当我打电话时
str(curimg)
我回来了:
<type 'str'>
。我尝试过使用 open(), .read, io.BytesIO(img.read() ,并且也不对其执行任何操作,但它一直将其视为字符串。当我打印字符串时,我得到无法识别的字符。有谁知道如何告诉 python 如何将此字符串解释为 jpeg 并将其转换为药丸图像,我可以在其中调用 .size 和 np.array ?
from PIL import Image
import io
Image.open(io.BytesIO(image))
注:
如果图像在网络上;你需要先下载它。
import requests
image = requests.get(image_url).content #download image from web
然后传递给io模块。
io.BytesIO(image)
如果图像在您的高清中;可以直接用PIL打开。
Image.open('image_file.jpg') #image in your HD
您应该能够将 StringIO 对象传递给 PIL 并以这种方式打开它。
即:
from PIL import Image
import StringIO
tempBuff = StringIO.StringIO()
tempBuff.write(curimg)
tempBuff.seek(0) #need to jump back to the beginning before handing it off to PIL
Image.open(tempBuff)
对我来说,上述解决方案都不起作用。
我终于成功地像这样正确地读取了字符串:
from PIL import Image
img = Image.frombytes('RGB', (640, 480), img_str, 'raw')
要测试它,您可以执行类似的操作
image = Image.open("some.png")
print(image.mode, image.size) # OUT: 'RGB' (640, 480)
image = Image.frombytes('RGB', (640, 480), image.tobytes(), 'raw')
image.show()
@CEO(根据this评论)我不知道SQL在这里扮演什么角色,我也不完全确定你想要实现什么,但我记得我遇到了一些问题,这就是有效的我的情况,希望有帮助
frame = self._rawNode.display_frame.copy()
width = int(self.customLayout.geometry().width())
height = int(frame.shape[0] * (width / frame.shape[1]))
display_frame = cv2.cvtColor(cv2.resize(frame, (width, height)), cv2.COLOR_BGR2RGB)
qImg = QtGui.QImage(display_frame.data, width, height, 3 * width, QtGui.QImage.Format_RGB888)
self.pixmap = QtGui.QPixmap(qImg)
self.Imagelabel.setPixmap(self.pixmap)