Matplotlib 이미지 투명도

Beginner

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

소개

이 랩에서는 Matplotlib 을 사용하여 2D 이미지에서 투명도와 색상을 혼합하는 방법을 보여줍니다. 목표는 imshow를 사용하여 데이터의 특정 부분을 강조하는 것입니다.

VM 팁

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

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

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

데이터 생성

2D 그리드에서 두 개의 2D 블롭 (blob) 을 생성하는 것으로 시작합니다. 하나의 블롭은 양수이고 다른 하나는 음수입니다.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import Normalize

def normal_pdf(x, mean, var):
    return np.exp(-(x - mean)**2 / (2*var))

## 블롭이 존재할 공간을 생성합니다.
xmin, xmax, ymin, ymax = (0, 100, 0, 100)
n_bins = 100
xx = np.linspace(xmin, xmax, n_bins)
yy = np.linspace(ymin, ymax, n_bins)

## 블롭을 생성합니다. 값의 범위는 대략 -.0002 에서 .0002 입니다.
means_high = [20, 50]
means_low = [50, 60]
var = [150, 200]

gauss_x_high = normal_pdf(xx, means_high[0], var[0])
gauss_y_high = normal_pdf(yy, means_high[1], var[0])

gauss_x_low = normal_pdf(xx, means_low[0], var[1])
gauss_y_low = normal_pdf(yy, means_low[1], var[1])

weights = (np.outer(gauss_y_high, gauss_x_high)
           - np.outer(gauss_y_low, gauss_x_low))

## 픽셀이 페이드될 회색 배경도 생성합니다.
greys = np.full((*weights.shape, 3), 70, dtype=np.uint8)

블롭 플롯

다음으로, 투명도 없이 imshow를 사용하여 이러한 블롭을 플롯합니다.

vmax = np.abs(weights).max()
imshow_kwargs = {
    'vmax': vmax,
    'vmin': -vmax,
    'cmap': 'RdYlBu',
    'extent': (xmin, xmax, ymin, ymax),
}

fig, ax = plt.subplots()
ax.imshow(greys)
ax.imshow(weights, **imshow_kwargs)
ax.set_axis_off()
plt.show()

투명도 혼합

imshow로 데이터를 플롯할 때 투명도를 포함하는 가장 간단한 방법은 데이터의 모양과 일치하는 배열을 alpha 인수에 전달하는 것입니다.

## 오른쪽으로 이동하면서 선형적으로 증가하는 값의 알파 채널을 생성합니다.
alphas = np.ones(weights.shape)
alphas[:, 30:] = np.linspace(1, 0, 70)

## 그림과 이미지를 생성합니다.
fig, ax = plt.subplots()
ax.imshow(greys)
ax.imshow(weights, alpha=alphas, **imshow_kwargs)
ax.set_axis_off()
plt.show()

투명도를 사용하여 값 강조

마지막으로, 동일한 플롯을 다시 만들지만 이번에는 투명도를 사용하여 데이터의 극단적인 값을 강조합니다. 이는 종종 p-값이 작은 데이터 포인트를 강조하는 데 사용됩니다. 또한 이미지 값을 강조하기 위해 등고선도 추가합니다.

## 가중치 값을 기반으로 알파 채널을 생성합니다.
alphas = Normalize(0, .3, clip=True)(np.abs(weights))
alphas = np.clip(alphas, .4, 1)  ## alpha value clipped at the bottom at .4

## 그림과 이미지를 생성합니다.
fig, ax = plt.subplots()
ax.imshow(greys)
ax.imshow(weights, alpha=alphas, **imshow_kwargs)

## 다른 레벨을 추가로 강조하기 위해 등고선을 추가합니다.
ax.contour(weights[::-1], levels=[-.1, .1], colors='k', linestyles='-')
ax.set_axis_off()
plt.show()

ax.contour(weights[::-1], levels=[-.0001, .0001], colors='k', linestyles='-')
ax.set_axis_off()
plt.show()

요약

이 랩에서는 Matplotlib 를 사용하여 2D 이미지에서 투명도를 색상과 혼합하는 방법을 배웠습니다. 또한 imshow를 사용하여 데이터의 특정 부분을 강조하는 방법도 배웠습니다.