본문 바로가기
Language/python

[Python] Image 읽는 방법

by _YUJIN_ 2023. 2. 10.

1. PIL

# pip install Pillow

from PIL import Image

img_path = "test_img.jpg"
img = Image.open(img_path)

#-- "RGB"로 불러오고 싶을 경우
img = Image.open(img_path).convert("RGB")

2. Opencv

  • opencv를 활용해서 이미지를 불러오면 "RGB"가 아니라 "BGR" 형태로 불러오는것을 확인 할 수 있다. 
  • 이를 RGB 형태의 배열로 변환해서 이미지를 확인하는 것을 추천한다. 
# pip install opencv-python

import cv2
img_path = "test_img.jpg"

img = cv2.imread(img_path)

#-- BGR 형태의 배열을 RGB 형태의 배열로 변환할 때 
rgb_img = cv2.cvtColor(img , cv2.COLOR_BGR_2_RGB)

3. io.BytesIO

  • PIL과 Opencv는 이미지 경로를 변수로 받아와서 이미지를 읽지만, 객체를 넘겨주고싶을때는 io.BytesIO( ) 함수를 사용하면 된다.
  • iO.BytesIO( ) 객체를 넘겨주면 객체 내에 저장된 bytes정보를 불러와서 이미지를 읽게 된다.
    그래서, 결과를 확인해보면 Object 형태로 나오는 것을 확인할 수 있다.
import os
from PIL import Image

img_path = "img_test.jpg"
with open(img_path, "rb") as f:
	data = f.read()
    
data_io = io.BytesIO(data)
print(data_io)   #-- output : <_io.BytesIO at 0x7f48ee73f220>

#-- 객체로 저장된 이미지를 불러오고 싶을 때
image = Image.open(data_io)
반응형