简体   繁体   English

如何从堆叠的 RGB 中以光栅形式写入 PNG?

[英]How to write PNG in rasterio from a stacked RGB?

I have 3 variables namely R, G, B. I want to make a PNG image based on the three using rasterio.我有 3 个变量,即 R、G、B。我想使用 rasterio 基于这三个变量制作 PNG 图像。 I tried using np.dstack to stack the 3 images and use the result to write it.我尝试使用 np.dstack 来堆叠 3 个图像并使用结果来编写它。

Using rasterio, I tried to write it this way:使用 rasterio,我尝试这样写:

rgb = np.dstack((Nr,Ng,Nb))  
finame = "Image_RGB.png"
with rasterio.Env():
    with rasterio.open(finame, 'w',
        driver='PNG',
        height=rgb.shape[0],
        width=rgb.shape[1],
        count=1,
        dtype=rgb.dtype,
        nodata=0,
        compress='deflate') as dst:
        dst.write(rgb, 1)

But I get this error:但我得到这个错误:

ValueError: Source shape (1, 830, 793, 3) is inconsistent 
with given indexes 1

Two things are going wrong here:这里有两个问题:

  1. Rasterio is channels first, while you have channels last. Rasterio 是频道在前,而您的频道在后。 In other words, the shape of the rgb should be (3, 830, 793) not (830, 793, 3).换句话说, rgb的形状应该是 (3, 830, 793) 而不是 (830, 793, 3)。
  2. You set count=1 and do dst.write(rgb, 1) .您设置count=1并执行dst.write(rgb, 1) This makes it try to write the rgb as the first band of the output file.这使它尝试将 rgb 写入输出文件的第一个波段。 Instead you want count=3 and dst.write(rgb) .相反,您需要count=3dst.write(rgb)

This is a bit late for you, but maybe others will still be helped by my answer.这对你来说有点晚了,但也许其他人仍然会从我的回答中得到帮助。

根据亚瑟的回答和原始代码,这是这个问题的一个解决方案,最后一行应该是:

        dst.write(np.rollaxis(rgb, 2,0))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从4波段图像中提取RGB(光栅) - Extracting RGB from a 4-band image (rasterio) 如何添加RGB png图片? - How to add RGB png picture? Geopandas + rasterio:将矢量隔离为png - Geopandas + rasterio : isolate a vector as png 使用光栅读取 PNG 文件时如何使用地理元数据指定输入文件 - How to specify input files with the geographical metadata when reading PNG files with rasterio 如何在 python 中检测 png 中某些像素的 rgb 值? - How do you detect the rgb value of some pixels from a png, in python? 如何从光栅 python 中的巨大 .tif 文件中获取掩码? - How to get mask from a huge .tif file in rasterio python? 如何使用Rasterio从多数据集MODIS图像中打开特定的数据集(波段)? Rasterio IndexError:波段索引超出范围 - How can I open a specific dataset (band) from a multi dataset MODIS image using Rasterio? Rasterio IndexError: band index out of range Python:如何从numpy数组中编写单通道png文件? - Python: How to write a single channel png file from numpy array? 如何从客户端烧瓶将png文件写入目标目录 - How to write png file to target directory from client side by flask python将.tif转换为.png而不将模式从cmyk更改为rgb - python converting .tif to .png without changing mode from cmyk to rgb
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM