Matplotlib 이미지 시각화 기술

Beginner

This tutorial is from open-source community. Access the source code

소개

Matplotlib 는 Python 프로그래밍 언어와 수치 수학 확장 NumPy 를 위한 플로팅 라이브러리입니다. Tkinter, wxPython, Qt 또는 GTK 와 같은 범용 GUI 툴킷을 사용하여 응용 프로그램에 플롯을 임베딩하기 위한 객체 지향 API 를 제공합니다. 이 랩에서는 Matplotlib 을 사용하여 다양한 유형의 이미지를 플로팅하는 방법을 배웁니다.

VM 팁

VM 시작이 완료되면 왼쪽 상단을 클릭하여 Notebook 탭으로 전환하여 실습을 위해 Jupyter Notebook에 액세스하십시오.

때로는 Jupyter Notebook 이 로딩을 완료하는 데 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한 사항으로 인해 작업의 유효성 검사는 자동화할 수 없습니다.

학습 중에 문제가 발생하면 언제든지 Labby 에게 문의하십시오. 세션 후 피드백을 제공해주시면 문제를 즉시 해결해 드리겠습니다.

필요한 라이브러리 가져오기

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cbook as cbook
import matplotlib.cm as cm
from matplotlib.patches import PathPatch
from matplotlib.path import Path

이변량 정규 분포 플롯

## 간단한 이변량 정규 분포 생성
delta = 0.025
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2

## 분포 플롯
fig, ax = plt.subplots()
im = ax.imshow(Z, interpolation='bilinear', cmap=cm.RdYlGn,
               origin='lower', extent=[-3, 3, -3, 3],
               vmax=abs(Z).max(), vmin=-abs(Z).max())
plt.show()

이미지 그림 플롯

## 샘플 이미지 로드
with cbook.get_sample_data('grace_hopper.jpg') as image_file:
    image = plt.imread(image_file)

## 256x256 16 비트 정수를 사용하여 다른 이미지 로드.
w, h = 256, 256
with cbook.get_sample_data('s1045.ima.gz') as datafile:
    s = datafile.read()
A = np.frombuffer(s, np.uint16).astype(float).reshape((w, h))
extent = (0, 25, 0, 25)

## 두 이미지 플롯
fig, ax = plt.subplot_mosaic([
    ['hopper', 'mri']
], figsize=(7, 3.5))

ax['hopper'].imshow(image)
ax['hopper'].axis('off')  ## x 축 및 y 축 지우기

im = ax['mri'].imshow(A, cmap=plt.cm.hot, origin='upper', extent=extent)

markers = [(15.9, 14.5), (16.8, 15)]
x, y = zip(*markers)
ax['mri'].plot(x, y, 'o')

ax['mri'].set_title('MRI')

plt.show()

이미지 보간 (Interpolate)

## 세 가지 다른 보간 방법을 사용하여 동일한 배열을 보간합니다.
A = np.random.rand(5, 5)

fig, axs = plt.subplots(1, 3, figsize=(10, 3))
for ax, interp in zip(axs, ['nearest', 'bilinear', 'bicubic']):
    ax.imshow(A, interpolation=interp)
    ax.set_title(interp.capitalize())
    ax.grid(True)

plt.show()

이미지 원점 (Origin) 제어

## 배열 원점 x[0, 0] 을 왼쪽 위 또는 오른쪽 아래로 플롯할지 지정합니다.
x = np.arange(120).reshape((10, 12))

interp = 'bilinear'
fig, axs = plt.subplots(nrows=2, sharex=True, figsize=(3, 5))
axs[0].set_title('파란색이 위로')
axs[0].imshow(x, origin='upper', interpolation=interp)

axs[1].set_title('파란색이 아래로')
axs[1].imshow(x, origin='lower', interpolation=interp)
plt.show()

클립 경로 (Clip Path) 를 사용하여 이미지 표시

## 클립 경로를 사용하여 이미지를 표시합니다.
delta = 0.025
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2

path = Path([[0, 1], [1, 0], [0, -1], [-1, 0], [0, 1]])
patch = PathPatch(path, facecolor='none')

fig, ax = plt.subplots()
ax.add_patch(patch)

im = ax.imshow(Z, interpolation='bilinear', cmap=cm.gray,
               origin='lower', extent=[-3, 3, -3, 3],
               clip_path=patch, clip_on=True)
im.set_clip_path(patch)

plt.show()

요약

이 랩에서는 Matplotlib 을 사용하여 다양한 유형의 이미지를 플롯하는 방법을 배웠습니다. 이변량 정규 분포, 사진 이미지, 보간된 이미지, 그리고 클립 경로를 사용한 이미지를 플롯했습니다. 또한 이미지 원점 (origin) 을 제어하는 방법도 배웠습니다.