使用tobytes之前,先將ndarray 編碼成和圖片一樣的格式
import numpy as np
import cv2
src = cv2.imread('timg.jpg', 1)
print(src.shape)
_,encode_image = cv2.imencode(".png",src)
encode_image = encode_image.tobytes()
#還原方法
img1 = np.frombuffer(encode_image, np.uint8)
print("img1 shape ", img1.shape) # (83653,)
img_cv = cv2.imdecode(img1, cv2.IMREAD_ANYCOLOR)
print("img_cv shape ", img_cv.shape) # (388, 690, 3)
cv2.imwrite("test.jpg", img_cv)
print('ok')