1. PIL 与 cv2 相互转化
import cv2 from PIL import Image import numpy as np # PIL 转 cv2 img= Image.open("test.jpg") img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR) print(type(img)) # cv2 转 PIL img = cv2.imread("test.jpg") img= Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB)) print(type(img))
2. PIL 与 bytes 相互转化
''' bytes 转 PIL ''' # 第一类:转换 本地的bytes图片 为 PIL with open('test.jpg', 'rb') as f: content = f.read() local_img = Image.open(BytesIO(content)) print(type(local_img)) # 第二类:转换 网络上的bytes图片 为 PIL url = 'https://z3.ax1x.com/2021/07/13/WAuYJU.jpg' content = requests.get(url, stream=True).content net_img = Image.open(BytesIO(content)) # BytesIO实现了在内存中读写Bytes print(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 np import cv2 # bytes 转 numpy img_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()
原创文章,作者:,如若转载,请注明出处:https://blog.ytso.com/272115.html