AI 공부 도전기

Python Image to byte file

 

 

PIL

 

import PIL
import io

def PIL_convert(img_path, quality=100):
    img = PIL.Image.open(img_path).convert('RGB')
    buffer = io.BytesIO()
    img.save(buffer, format='jpeg', quality=quality)
    # BytesIO에서 byte 객체 얻기
    val = buffer.getvalue()
    # BytesIO에서 PIL.Image 객체 얻기
    PIL_img = PIL.Image.open(buffer)
    return val, PIL_img

 

 

OpenCV

 

import cv2
import numpy as np

img = cv2.imread('./data/imgs/nature/cat.jpg', cv2.IMREAD_COLOR)
encode_img = np.frombuffer(img, dtype=np.uint8)
cv2 = cv2.imdecode(encode_img, cv2.IMREAD_COLOR)

 

 

비교

 

import cv2, io, time
from PIL import Image
import numpy as np

with open('./data/imgs/nature/cat.jpg', 'rb') as f:
    data = f.read()

cv_start = time.time()
encode_img = np.frombuffer(data, dtype=np.uint8)
cv2 = cv2.imdecode(encode_img, cv2.IMREAD_COLOR)
print('openCV :', time.time() - cv_start)

pil_start = time.time()
buffer = io.BytesIO(data)
pil = Image.open(buffer)
print('PIL :', time.time() - pil_start)

 

 

PIL이 더 빠름

openCV : 0.005984306335449219
PIL : 0.0010259151458740234

 

 

 

공유하기

facebook twitter kakaoTalk kakaostory naver band
loading