解码base64时得到黑色图像

Got black image when decode base64

当我解码 base64 编码的裁剪面部图像时,它变黑并且数据损坏。

这是一段代码:

def create_learn_msg(db_name, person_name, last_location, images, labels):
    json_string = {}
    cv2.imwrite('%s/%s.png' % ("faces/", "original-image"), images[1])
    print(type(images[1]))  # <type 'numpy.ndarray'>
    image_string = images[1].tostring()
    encode_string = base64.b64encode(image_string)
    # Decode test
    decode_string = base64.b64decode(encode_string)
    decode_image = numpy.fromstring(decode_string, dtype=numpy.uint8)

    print(type(decode_image))  # <type 'numpy.ndarray'>
    cv2.imwrite('%s/%s.png' % ("faces/", "decode-image"), decode_image)

    json_string['data'] = {'type': "learn", 'db_name': db_name, 'person_name': person_name,
                           'last_location': last_location, 'image1': base64.b64encode(images[0]),
                           'image2': base64.b64encode(images[1]), 'label1': labels[0], 'label2': labels[1]}

    return json.dumps(json_string)

这个cv2.imwrite('%s/%s.png' % ("faces/", "decode-image"), q)不解码base64编码的数据

中的代码是:

# 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()

( https://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html )

我找到了解决方案,我们使用的是 cv2 图像,所以我们应该在 base64 编码之前添加 cv2.imencode,在 base64 解码之后添加 cv2.imdecode,如下所示:

retval, image_string = cv2.imencode('.png', images[1])
encode_string = base64.b64encode(image_string)
decode_string = base64.b64decode(encode_string)
decode_image = numpy.fromstring(decode_string, dtype=numpy.uint8)
original_image = cv2.imdecode(decode_image, 1)