问题分析
需要将图片的numpy的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()