【问题标题】:How to assign particular color to each pixel in image如何为图像中的每个像素分配特定的颜色
【发布时间】:2021-05-12 15:13:39
【问题描述】:

我有一个具有 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)。 我遇到了颜色图选项,但无法按需要显示。

【问题讨论】:

标签: python image matplotlib tiff rasterio


【解决方案1】:

我最近解决了这个问题,所以这对我有用。将栅格导入为 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)

接下来你要创建你的情节:

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')

【讨论】:

    猜你喜欢
    • 2019-09-17
    • 1970-01-01
    • 1970-01-01
    • 2019-03-18
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    • 2011-09-19
    • 2013-10-04
    相关资源
    最近更新 更多