遙感影像分類(lèi)圖一般為特定數(shù)值對(duì)應(yīng)一類(lèi)地物,用Python繪制時(shí),主要在顏色的映射和對(duì)應(yīng)的圖例生成。
plt.matplotlib.colors.ListedColormap支持自定義顏色。matplotlib.patches mpatches對(duì)象可以生成一個(gè)矩形對(duì)象,控制其顏色和地物類(lèi)型的顏色對(duì)應(yīng)就可以生成地物分類(lèi)的圖例了。具體用法可以自行Google和百度。下面給出一個(gè)模擬地物分類(lèi)數(shù)據(jù)的可視化例子。
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
data = np.random.randint(0, 3, size=(100,100))
colors = dict((
(0, (0, 255, 0, 255)), # 前三位RGB,255代表256色
(1, (0, 0, 255, 255)),
(2, (255, 255, 0, 255)),
))
# 轉(zhuǎn)換為0-1
for k in colors:
v = colors[k]
_v = [_v / 255.0 for _v in v]
colors[k] = _v
index_colors = [colors[key] if key in colors else
(255, 255, 255, 0) for key in range(0, len(colors))]
cmap = plt.matplotlib.colors.ListedColormap(index_colors, 'Classification', len(index_colors)) # n等于顏色表長(zhǎng)度,否則被截?cái)嗷虮恢貜?fù)
# cmap = plt.matplotlib.colors.ListedColormap(['gray', 'orange', 'k'], 'Classification')
plt.rcParams['font.family'] = 'Arial'
plt.rcParams['font.size'] = 10
plt.rcParams['font.weight'] = 'bold'
fig, ax = plt.subplots(figsize=(4,3.5), dpi=300)
ax.imshow(data, cmap=cmap, interpolation='none')
# 繪制矩形的補(bǔ)丁, 用來(lái)生成圖例,fig.add_artist()才會(huì)在圖中顯示出來(lái)
import matplotlib.patches as mpatches
rectangles = [mpatches.Rectangle((0, 0,), 1, 1, facecolor=index_colors[i])
for i in range(len(index_colors))]
labels = ['forest',
'water',
'urban']
ax.legend(rectangles, labels,
bbox_to_anchor=(1.4, 0.25), fancybox=True, frameon=False,)
# 取消刻度和標(biāo)簽顯示
ax.tick_params(which='major', bottom=0, left=0)
ax.set_xticklabels('')
ax.set_yticklabels('')