From ipython.display 이미지 display 방법

● IDE, System/JupyterNotebook

by 0ver-grow 2021. 2. 21.

From ipython.display 이미지 display 방법

1. 주피터 노트북에 패키지 설치하고

!pip install IPython

2. 주피터노트북에 이미지 삽입하도록 패키지 임포트

from IPython.display import Image

From ipython.display 이미지 display 방법

3. 이미지 불러오기 (2가지 방법있음)

A. 코드블럭

Image("파일경로/파일명.확장자명")

현재 코드를 입력하고 있는 파일의 하위폴더(폴더명:folder)에 okky.jpg라는 파일명을 불러오고 싶다.

Image("folder/okky.jpg")

B. 마크다운

![이미지파일명](파일경로/파일명.확장자명)

개발 이야기/Python, Machine Learning

2021. 3. 10.

Colab에서 PIL 명령어로 show로 이미지가 안열리는 현상을 발견했다.

이 이유에 대해 알아보고 해결법을 알아보자. 

먼저 PIL은 뭐고, Colab은 뭐냐?


PIL (Pillow)

PIL 명령어는 이미지를 열고 가공하고 저장하는데 유용한 라이브러리다. 

From ipython.display 이미지 display 방법

IPython

Colab, Jupyter notebook은 IPython 을 이용한 명령쉘이며
웹에서 대화형 코딩을 할 수 있게 해주어 우리에게 많은 편리함을 가져다 주고 있다.

From ipython.display 이미지 display 방법

이런 IPython 상에서 문제가 있으니, 아래의 명령어가 듣질 않는 것이다.

from PIL import Image

pil_img = Image.open('stock.png')
pil_img.show()

이렇게 하면 원래라면 stock.png 이미지가 출력되어야 하는데, 나오지 않는다. 반응이 없다.

이유는 아래의 설명에서 알 수 있다.


def show(title=None, command=None)

Displays this image. This method is mainly intended for debugging purposes.

The image is first saved to a temporary file. By default, it will be in PNG format.

On Unix, the image is then opened using the **display**, **eog** or **xv** utility, depending on which one can be found.

On macOS, the image is opened with the native Preview application.

On Windows, the image is opened with the standard PNG display utility.

:param title: Optional title to use for the image window, where possible.

:param command: command used to show the image


즉, show 명령은 기본 OS에 깔린 유틸리티로 이미지를 열게 해주는 기능인데,

온라인 기반 IPython에는 그런 실행이 불가능 하기 때문.

대안

그래서 대안이 무엇이냐? 

PIL에서 이미지를 여는 것 자체가 개발자의 편의를 위한 임시 확인용, 디버깅 용일 뿐이다.

그러니 다른 방법으로 이미지를 열어 In-line에서 보여주기만 하면 된다.

이렇게 해보자.

from PIL import Image
from IPython.display import Image

image1 = Image(filename='stock.png')
display(image1)
From ipython.display 이미지 display 방법

결과 이미지가 정상적으로 출력됨을 알 수 있다.

다른 방법은 Numpy와 matplotlib의 imshow를 사용하는 것이다.

아래와 같이 하면 된다.

from matplotlib.pyplot import imshow
import numpy as np
from PIL import Image 

%matplotlib inline
pil_im = Image.open('stock.png')
imshow(np.asarray(pil_im))

한가지 더

또 다른 방법은 opencv를 사용하는 것

colab에서 opencv로 이미지를 출력하는 방법은 아래 코드와 같다.

자세한 내용은 링크를 참고해보자.

[딥러닝 첫걸음] 생에 첫 컴퓨터 비전, OpenCV야 안녕? OpenCV로 이미지 열어버리기

[딥러닝 첫걸음] 생에 첫 컴퓨터 비전, OpenCV야 안녕? OpenCV로 이미지 열어버리기

opencv 두려워하지말고 시작해보자. 내 첫 OpenCV 실행을 글로 남긴다. 언젠가 컴퓨터 비전과 딥러닝 전문가가 되어 이 글을 열어보게 된다면 피식 할 것 같다. OpenCV 위키백과, 우리 모두의 백과사전

lapina.tistory.com

From ipython.display 이미지 display 방법
import cv2
from google.colab.patches import cv2_imshow
img = cv2.imread('stock.png', cv2.IMREAD_COLOR)
cv2_imshow(img)

끝!


Colab에서 이미지가 안보일 때의 확인 방법을 알아보았다.

도움이 되었길 바란다.