Spaces:
Sleeping
Sleeping
import numpy as np | |
import rasterio | |
from rasterio.plot import show | |
import cv2 | |
def read_pansharpened_rgb(file_path): | |
with rasterio.open(file_path) as src: | |
# Read all bands | |
image = src.read() | |
# Check the number of bands | |
num_bands = image.shape[0] | |
if num_bands >= 3: | |
# If we have 3 or more bands, use the first three as RGB | |
rgb_image = image[:3] | |
else: | |
raise ValueError(f"The image has only {num_bands} bands. At least 3 bands are required for RGB.") | |
# Transpose the image to have the bands as the last dimension | |
rgb_image = np.transpose(rgb_image, (1, 2, 0)) | |
# Normalize each band separately | |
r = normalize_band(rgb_image[:,:,0]) | |
g = normalize_band(rgb_image[:,:,1]) | |
b = normalize_band(rgb_image[:,:,2]) | |
# Combine the normalized bands | |
rgb_normalized = np.dstack((r, g, b)) | |
return rgb_normalized | |
def normalize_band(band): | |
"""Normalize a single band to 0-255 range.""" | |
min_val = np.min(band) | |
max_val = np.max(band) | |
if max_val > min_val: | |
normalized = ((band - min_val) / (max_val - min_val) * 255).astype(np.uint8) | |
else: | |
normalized = np.zeros_like(band, dtype=np.uint8) | |
return normalized | |
# Example usage | |
# Display the image using matplotlib | |