Created
February 14, 2021 12:37
-
-
Save zabir-nabil/495135417aea7272730c83bc6abbe9d2 to your computer and use it in GitHub Desktop.
OpenCV numpy image -> JPEG memory buffer -> bytes and back
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
import numpy as np | |
import sys | |
img = cv2.imread('1.jpg') | |
print(sys.getsizeof(img)) | |
img_encoded = cv2.imencode('.jpg', img)[1] | |
print(sys.getsizeof(img_encoded)) | |
img_bytes = img_encoded.tobytes() # bytes class | |
print(sys.getsizeof(img_bytes)) | |
# 'repair' image from byte array | |
nparr = np.frombuffer(img_bytes, np.byte) | |
img2 = cv2.imdecode(nparr, cv2.IMREAD_REDUCED_COLOR_8) | |
print(sys.getsizeof(img2)) | |
cv2.imwrite('out.jpg', img2, [cv2.IMWRITE_JPEG_PROGRESSIVE]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment