Create a new raster with new band

Hello!
From S2 image I extracted bands to numpy arrays and created new array.
I would like to save those bands into a new product.
When I create 1 product per band, no problem. However is it possible to create a product and add 2 bands, or more to it?
I try with a for loop but I have this message : RuntimeError: java.lang.NullPointerException

Here my function :

def CreatBand2(p,band,name,path,w,h):

SandMask = Product('Sand_Mask','SandMask',w,h)
snappy.ProductUtils.copyGeoCoding(p,SandMask)
snappy.ProductUtils.copyMetadata(p, SandMask)

for i in range(len(band)):
    new_band = SandMask.addBand(name[i],ProductData.TYPE_FLOAT32)
    writer = ProductIO.getProductWriter('BEAM-DIMAP')
    SandMask.setProductWriter(writer)
    SandMask.writeHeader(path + '\\' + name[i] + '_band.dim')
    new_band.writePixels(0,0,w,h,band[i])

ProductIO.writeProduct (SandMask,path,'BEAM-DIMAP')

If anyone got an idea
Thank you :blush:

Found a solution!

1 Like

Would you mind to share your solution with the community?

1 Like

Here the function to create a product and ad new band from np.array:

def Create_SandMask(p,band,name,path,w,h):

SandMask = Product('Sand_Mask','SandMask',w,h)
snappy.ProductUtils.copyGeoCoding(p,SandMask)
snappy.ProductUtils.copyMetadata(p, SandMask)        

for i in range(len(band)):
    new_band = SandMask.addBand(name[i],ProductData.TYPE_FLOAT32)


    writer = ProductIO.getProductWriter('BEAM-DIMAP')
    SandMask.setProductWriter(writer)
    SandMask.writeHeader(path + '\\' + 'SandMask.dim')
    
    new_band.writePixels(0,0,w,h,band[i])

the problem was the writeProduct at the end

One further improvement could be to seperate the product creation (adding bands) from the writing of the data.

SandMask = Product('Sand_Mask','SandMask',w,h)
snappy.ProductUtils.copyGeoCoding(p,SandMask)
snappy.ProductUtils.copyMetadata(p, SandMask)        
for i in range(len(name)):
    new_band = SandMask.addBand(name[i],ProductData.TYPE_FLOAT32)

writer = ProductIO.getProductWriter('BEAM-DIMAP')
SandMask.setProductWriter(writer)
SandMask.writeHeader(path + '\\' + 'SandMask.dim')
    
for i in range(len(name)):
    new_band = SandMask.getBand(name[i])
    new_band.writePixels(0,0,w,h,band[i])

SandMask.closeIO()

In your code the header would have been written several times and each time a new writer was created.
Probably you know it already. You can find examples in the example directory of your snappy installation. They are also on GitHub

Oh thanks, I’ll try