본문 바로가기

D.S/Python

210815일 - 바이너리 이미지 변환 관련

728x90

 

 

이미지를 파이썬 open() 을 사용하면 bytes 객체에 담기게 됨

 

바이너리 이미지 변환 

1. PIL을 사용

 

데이터 변환과정:  bytes 객체 -> io.BytesIO 객체에 옮겨 담음 -> PIL.Image 객체에 담음

import io
from PIL import Image
path = './test_image.jpg'
with open(path, 'rb') as f:
    data = f.read()

data_io = io.BytesIO(data)
img = Image.open(data_io)

 

* BytesIO에서 다시 byte 객체 얻기

print(type(data))  # <class 'bytes'>
print(type(data_io))  # _io.BytesIO
data_io.getvalue() == data # True

 

 

역변환:  PIL.Image -> io.BytesIO  -> bytes 

output = io.BytesIO()

img_pil.save(output, 'PNG')

binary_pil = output.getvalue()   # == data

 

2. OpenCV 사용

 

데이터 변환과정:  bytes객체 -> numpy 1-D array -> cv.imdecode()

import cv2
import numpy as np

img_p = 'img.jpg'
with open(img_p, 'rb') as f:
    img_b = f.read()

# fromstring은 decrecated됨. 그대신 frombuffer 사용을 권장하고 있다.
# img_ = np.fromstring(img_b, dtype = np.uint8)
'''
/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:3: 
DeprecationWarning: The binary mode of fromstring is deprecated, 
as it behaves surprisingly on unicode inputs. Use frombuffer instead
This is separate from the ipykernel package so we can avoid doing imports until
'''

# bytes값을 int8값의 1-D array형태로 바꿔줌.
img_ = np.frombuffer(data, dtype=np.uint8) 
# array([137,  80,  78, ...,  66,  96, 130], dtype=uint8)

img_cv = cv2.imdecode(img_, cv2.IMREAD_COLOR)

 

참조: 

https://ballentain.tistory.com/50

반응형