简体   繁体   English

如何为图像中的每个像素分配特定颜色

[英]How to assign particular color to each pixel in image

I have a single band raster tif image with 5 values ie 4,3, 2, 1, 0.我有一个具有 5 个值的单波段光栅 tif 图像,即 4,3,2,1,0。

This code displays image with random color assigned to each pixel value此代码显示分配给每个像素值的随机颜色的图像

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)

How can I display this image by assigning particular color to each image (Eg red: 4,blue:3, green:2, black:1, white: 0).我如何通过为每个图像分配特定颜色来显示此图像(例如红色:4,蓝色:3,绿色:2,黑色:1,白色:0)。 I came across colormap option but I am not able to display it as desired.我遇到了颜色映射选项,但无法按需要显示它。

I recently solved this, so here is what worked for me.我最近解决了这个问题,所以这对我有用。 Import your raster as a numpy array将栅格导入为 numpy 数组

import rasterio as rio
with rio.open(path_img) as img:
    img_data = img.read()

First you need to create a colormap:首先你需要创建一个颜色图:

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)

Next you want to create your plot:接下来你要创建你的 plot:

fig, ax = plt.subplots(figsize=(15,15))
raster_plot = show(img_data,ax=ax,cmap=cmap,norm=norm)

Now you create the colorbar:现在创建颜色条:

#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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM