解码base64时得到黑色图像

时间:2018-01-15 09:02:37

标签: python numpy base64 cv2

当我解码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)

2 个答案:

答案 0 :(得分:1)

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

Convert base64 String to an Image that's compatible with OpenCV中的

是代码:

# 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

答案 1 :(得分:1)

我找到了解决方案,我们正在使用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)