一、常用圖片庫:
opencv、PIL
二、圖片的數(shù)據(jù)類型
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)
四、圖片可能出現(xiàn)的場景
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'>