PIL과 opencv에서의 image 변환.

2021. 11. 22. 23:54·Programming/DIP
728x90
728x90

PIL과 opencv에서의 image 변환.

필요성

tensorflow 나, pytorch등에서 에서의 image를 이용한 이미지 로딩의 경우,
PIL.Image.Image를 기본적으로 이미지를 위한 class 타입으로 사용함.

from tensorflow.keras.preprocessing import image
image_tf = image.load_img('test.gif')
print(f'type : {type(image_tf)}')

 

결과는 다음과 같음

type : <class 'PIL.Image.Image'>

 

opencv or scikit-image를 이용한 전처리 수행하고 싶은 경우에는 이 두 라이브러리의 데이터 간 변환이 필요함.

간단한 전처리가 아닌 computer vision 분야의 알고리즘을 이용하려고 할 경우, opencv 또는 scikit-image 가 많이 사용되기 때문임.
둘 패키지 모두 NumPy의 ndarray를 사용하여 이미지를 다룸: channel 순서만 차이가 있음 (BGR or RGB) 


방법

방법 자체는 매우 간단한데,
opencv의 python라이브러리는 실제로 numpy의 ndarray를 기본 이미지 class로 사용하기 때문에
PIL.Image.Image와 numpy의 array간의 변환을 이용하면 된다.

  • 단, color image를 처리할 때 opencv의 경우 BGR Color-space를 기본으로 사용한다는 점을 주의할 것.

변환은 다음 코드를 참조하자.

import numpy as np
from PIL import Image
import cv2

def PIL2opencv(pilimage):
  return cv2.cvtColor(np.array(pilimage),cv2.COLOR_RGB2BGR)

def opencv2PIL(cv2image):
  return Image.fromarray(cv2image)

 

이들을 테스트하기 위해, 특정 url에서 image를 로드하여 opencv의 이미지 타입인 numpy.ndarray로 읽고 이들간의 변환을 해보면 다음과 같다.

import urllib
import cv2
import numpy as np
import urllib.request
from PIL import Image

url_str = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTmYnfxeVfCSqG514OtmU_Lw4VKmqDuf-UU9A&usqp=CAU'

# url에서 byte단위로 읽어들인 경우, opencv에서 사용가능한 image 로딩하는 방법.
resp = urllib.request.urlopen(url_str)
img1D = np.asarray(bytearray(resp.read()), dtype=np.uint8)
print(f'type : {type(img1D)}, shape:{img1D.shape}')
cv2img = cv2.imdecode(img1D,cv2.IMREAD_COLOR)
print(f'type : {type(cv2img)}, shape:{cv2img.shape}')

pilimage = opencv2PIL(cv2img)
print(f'type : {type(pilimage)}')
cv2img_new = PIL2opencv(pilimage)
print(f'type : {type(cv2img_new)}')

pilimage.save('test.gif')

 

결과는 다음과 같다.

type : <class 'numpy.ndarray'>, shape:(9527,)
type : <class 'numpy.ndarray'>, shape:(254, 199, 3)
type : <class 'PIL.Image.Image'>
type : <class 'numpy.ndarray'>

 

이를 matplotlib.pyplot을 이용하여 살펴보면 다음과 같음.

import matplotlib.pyplot as plt

matimg = plt.imread('test.gif')
plt.subplot(1,3,1)
plt.imshow(matimg)
plt.axis('off')
plt.subplot(1,3,2)
plt.imshow(np.array(pilimage))
plt.axis('off')
plt.subplot(1,3,3)
plt.imshow(cv2img_new[:,:,::-1])
plt.axis('off')
plt.show()

tensorflow.keras.preprocessing.image

내부적으로 PIL을 이용하여 이미지를 로딩한다.

from tensorflow.keras.preprocessing import image
image_tf = image.load_img('test.gif')
print(f'type : {type(image_tf)}')

결과는 다음과 같음.

type : <class 'PIL.Image.Image'>

Tensorflow 라이브러리를 이용한 URL통한 이미지 로드.

tensorflow.keras.utils.get_file을 이용한다.

import tensorflow as tf
import os
import matplotlib.pyplot as plt

url_str = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTmYnfxeVfCSqG514OtmU_Lw4VKmqDuf-UU9A&usqp=CAU'

bname = os.path.basename(url_str)
bname = bname.split('?')[0]
img_url = tf.keras.utils.get_file(bname, origin=url_str)
pilimg = tf.keras.preprocessing.image.load_img(img_url, target_size=(224,224))
print(img_url) #/root/.keras/datasets/img
os.remove(img_url) # Remove the cached file

#plt.imshow(np.array(pilimg))
#plt.axis('off')
#plt.show()

 

결과는 다음과 같음.

Downloading data from https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTmYnfxeVfCSqG514OtmU_Lw4VKmqDuf-UU9A&usqp=CAU
16384/9527 [===================================================] - 0s 0us/step
24576/9527 [=============================================================================] - 0s 0us/step
/root/.keras/datasets/images

같이 보면 좋은 자료들

https://ds31x.tistory.com/315

 

[Python] PIL, Pillow, OpenCV, and Scikit-image

Python에서 이미지를 다룰 때 이용되는 주요 패키지들은 다음과 같음.1.PIL (Python Imaging Library)PIL은 1995년에 처음 개발된 Python의 최초 이미지 처리 라이브러리 중 하나임. 매우 직관적이고 사용하기

ds31x.tistory.com

 

https://ds31x.tistory.com/305

 

[DL] Dataset: CIFAR-10

CIFAR-10Machine Learning 과 Computer Vision 의 학습에서 널리 사용되는 image dataset.캐나다 토론토 대학교의 Alex Krizhevsky, Vinod Nair, Geoffrey Hinton에 의해 만들어짐.구성 및 classes1.Data 구성:이미지 크기: 32x32 Pix

ds31x.tistory.com

 

 


'Programming > DIP' 카테고리의 다른 글

[OpenCV] cv2.cvtColor  (0) 2022.07.14
[Math] Hessian: Summary  (0) 2022.06.05
Conda backup for DIP 2021  (0) 2021.09.18
NumPy : sum, mean, std, and so on  (0) 2021.09.17
NumPy 검색  (0) 2021.09.11
'Programming/DIP' 카테고리의 다른 글
  • [OpenCV] cv2.cvtColor
  • [Math] Hessian: Summary
  • Conda backup for DIP 2021
  • NumPy : sum, mean, std, and so on
dsaint31x
dsaint31x
    반응형
    250x250
  • dsaint31x
    Dsaint31's blog
    dsaint31x
  • 전체
    오늘
    어제
    • 분류 전체보기 (740)
      • Private Life (13)
      • Programming (56)
        • DIP (104)
        • ML (26)
      • Computer (119)
        • CE (53)
        • ETC (33)
        • CUDA (3)
        • Blog, Markdown, Latex (4)
        • Linux (9)
      • ... (351)
        • Signals and Systems (103)
        • Math (172)
        • Linear Algebra (33)
        • Physics (42)
        • 인성세미나 (1)
      • 정리필요. (54)
        • 의료기기의 이해 (6)
        • PET, MRI and so on. (1)
        • PET Study 2009 (1)
        • 방사선 장해방호 (4)
        • 방사선 생물학 (3)
        • 방사선 계측 (9)
        • 기타 방사능관련 (3)
        • 고시 (9)
        • 정리 (18)
      • RI (0)
      • 원자력,방사능 관련법 (2)
  • 블로그 메뉴

    • Math
    • Programming
    • SS
    • DIP
  • 링크

    • Convex Optimization For All
  • 공지사항

    • Test
    • PET Study 2009
    • 기타 방사능관련.
  • 인기 글

  • 태그

    Vector
    Python
    math
    signal_and_system
    Optimization
    검사
    인허가제도
    fourier transform
    random
    Convolution
    Probability
    Term
    function
    linear algebra
    numpy
    signals_and_systems
    SIGNAL
    Programming
    SS
    opencv
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
dsaint31x
PIL과 opencv에서의 image 변환.
상단으로

티스토리툴바