File size: 13,342 Bytes
70d35ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
import base64
import numpy as np
from PIL import Image
import webcolors
import pdb
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgb
import seaborn as sns
import io

def create_color_palette_with_names(palette_name='tab10', n_colors=10):
    """
    Generate a color palette with human-readable color names.

    Parameters:
        palette_name (str): The name of the matplotlib or seaborn palette (e.g., 'tab10', 'Set3', 'husl').
        n_colors (int): The number of colors to generate.

    Returns:
        list of tuples: A list of (color_name, RGB tuple) pairs.
    """
    # Load the color palette
    try:
        palette = sns.color_palette(palette_name, n_colors)
    except ValueError:
        raise ValueError(f"Invalid palette name '{palette_name}'. Try using palettes like 'tab10', 'Set3', or 'husl'.")

    # Convert palette to RGB tuples and approximate color names
    color_palette = []
    for rgb in palette:
        nrgb = tuple((int(c * 255) for c in rgb))
        color_name = f"RGB{nrgb}"  # Fallback to RGB values as color names
        color_palette.append((color_name, tuple(nrgb)))
    
    return color_palette

def color_seg(seg_map, palette):
    """
    Convert a segmentation map to a color image using the given palette.
    seg_map: (H, W) with integer class IDs
    palette: list of [R, G, B] colors for each class
    """
    h, w = seg_map.shape
    color_img = np.zeros((h, w, 3), dtype=np.uint8)
    for class_id, color in palette.colors.items():
        color_img[seg_map == class_id] = color
    return color_img


def closest_colour(requested_colour):
    min_colours = {}
    for name in webcolors.names("css3"):
        r_c, g_c, b_c = webcolors.name_to_rgb(name)
        rd = (r_c - requested_colour[0]) ** 2
        gd = (g_c - requested_colour[1]) ** 2
        bd = (b_c - requested_colour[2]) ** 2
        min_colours[(rd + gd + bd)] = name
    return min_colours[min(min_colours.keys())]


def get_significant_classes(segmentation_map, threshold=0.001):
    """
    Identify significant classes in a segmentation map that occupy more than a given percentage
    of the total area.

    Parameters:
        segmentation_map (np.ndarray): A 2D numpy array of shape (image_width, image_height) where
                                        each pixel is an integer indicating a semantic class.
        threshold (float): The minimum proportion of the total area a label must occupy to be retained.
                           Default is 0.03 (3%).

    Returns:
        list: A list of class IDs that occupy more than the threshold proportion of the total area.
    """
    # Calculate the total number of pixels
    total_pixels = segmentation_map.size

    # Get unique labels and their pixel counts
    unique_labels, label_counts = np.unique(segmentation_map, return_counts=True)

    #[5,11], [15,855]

    # Calculate the proportion of each label
    label_proportions = label_counts / total_pixels
    # [0.001, 0.8]

    # Find labels that exceed the threshold
    retained_labels = unique_labels[label_proportions > threshold]
    retained_percents = label_proportions[label_proportions > threshold]
    class_percents = {id:percent for id, percent in zip(retained_labels, retained_percents)}

    return retained_labels.tolist(), class_percents


def get_tableau_colors():
    """
    Extract Tableau colors with their pure names and RGB tuples.

    Returns:
        dict: A dictionary mapping color names to their RGB tuples.
    """
    # Import Tableau colors from Matplotlib
    TABLEAU_COLORS = {
        'red': '#FF0000',
        'blue': '#0000FF', 
        'green': '#00FF00',
        'yellow': '#FFFF00',
        'purple': '#800080',
        'orange': '#FFA500',
        'pink': '#FFC0CB',
        'brown': '#A52A2A',
        'gray': '#808080',
        'cyan': '#00FFFF',
        'magenta': '#FF00FF',
        'lime': '#32CD32',
        'navy': '#000080',
        'olive': '#808000',
        'maroon': '#800000',
        'teal': '#008080',
        'lavender': '#E6E6FA',
        'turquoise': '#40E0D0',
        'indigo': '#4B0082',
        'coral': '#FF7F50'
    }

    # Convert hex to RGB to BGR
    tableau_colors = {name: tuple(int(c * 255) for c in to_rgb(color))
                      for name, color in TABLEAU_COLORS.items()}
    
    return tableau_colors

def generate_color_coded_segmentation_map(segmentation_map, class_colors, label_remap=None):
    """
    Generate a color-coded segmentation map given a segmentation map and class colors.

    Parameters:
        segmentation_map (np.ndarray): A 2D numpy array where each pixel is a class ID.
        class_colors (dict): A dictionary mapping class IDs to RGB tuples, e.g., {0: (255, 0, 0), ...}.

    Returns:
        Image: A PIL Image object of the color-coded segmentation map.
    """
    # Create an empty array for the color-coded image
    height, width = segmentation_map.shape
    color_coded_map = np.zeros((height, width, 3), dtype=np.uint8)

    # Assign colors to each class
    for class_id, (color_name, color) in enumerate(class_colors.items()):
        if label_remap is not None:
            if class_id == len(label_remap)-1:
                break
            class_id = label_remap[class_id]
        mask = segmentation_map == int(class_id)
        color_coded_map[mask] = color
        

    # Convert to a PIL Image for saving or visualization
    return Image.fromarray(color_coded_map)


def rgb_to_color_name(rgb):
    """
    Convert an RGB tuple to a human-readable color name.

    Parameters:
        rgb (tuple): A tuple representing the RGB color, e.g., (255, 0, 0).
    Returns:
        str: The closest color name as a string.
    """
    try:
        # Try to match the exact color name
        return webcolors.rgb_to_name(rgb)
    except ValueError:
        # If no exact match, find the closest color
        closest_name = closest_colour(rgb)
        return closest_name


def generate_prompt_for_segmentation(class_colors, class_labels, class_percents):
    """
    Generate a descriptive prompt for the segmentation map based on class colors and class labels.

    Parameters:
        class_colors (dict): A dictionary mapping class IDs to RGB tuples, e.g., {0: (255, 0, 0), ...}.
        class_labels (dict): A dictionary mapping class IDs to their names, e.g., {0: "building", ...}.
        use_color_names (bool): Whether to use human-readable color names instead of RGB values.

    Returns:
        str: A formatted prompt describing the segmentation map.
    """
    prompt_lines = ["You are an AI visual assistant that can describe the scene given a segmentation map. " 
                    "The map uses colors to represent different land cover types. The color legend is as follows:"]
    
    presented_labels = []
    for class_id, label in class_labels.items():
        color_description = class_colors[class_id]
        percent = class_percents[class_id]
        label = class_labels.get(class_id, "unknown class")
        prompt_lines.append(f"- {color_description} color represents {label}, which occupies {int(percent*100)+1} percent area.")
        presented_labels.append(label)
    
    prompt = ("\n "
              "Do not mention any colors, color coding, or technical details. "
              "Use the given class names. Only mention land cover types in the color legend. "
              "Generate a brief and natural description of the scene by refining "
              f"'The hyperspectral image contains {', '.join(presented_labels)} land types'. "
              "Provide a concise description on their spatial distributions (e.g. left, right, top, bottom)."
              )
    
    return "\n".join(prompt_lines) + prompt



def generate_elevation_map_prompt(segmentation_map, height_map, class_labels):
    """
    Generate a descriptive prompt for an elevation map based on the segmentation map and height map.

    Parameters:
        segmentation_map (np.ndarray): A 2D numpy array where each pixel is a class ID.
        height_map (np.ndarray): A 2D numpy array where each pixel indicates the height at that location.
        class_labels (dict): A dictionary mapping class IDs to their semantic labels.
    
    Returns:
        str: A descriptive prompt for the elevation map.
    """
    # Find the highest and lowest points
    highest_height = np.max(height_map)
    lowest_height = np.min(height_map)

    # Identify the corresponding classes
    highest_class_id = segmentation_map[np.unravel_index(np.argmax(height_map), height_map.shape)]
    lowest_class_id = segmentation_map[np.unravel_index(np.argmin(height_map), height_map.shape)]
    
    highest_class = class_labels.get(highest_class_id, "unknown")
    lowest_class = class_labels.get(lowest_class_id, "unknown")

    # Generate the prompt
    prompt = (
        "This is an elevation map that indicates the height of each pixel. "
        f"The highest areas, at an elevation of approximately {int(highest_height*255/5)} meters, are {highest_class}. "
        f"The lowest areas, at an elevation of approximately {int(lowest_height*255/5)} meters, are {lowest_class}. "
        "Based on the provided context and elevation values, generate a concise and accurate description of the elevation map. "
        "Describe the image by briefly introducing: 1) the heighest and lowest land cover types; "
        "2) Is the terrain relatively flat or does it have significant elevation differences."
    )

    return prompt


def encode_image(image_path):
        with open(image_path, "rb") as image_file:
            return base64.b64encode(image_file.read()).decode('utf-8')


def downsample_image(image, skip_index):
    """
    Downsample a PIL image by skipping pixels.

    Args:
    image (PIL.Image.Image): The source image.
    skip_index (int): The number of pixels to skip.

    Returns:
    PIL.Image.Image: The downsampled image.
    """
    # Ensure the input is a PIL Image
    if not isinstance(image, Image.Image):
        raise ValueError("image must be a PIL.Image.Image object")

    # Get the size of the original image
    width, height = image.size

    # Calculate the size of the downsampled image
    new_width = (width + skip_index - 1) // skip_index
    new_height = (height + skip_index - 1) // skip_index

    # Create a new image of the desired size
    downsampled_image = Image.new("RGB", (new_width, new_height))

    # Copy pixels from the original image to the new image, skipping as appropriate
    for y in range(0, height, skip_index):
        for x in range(0, width, skip_index):
            downsampled_image.putpixel((x // skip_index, y // skip_index), image.getpixel((x, y)))

    return downsampled_image


def resize_and_encode_image(pil_image):
    """
    Resize an image to 128x128 using nearest neighbor interpolation and then encode it to base64.

    Args:
    image_path (str): The path to the image file.

    Returns:
    str: A base64 encoded string of the resized image.
    """
    # Open the image
    resized_img = downsample_image(pil_image, 2)

    # Save the resized image to a bytes buffer
    buffer = io.BytesIO()
    format = pil_image.format if pil_image.format else "PNG"  # Default to PNG if format is None

    resized_img.save(buffer, format=format)

    # Get the byte data from the buffer
    byte_data = buffer.getvalue()

    # Encode the byte data to base64
    base64_encoded = base64.b64encode(byte_data).decode('utf-8')

    return base64_encoded


def generate_flood_map_prompt(binary_mask):
    """
    Generate a descriptive prompt for flood maps for Vision Large Language Models (VLMs).

    Parameters:
        binary_mask (np.ndarray): A 2D numpy array where 1 indicates a flooded area and 0 indicates non-flooded areas.
    
    Returns:
        str: A prompt describing the flood map, including the portion of flooded area and spatial locations.
    """
    # Compute the total and flooded area
    total_area = binary_mask.size
    flooded_area = np.sum(binary_mask)
    flood_percentage = (flooded_area / total_area) * 100

    # Compute the spatial distribution of flooded areas
    height, width = binary_mask.shape
    top_half = binary_mask[:height // 2, :]
    bottom_half = binary_mask[height // 2:, :]
    left_half = binary_mask[:, :width // 2]
    right_half = binary_mask[:, width // 2:]

    # Analyze the spatial distribution
    spatial_parts = []
    if np.sum(top_half) > 0:
        spatial_parts.append("top")
    if np.sum(bottom_half) > 0:
        spatial_parts.append("bottom")
    if np.sum(left_half) > 0:
        spatial_parts.append("left")
    if np.sum(right_half) > 0:
        spatial_parts.append("right")

    spatial_description = ", ".join(spatial_parts) if spatial_parts else "no specific region"

    # Generate the prompt
    prompt = (
        "This is a flood map where areas marked with white pixels indicate flooded regions. "
        f"The flooded area occupies approximately {flood_percentage:.2f}% of the entire map. "
        "Please analyze the flood map and provide insights into the affected areas. You must generate "
        "a short description (less than 70 words) of the elevation image. First describe the portion of floods; "
        "then introduce the location of the flooded areas."
    )

    return prompt