Skip to content

Instantly share code, notes, and snippets.

@zabir-nabil
Created February 14, 2021 12:37
Show Gist options
  • Save zabir-nabil/495135417aea7272730c83bc6abbe9d2 to your computer and use it in GitHub Desktop.
Save zabir-nabil/495135417aea7272730c83bc6abbe9d2 to your computer and use it in GitHub Desktop.
OpenCV numpy image -> JPEG memory buffer -> bytes and back
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