我有以下图像:
转换为base64,它看起来像这样:
import base64
filename = 'image.jpg'
with open(filename, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read())
image_file.close()
with open("encoded_string.txt", "w") as converted_file:
converted_file.write(str(encoded_string))
converted_file.close()
在这里下载输出文件(base64):https://file.io/NXV7v4
现在,我的问题是:
如何在不存储的情况下检索转换后的图像并将其显示在jupyter笔记本中?
基于[this] [2]问题,我尝试了:
from PIL import Image
import cv2
import io
# Take in base64 string and return cv image
def stringToRGB(base64_string):
imgdata = base64.b64decode(str(base64_string))
image = Image.open(io.BytesIO(imgdata))
return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)
stringToRGB(encoded_string)
但是我得到了:
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
<ipython-input-43-2564770fa4af> in <module>()
----> 1 stringToRGB(encoded_string)
<ipython-input-42-538f457423e9> in stringToRGB(base64_string)
18 def stringToRGB(base64_string):
19 imgdata = base64.b64decode(str(base64_string))
---> 20 image = Image.open(io.BytesIO(imgdata))
21 return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)
~\Anaconda3\lib\site-packages\PIL\Image.py in open(fp, mode)
2655 warnings.warn(message)
2656 raise IOError("cannot identify image file %r"
-> 2657 % (filename if filename else fp))
2658
2659 #
OSError: cannot identify image file <_io.BytesIO object at 0x00000224D6E7D200>
答案 0 :(得分:4)
也许更简单?
from IPython import display
from base64 import b64decode
display.Image(b64decode(base64_data)
答案 1 :(得分:1)
我不知道您的错误来自哪里,但这对我有用:
from PIL import Image
import io
import matplotlib.pyplot as plt
# Take in base64 string and return a numpy image array
def stringToRGB(base64_string):
imgdata = base64.b64decode(base64_string)
image = Image.open(io.BytesIO(imgdata))
return np.array(image)
plt.imshow(stringToRGB(encoded_string))
答案 2 :(得分:1)
另一种选择是让浏览器负责解码并将base64字符串放入img标签中:
from IPython import display
im = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
display.HTML(f'<img src="data:image/png;base64,{im}" />')