OpenCV image 또는 PIL image와 BytesIO 연동

|

데모를 만들거나 할 때, bytesio를 써서 쉽게쉽게 연동하고싶은데, 맨날 까먹어서 정리해놓는다.

OpenCV 이미지와 bytesio 연동

from io import BytesIO

img = cv2.imread("../Documents/3.jpg")
img.shape   # (438, 763, 3)
type(img)   # <class 'numpy.ndarray'>
img.dtype   # dtype('uint8')

# 둘 다 가능
img_str = cv2.imencode('.jpg', img)[1].tostring()
type(img_str)  #<class 'bytes'>
img_str = cv2.imencode('.jpg', img)[1].tobytes()
type(img_str)  #<class 'bytes'>

bytesio = BytesIO(img_str)

PIL image와 bytesio 연동


from io import BytesIO
from PIL import Image, ImageDraw

image = Image.new("RGB", (300, 50))
draw = ImageDraw.Draw(image)
draw.text((0, 0), "This text is drawn on image")

byte_io = BytesIO()
image.save(byte_io, 'PNG')  # 여기는 filename이나 file object 둘 다 가능하다.