Spaces:
Sleeping
Sleeping
Update Utils/convert.py
Browse files- Utils/convert.py +44 -4
Utils/convert.py
CHANGED
|
@@ -1,4 +1,44 @@
|
|
| 1 |
-
import
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import rasterio
|
| 3 |
+
from rasterio.plot import show
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
import cv2
|
| 6 |
+
|
| 7 |
+
def convert_gtiff_to_8bit(file_path):
|
| 8 |
+
with rasterio.open(file_path) as src:
|
| 9 |
+
# Read all bands
|
| 10 |
+
image = src.read()
|
| 11 |
+
|
| 12 |
+
# Check the number of bands
|
| 13 |
+
num_bands = image.shape[0]
|
| 14 |
+
|
| 15 |
+
if num_bands >= 3:
|
| 16 |
+
# If we have 3 or more bands, use the first three as RGB
|
| 17 |
+
rgb_image = image[:3]
|
| 18 |
+
else:
|
| 19 |
+
raise ValueError(f"The image has only {num_bands} bands. At least 3 bands are required for RGB.")
|
| 20 |
+
|
| 21 |
+
# Transpose the image to have the bands as the last dimension
|
| 22 |
+
rgb_image = np.transpose(rgb_image, (1, 2, 0))
|
| 23 |
+
|
| 24 |
+
# Normalize each band separately
|
| 25 |
+
r = normalize_band(rgb_image[:,:,0])
|
| 26 |
+
g = normalize_band(rgb_image[:,:,1])
|
| 27 |
+
b = normalize_band(rgb_image[:,:,2])
|
| 28 |
+
|
| 29 |
+
# Combine the normalized bands
|
| 30 |
+
rgb_normalized = np.dstack((r, g, b))
|
| 31 |
+
|
| 32 |
+
return rgb_normalized
|
| 33 |
+
|
| 34 |
+
def normalize_band(band):
|
| 35 |
+
"""Normalize a single band to 0-255 range."""
|
| 36 |
+
min_val = np.min(band)
|
| 37 |
+
max_val = np.max(band)
|
| 38 |
+
if max_val > min_val:
|
| 39 |
+
normalized = ((band - min_val) / (max_val - min_val) * 255).astype(np.uint8)
|
| 40 |
+
else:
|
| 41 |
+
normalized = np.zeros_like(band, dtype=np.uint8)
|
| 42 |
+
return normalized
|
| 43 |
+
|
| 44 |
+
|