圖片np.array格式轉成bytes格式
需要將圖片的np.array數據轉換為bytes,轉換之后的bytes數據要等價於open(file,"rb")。
在使用numpy的tobytes(等價於tostring)方法發現得到的bytes數據並不等價於open(file,"rb")數據,需要對array數據進行相同的圖片格式編碼之后,再使用tobytes才行。
import cv2
img_path = "img/test.jpg"
# 打開圖片文件獲取二進制數據
with open(img_path,"rb") as f:
#讀取圖片的二進制數據
bin_contents = f.read()
# 使用opencv讀取圖片
img = cv2.imread(img_path)
# 將numpy的數組轉換為bytes
array_bytes = img.tobytes() # 或者使用img.tostring()
# 對數組的圖片格式進行編碼
success, encoded_image = cv2.imencode(".jpg", img)
# 將數組轉為bytes
img_bytes = encoded_image.tostring()