简体   繁体   中英

Using Rasterio to save window image (as jpg)

I'm trying to open an jpg (01.jpg) using Python Rasterio and save the Window as a jpg I can do it for 1 band, not not for the 3 bands of the RGB source image. the issue is with the band rearranging. below my code and the error:

Source shape (2000, 2000, 3) is inconsistent with given indexes 1

I tried to modify line code src = np.moveaxis(src, [0, 1, 2], [2, 1, 0]) but I still have errors.. can you please offer advice?

import cv2
import numpy as np
import rasterio
from rasterio.plot import show

w =2000
h = 2000
tile = np.ones((w,h))
cv2.imwrite('tile.jpg', tile)

with rasterio.open('01.JPG') as src:
  src = src.read(window=Window(0, 0, w, h))
  show(src)

with rasterio.open('tile.jpg', 'w', driver='GTiff',width=w, height=h, count=1,dtype=src.dtype) as tile:
  src = np.moveaxis(src, [0, 1, 2], [2, 1, 0])
  tile.write(src)

You are trying to save a 3-band image (which you read from 01.JPG ) into a 1-band image (which you opened with count=1 ). np.moveaxis just shifts the axes positions, but you still have three axes (as the error message is telling you the shape is (2000, 2000, 3) ).

If you want to save all three bands, but with changed order (possibly to create a false-color/pseudocolor image ), you'd need to change count=1 to count=3 .

If you need to write just one band

There are two ways to do that: you can read just one band when you read the 01.JPG raster, by passing the band index as the first argument to the read() function , or keep reading all three bands and indexing the band you want when you save, so you get an array with shape (2000, 2000) (probably src[i] if you want to read band i ).

Note this index will start at zero, following numpy convention, instead of 1 when reading from rasterio (which follows the GDAL convention of starting the band numbers at 1 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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