简体   繁体   中英

Set or change the values of a new xarray dimension

I have an xarray DataArray with a blue band image (shape 600 x 600), which I'd like to transform into a pseudo RGB-image (ie an image that, when viewed in RGB mode, will be displayed as blue). My thinking is that if I add two bands (red and green) and set their values to 0, that would do the trick (I'm using rioxarray to save the array as a PNG).

dummy_image = np.random.randint(0, 255, size=(600, 600))
im_xa_band = xa.DataArray(dummy_image, dims=['y', 'x'], coords={'x': np.arange(0, 600), 'y': np.arange(0, 600)})
im_xa_3band = im_xa.expand_dims({'band': 3})
im_xa_3band = im_xa_3band.assign_coords(band=['R', 'G', 'B'])

When I do this, the two new bands get the same values as the original, blue band. However, I fail in finding a way to set the new bands to 0 (or rather, how to set their values at all, seems like such a simple task).

.sel() can't be used to assign values. When I try.loc as I would in Pandas, I get an error:

im_xa_3band.loc['R', :, :] = 0

ValueError: Assignment destination is a view. Do you want to .copy() array first?

Any advice on how to change the values is appreciated.

It seems you need to call .copy() after .expand_dims() , see a discussion here .

im_xa_3band = im_xa.expand_dims({'band': 3}).copy()
im_xa_3band = im_xa_3band.assign_coords(band=['R', 'G', 'B'])
im_xa_3band.loc['R', :, :] = 0

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