python 图像的3种常见格式互转

Python 545℃

一、图像在python中的三种格式

1、图像 的文件格式是 二进制 在python中 就是bytes 格式
2、在numpy 中 是 ndarray 格式 shape = 高,宽,色通道
注意: mat 格式 兼容 ndarray 格式 ,例如:cv2.imshow(“”, mat ) 可以传入 ndarray
3、在 PIL 中 是 Image 格式

二、bytes 互转 image

#bytes转img 
bytes_stream = BytesIO(bytes )
img= Image.open(bytes_stream)
#或者 指定尺寸和格式
Image.frombytes('RGB', (width, height), bytes)
#img 转 bytes
img.tobytes()

三、bytes 互转 ndarray

#ndarry 转 bytes
cv2.imencode(后缀, narr)[1].tobytes()
#bytes 转 ndarray
ndarray= cv2.imdecode(np.frombuffer( bytes , np.uint8),cv2.IMREAD_COLOR)

四、image 互转 ndarray

#ndarray 转image
img2 = Image.fromarray(cv2.cvtColor(ndarray, cv2.COLOR_BGR2RGB))
#注意:OpenCV使用的是BGR模式,而PIL使用的是RGB模式。所以需要用上述代码转换
#在OpenCV看来(0,0,255)对应的是(B,G,R)也就是显示红色,而在PIL看来,(0,0,255)对应的是(R,G,B)显示为蓝色
#image 转 ndarray
narr= np.array(img)

转载请注明:零五宝典 » python 图像的3种常见格式互转