一、常用图片库:
opencv、PIL
二、图片的数据类型
1.rgb或bgr byte array是一个可变的序列,每个元素的值的取值范围是[0, 255]
<class 'numpy.ndarray'>
2.二进制流
<class 'bytes'>
3.BytesIO对象
<class '_io.BytesIO'>
6.pil image
<class 'PIL.JpegImagePlugin.JpegImageFile'>
三、之间的转换关系
-
BytesIO对象 <-> 二进制
- 二进制 -> BytesIO对象
BytesIO对象 = io.BytesIO(二进制) - BytesIO对象 -> 二进制
二进制 = BytesIO对象.getvalue()
- 二进制 -> BytesIO对象
-
BytesIO对象 <-> np序列
- BytesIO对象 -> np序列
np序列 = cv2.imdecode(np.frombuffer(BytesIO对象.getvalue(), np.uint8), 1) - np序列 -> BytesIO对象
is_success, buffer = cv2.imencode(".jpg", np序列)
BytesIO对象 = io.BytesIO(buffer)
- BytesIO对象 -> np序列
-
二进制 <-> np序列
- 二进制 -> np序列
np序列 = cv2.imdecode(np.frombuffer(二进制, np.uint8), 1) - np序列 -> 二进制
二进制 = np序列.tobytes()
- 二进制 -> np序列
-
PIL <-> rgb序列
- np序列->PIL
PIL_image = Image.fromarray(np序列) - PIL -> np序列
np序列 = numpy.array(PIL_image)
- np序列->PIL
-
PIL <-> BytesIO对象
- BytesIO对象 -> PIL
PIL_image = Image.open(BytesIO对象) - PIL -> BytesIO对象
b = io.BytesIO()
PIL_image.save(b, format='JPEG')
b: BytesIO对象
- BytesIO对象 -> PIL
-
PIL <-> 二进制
-
PIL -> 二进制
b = io.BytesIO()
PIL_image.save(b, format='JPEG')
b.getValue() -
二进制 -> PIL
b = io.BytesIO(二进制)
PIL = Image.open(b)
-
-
bgr和rgb的array转换
RGB序列 = cv2.cvtColor(BGR序列,cv2.COLOR_BGR2RGB)
四、图片可能出现的场景
with open(img_url, 'rb') as f:
a = f.read()
a:二进制
b = io.BytesIO(a)
b:BytesIO对象
import io
from PIL import Image
img = Image.open(a)
img.save("out.jpg")
a:BytesIO对象
img:PIL图片对象
import cv2
img = cv2.imread("/Users/tezign/Downloads/cat.jpg", 1)
cv2.imwrite("out.jpg", img)
img:
<class 'numpy.ndarray'>
网友评论