首页 > 解决方案 > 使用 Python 将单波段 Tif 图像转换为伪彩色单波段图像

问题描述

我已经阅读了很多关于这个主题的帖子,但我找不到解决我的问题的方法。我有一个光栅图像,我在其中提取了具有一个波段的值的数组并将其标准化以满足范围(0,255)。但是,当我使用 PIL 包时,无法将灰度图像转换为具有“RGB”或“P”模式的图像,我可以在其中应用调色板。这是我的python代码:

from PIL import Image
import numpy as np
import rasterio

file_path = "./dem.tif"
with rasterio.open(file_path) as src:
    img = src.read(1) # read the one band
    img_cleaned = np.where(img<1e-20,img*0,img) # pixels where no value is available were given a very small value which I remove here
    img_normalized = (img_cleaned - np.min(img_cleaned)) / (np.max(img_cleaned) - np.min(img_cleaned)) * 255.0 # normalize
    img_grey = Image.fromarray(img_normalized)
    img_color = img_grey.convert("P") # it is the same with img_color = img_grey.convert("RGB")
    
    img_color.show()

这是数组值的直方图,证明这些值在正确的范围内: 数组值的直方图

这是图像,即使我转换了它:

在此处输入图像描述

标签: pythonpython-imaging-librarygeospatialrasterio

解决方案


推荐阅读