hotamul의 개발 이야기

[Python] image 파일 numpy.ndarray로 불러오기 본문

dev/Python

[Python] image 파일 numpy.ndarray로 불러오기

hotamul 2023. 1. 1. 11:35

image 파일을 numpy.ndarray로 불러오는 방법은 3가지가 있다.

OpenCV

$ pip install opencv-python-headless
import cv2

img_cv = cv2.imread('./testimg.jpg')
print(img_cv)
[[[ 21  48  92]
  [ 19  46  90]
  [ 16  42  88]
  ...
  [  0  14  13]
  [  0  11  10]
  [  0  15  14]]

 [[ 17  44  88]
...

OpenCVimread는 BGR (Blue, Green, Red) 순서의 numpy.ndarray를 리턴한다.

matplotlib.image

$ pip install matplotlib
import matplotlib.image as matimg

img_mat = matimg.imread('./testimg.jpg')
print(img_mat)
[[[ 92  48  21]
  [ 90  46  19]
  [ 88  42  16]
  ...
  [ 13  14   0]
  [ 10  11   0]
  [ 14  15   0]]

 [[ 88  44  17]
...

matplotlib.image.imread는 RGB 순서의 numpy.ndarray를 리턴한다.

Pillow

$ pip install pillow
import numpy as np
from PIL import Image

img_pil = Image.open('./testimg.jpg')
print(type(img_pil)

img_pil_arr = np.array(img_pil)
print(img_pil_arr)
<class 'PIL.JpegImagePlugin.JpegImageFile'>
[[[ 92  48  21]
  [ 90  46  19]
  [ 88  42  16]
  ...
  [ 13  14   0]
  [ 10  11   0]
  [ 14  15   0]]

 [[ 88  44  17]

PillowImage.open을 이용해 image 파일을 읽어들이는데 리턴 값이 Image 타입 객체이기 때문에 numpy.array를 이용해 numpy.ndarray로 변환시켜 주어야 한다. (순서는 RGB)

'dev > Python' 카테고리의 다른 글

[Python] OpenCV Face Detection  (0) 2023.01.01
[Python] OpenCV로 image size 조절하기  (0) 2023.01.01
[Data][Python] Pandas + Numpy example  (0) 2022.01.10
[Data][Python] Pandas example  (0) 2022.01.10
[Data] An understanding data  (0) 2022.01.10
Comments