1. PIL 与 cv2 互相转化

import cv2from PIL import Imageimport numpy as np# PIL 转 cv2img= Image.open("test.jpg")img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)print(type(img))# cv2 转 PILimg = cv2.imread("test.jpg")img= Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))print(type(img))

2. PIL 与 bytes 互相转化

'''    bytes 转 PIL '''# 第一类:转换 本地的bytes图片 为 PILwith open('test.jpg', 'rb') as f:    content = f.read()  local_img = Image.open(BytesIO(content))   print(type(local_img))  # 第二类:转换 网络上的bytes图片 为 PILurl = 'https://z3.ax1x.com/2021/07/13/WAuYJU.jpg'content = requests.get(url, stream=True).contentnet_img = Image.open(BytesIO(content))   # BytesIO实现了在内存中读写Bytesprint(type(net_img))    '''    PIL 转 bytes'''img_bytes  = BytesIO()img = Image.open('test.jpg', mode='r')img.save(img_bytes, format='JPEG')img_bytes = img_bytes.getvalue()print(type(img_bytes))  

3. cv2 与bytes 互相转化

import numpy as npimport cv2# bytes 转 numpyimg_buffer_numpy = np.frombuffer(img_bytes, dtype=np.uint8)  # 将 图片字节码bytes  转换成一维的numpy数组 到缓存中img_numpy = cv2.imdecode(img_buffer_numpy, 1)   # 从指定的内存缓存中读取一维numpy数据,并把数据转换(解码)成图像矩阵格局# numpy 转 bytes _, img_encode = cv2.imencode('.jpg', img_numpy)img_bytes = img_encode.tobytes()