我正在尝试将 JPEG 的 base64 表示形式转换为可与 OpenCV 一起使用的图像。问题是我希望能够在不必物理保存照片的情况下执行此操作(我希望它保留在内存中)。有没有更新的方法来完成这个?
我正在使用 python 3.6.2 和 OpenCV 3.3
这是我尝试转换的输入类型的部分示例:
/9j/4AAQSkZJRgABAQAASABIAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAA....
我已经尝试过这些问题提供的解决方案,但不断得到相同的“内置操作的错误参数类型”错误:
最佳答案
这是一个使用 imageio 而不是 PIL 的 python 3.6 示例。它首先加载图像并将其转换为 b64_string。然后可以发送此字符串并按如下方式重建图像:
import base64
import io
import cv2
from imageio import imread
import matplotlib.pyplot as plt
filename = "yourfile.jpg"
with open(filename, "rb") as fid:
data = fid.read()
b64_bytes = base64.b64encode(data)
b64_string = b64_bytes.decode()
# reconstruct image as an numpy array
img = imread(io.BytesIO(base64.b64decode(b64_string)))
# show image
plt.figure()
plt.imshow(img, cmap="gray")
# finally convert RGB image to BGR for opencv
# and save result
cv2_img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
cv2.imwrite("reconstructed.jpg", cv2_img)
plt.show()
关于python - 将 base64 字符串转换为与 OpenCV 兼容的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45923296/