[英]How to assign particular color to each pixel in image
我有一個具有 5 個值的單波段光柵 tif 圖像,即 4,3,2,1,0。
此代碼顯示分配給每個像素值的隨機顏色的圖像
import rasterio
from rasterio.plot import show
import matplotlib.pyplot as plt
img_data = rasterio.open(img)
fig, ax = plt.subplots(figsize=(10,10))
show(img_data)
我如何通過為每個圖像分配特定顏色來顯示此圖像(例如紅色:4,藍色:3,綠色:2,黑色:1,白色:0)。 我遇到了顏色映射選項,但無法按需要顯示它。
我最近解決了這個問題,所以這對我有用。 將柵格導入為 numpy 數組
import rasterio as rio
with rio.open(path_img) as img:
img_data = img.read()
首先你需要創建一個顏色圖:
from matplotlib import colors
#since your values are from 0 to 4, you want the color bins to be at 0.5 increments
levels = [-0.5,0.5,1.5,2.5,3.5,4.5]
clrs = ['white','black','green','blue','red']
cmap, norm = colors.from_levels_and_colors(levels, clrs)
接下來你要創建你的 plot:
fig, ax = plt.subplots(figsize=(15,15))
raster_plot = show(img_data,ax=ax,cmap=cmap,norm=norm)
現在創建顏色條:
#get the image values
im = raster_plot.get_images()[0]
#create a colorbar
cbar = fig.colorbar(im, ax=ax)
cbar.ax.get_yaxis().set_ticks([])
#add text to the middle of the colorbar values
for j, lab in enumerate(['0','1','2','3','4']):
cbar.ax.text(2, j, lab, ha='center', va='center')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.