Got black image when decode base64


When I decode a base64 encoded cropped face image, it goes black and the data corrupts.

This is the piece of code:

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)
Asked By: Farshid616



this cv2.imwrite('%s/%s.png' % ("faces/", "decode-image"), q) does not decode the base64 encoded data

in Convert base64 String to an Image that's compatible with OpenCV is code for this :

# reconstruct image as an numpy array
img = imread(io.BytesIO(base64.b64decode(b64_string)))

# show image
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)

( )

Answered By: ralf htp

I found the solution, we’re using the OpenCV image so we should add cv2.imencode before base64 encoding and cv2.imdecode after base64 decoding as following:

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)
Answered By: Farshid616
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.