【发布时间】:2021-08-30 21:58:14
【问题描述】:
我需要将图像编码为二进制,将其发送到服务器并再次将其解码回图像。 解码方法是:
def decode_from_bin(bin_data):
bin_data = base64.b64decode(bin_data)
image = np.asarray(bytearray(bin_data), dtype=np.uint8)
img = cv2.imdecode(image, cv2.IMREAD_COLOR)
return img
我们使用 OpenCV 对图像进行编码:
def encode_from_cv2(img_name):
img = cv2.imread(img_name, cv2.IMREAD_COLOR) # adjust with EXIF
bin = cv2.imencode('.jpg', img)[1]
return str(base64.b64encode(bin))[2:-1] # Raise error if I remove [2:-1]
你可以运行:
raw_img_name = ${SOME_IMG_NAME}
encode_image = encode_from_cv2(raw_img_name)
decode_image = decode_from_bin(encode_image)
cv2.imshow('Decode', decode_image)
cv2.waitKey(0)
我的问题是:为什么我们必须从 base64 编码中去除前两个字符?
【问题讨论】:
标签: python-3.x sockets base64 opencv3.0 opencv-python