Cv2.imdecode() Returns None From Image In Base64, Mimetype Image/jpeg Received Via Websockets
I use websockets to receive video frames. Image is encoded in base64 mimetype image/jpeg. I'm trying to convert image to np.ndarray. When I read image file code works correct. But
Solution 1:
You have to skip data:image/jpeg;base64,
to get only base64
data which will give you correct image data and cv2
will decode and display it.
In example I use split(',', 1)
for this - it gives me data:image/jpeg;base64,
in variable header
and image data in data
.
I use full image in code.
import base64
import numpy as np
import cv2
encoded_image = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4QOIRXhpZgAASUkqAAgAAAAJAAABCQABAAAABwAAAAEBCQABAAAABwAAABIBCQABAAAAAQAAABoBCQABAAAASAAAABsBCQABAAAASAAAACgBCQABAAAAAgAAADIBAgAUAAAAegAAABMCCQABAAAAAQAAAGmHBAABAAAAjgAAANwAAAAyMDE5OjExOjA1IDAyOjE1OjE1AAYAAJAHAAQAAAAwMjIxAZEHAAQAAAABAgMAAKAHAAQAAAAwMTAwAaAJAAEAAAABAAAAAqAJAAEAAAAHAAAAA6AJAAEAAAAHAAAAAAAAAAYAAwEDAAEAAAAGAAAAGgEJAAEAAABIAAAAGwEJAAEAAABIAAAAKAEJAAEAAAACAAAAAQIEAAEAAAAqAQAAAgIEAAEAAABVAgAAAAAAAP/Y/+AAEEpGSUYAAQEAAAEAAQAA/9sAQwABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB/9sAQwEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB/8IAEQgABwAHAwEiAAIRAQMRAf/EABUAAQEAAAAAAAAAAAAAAAAAAAAG/8QAFAEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEAMQAAABjQf/xAAVEAEBAAAAAAAAAAAAAAAAAAAEBf/aAAgBAQABBQJDC1C//8QAFBEBAA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AAAAAP/aAAgBAwEBPxB//8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAgBAgEBPxB//8QAFBABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQABPxAgiWf92Otwc//Z'
header, data = encoded_image.split(',', 1)
#print('header:', header)
#print(' data:', data[:20])
image_data = base64.b64decode(data)
#print('result:', image_data[:20])
np_array = np.frombuffer(image_data, np.uint8)
#print(' array:', np_array[:2])
image = cv2.imdecode(np_array, cv2.IMREAD_UNCHANGED)
#print(' image:', image[:2])
cv2.imshow('image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Result:
(face image with size 7x7)
Post a Comment for "Cv2.imdecode() Returns None From Image In Base64, Mimetype Image/jpeg Received Via Websockets"