Aug.01.21

iissaacc·2021년 8월 1일
1

TIL

목록 보기
4/10

Prologue

그동안 이미지를 불러올 때 주소값을 넘겼는데 바이너라 파일을 넘기는 방법을 쓰는 코드를 봤다.

How to read Image file

이미지 파읽을 읽는 데는 크게 두 가지 방식이 있다.

  1. 이미지 주소를 전달
  2. binary object를 전달

굳이 코드를 더 써가면서 쓰는 이유가 있나 찾아봤다. 같은 파일이면 원본보다 크기를 많이 줄일 수 있어서 전송속도와 저장공간에서 이점을 볼 수 있다고 한다.

Parse image directory

import os
from PIL import Image

file_path = os.path.join('path', 'to', 'the', 'folder')
file = [file for file in os.listdir(file_path)]
img_dir = os.path.join(file_dir, file[0])

Image.open(img_dir)

Parse binary file

import os
from PIL import Image
from io import BytesIO

file_path = os.path.join('path', 'to', 'the', 'folder')
file = [file for file in os.listdir(file_path)]
img_dir = os.path.join(file_dir, file[0])

with open(img_dir, 'rb') as f:
    data = f.read()
data_io = BytesIO(data)
Image.open(data_io)

Epilogue

근데 여기서 드는 의문점 한 가지. 형변환하는 비용이 크지 않나 싶어서 시간을 재봤더니 바이너리 파일을 넘기는 게 약 2배정도 빠르다. 정수에서 문자열로 바꾸는 만큼 비용이 크지는 않은 것 같다. 앞으로 뭐든 바이너리로 바꾸도록 하자.

0개의 댓글