Python – Load RGB images in python from the ESA Sentinel-2 product and save them using openCV

Load RGB images in python from the ESA Sentinel-2 product and save them using openCV… here is a solution to the problem.

Load RGB images in python from the ESA Sentinel-2 product and save them using openCV

According to ESA snap, for RGB images, we should put band 4 into the red channel, band 3 into the green channel, and band 2 into the blue channel. How can we use python to read these bands into a numpy array so that we can do whatever image processing we want and then save the RGB image on disk?

from snappy import Product
from snappy import ProductIO
import numpy as np
import cv2

product = ProductIO.readProduct(path_to_product)

width = product.getSceneRasterWidth()
height = product.getSceneRasterHeight()

# Natural colors 
red = product.getBand('B4')
green = product.getBand('B3')
blue = product.getBand('B2')

For example, here is the type of one of the above variables (the others are the same):

type(red)
# org.esa.snap.core.datamodel.Band

How to get numpy arrays from these data and then save them to disk as jpg images?

Solution

#Read in channel's pixels    
red_pixels = np.zeros(width * height, np.float32)
red.readPixels(0, 0, width, height, red_pixels)

green_pixels = np.zeros(width * height, np.float32)
green.readPixels(0, 0, width, height, green_pixels)

blue_pixels = np.zeros(width * height, np.float32)
blue.readPixels(0, 0, width, height, blue_pixels)

#Reshape to image dimensions
red_pixels.shape =  height, width
green_pixels.shape =  height, width
blue_pixels.shape =  height, width

#Combine into a RGB image
rgb=np.zeros((height,width,3))
rgb[...,0] = red_pixels
rgb[...,1] = green_pixels
rgb[...,2] = blue_pixels

So far, we have an RGB image in a numpy array with floating-point values. To write to disk as a jpg picture, we first crop the larger values to make the image brighter, and then convert the image to an integer value of 0-255.

rgb2 = ((np.clip(rgb.copy(),0,1))*255).astype('uint8')
#Reverse Red-Blue Channels as open cv will reverse again upon writing image on disk
cv2.imwrite('image_name.jpg',rgb2[...,::-1])

Related Problems and Solutions