Datasets:
Download tools/Perception.py from LvZTTTT/Earth-Bench-OW: direct link, hf CLI and curl.
- Browser
- Download file 31.5 kB
-
https://huggingface.co/datasets/LvZTTTT/Earth-Bench-OW/resolve/main/tools/Perception.py
- Command line
-
hf download hf://datasets/LvZTTTT/Earth-Bench-OW/tools/Perception.py
-
curl -L -o Perception.py https://huggingface.co/datasets/LvZTTTT/Earth-Bench-OW/resolve/main/tools/Perception.py
31.5 kB
| import argparse | |
| from pathlib import Path | |
| from fastmcp import FastMCP | |
| from tool_utils import read_image, read_image_uint8 | |
| mcp = FastMCP("perception") | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument('--temp_dir', default='tmp/tmp', type=str) | |
| parser.add_argument('--port', default=20003, type=int) | |
| args, unknown = parser.parse_known_args() | |
| TEMP_DIR = Path(args.temp_dir) | |
| TEMP_DIR.mkdir(parents=True, exist_ok=True) | |
| _REPO_ROOT = Path(__file__).resolve().parents[2] | |
| def threshold_segmentation(input_image_path, threshold, output_path): | |
| ''' | |
| Perform threshold-based segmentation on a single-band raster image. | |
| The function reads a raster image from the specified path, converts it to a binary mask | |
| by applying a fixed threshold, and writes the resulting binary image to a new file. | |
| Pixel values greater than the threshold are set to 255 (white), and values less than or | |
| equal to the threshold are set to 0 (black). | |
| Parameters: | |
| input_image_path (str): Path to the input raster image file (e.g., TIFF, PNG, JPG). | |
| threshold (float or int): Pixel intensity threshold used to generate the binary mask. | |
| output_path (str): Relative output path (under TEMP_DIR) where the result will be saved, | |
| e.g., "question17/threshold_segmentation_2022-01-16.tif". | |
| Returns: | |
| str: Message indicating the file path where the result is saved. | |
| ''' | |
| try: | |
| import os | |
| import rasterio | |
| import numpy as np | |
| with rasterio.open(input_image_path) as src: | |
| image = src.read(1) | |
| meta = src.meta.copy() | |
| binary_image = (image > threshold).astype(np.uint8) | |
| meta.update(dtype=rasterio.uint8, count=1) | |
| os.makedirs((TEMP_DIR / output_path).parent, exist_ok=True) | |
| with rasterio.open(TEMP_DIR / output_path, 'w', **meta) as dst: | |
| dst.write(binary_image, 1) | |
| return f'Result save at {TEMP_DIR / output_path}' | |
| except Exception as e: | |
| return f'Error in threshold_segmentation: {str(e)}' | |
| def bbox_expansion(bboxes: list[list[float]], radius: float, gsd: float): | |
| """ | |
| Expands bounding boxes by a given radius and returns the expanded bounding boxes. | |
| Parameters: | |
| bboxes (list[list[float]]): List of bounding boxes, each represented as [x1, y1, x2, y2]. | |
| radius (float): Expansion radius in the same unit as the GSD. | |
| gsd (float): Ground Sampling Distance in the same unit as the radius. | |
| Returns: | |
| list[list[float]]: List of expanded bounding boxes, each represented as [x1, y1, x2, y2]. | |
| """ | |
| try: | |
| expanded_bboxes = [] | |
| for bbox in bboxes: | |
| x1, y1, x2, y2 = bbox | |
| x1 = x1 - radius / gsd | |
| y1 = y1 - radius / gsd | |
| x2 = x2 + radius / gsd | |
| y2 = y2 + radius / gsd | |
| expanded_bboxes.append([x1, y1, x2, y2]) | |
| return expanded_bboxes | |
| except Exception as e: | |
| return f'Error in bbox_expansion: {str(e)}' | |
| def count_above_threshold(file_path: str, threshold: float): | |
| """ | |
| Description: | |
| Count the number of pixels in an image whose values are greater than | |
| the specified threshold. | |
| Parameters: | |
| file_path (str): | |
| Path to the input image (GeoTIFF or raster format). | |
| threshold (float): | |
| Threshold value for hotspot detection. | |
| Returns: | |
| count (int): | |
| Number of pixels with values greater than the threshold. | |
| Example: | |
| >>> count_above_threshold("sample_image.tif", 100) | |
| 2456 | |
| """ | |
| try: | |
| import numpy as np | |
| import rasterio | |
| with rasterio.open(file_path) as src: | |
| x = src.read(1) | |
| x = np.asarray(x) | |
| # Count elements greater than threshold | |
| count = np.sum(x > threshold) | |
| return int(count) | |
| except Exception as e: | |
| return f'Error in count_above_threshold: {str(e)}' | |
| def count_connected_components(image_path): | |
| """ | |
| Description: | |
| Read a binary image, apply erosion and skeletonization, | |
| then count the number of external contours in the skeletonized image. | |
| Parameters: | |
| image_path (str): | |
| Path to the input binary (black and white) image. | |
| Returns: | |
| count (int): | |
| Number of external contours detected after skeletonization. | |
| Example: | |
| >>> count_skeleton_contours("binary_mask.png") | |
| 12 | |
| """ | |
| try: | |
| import cv2 | |
| import numpy as np | |
| from skimage.morphology import skeletonize | |
| # Read image as grayscale | |
| img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE) | |
| if img is None: | |
| raise FileNotFoundError(f"Failed to read image: {image_path}") | |
| # Binarize the image | |
| _, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) | |
| # Apply erosion | |
| kernel = np.ones((3, 3), np.uint8) | |
| eroded = cv2.erode(binary, kernel, iterations=1) | |
| # Skeletonize | |
| skeleton = skeletonize(eroded > 0) # Convert to boolean for skimage | |
| skeleton_uint8 = (skeleton * 255).astype(np.uint8) | |
| # Find contours | |
| contours, _ = cv2.findContours(skeleton_uint8, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) | |
| return len(contours) | |
| except Exception as e: | |
| return f'Error in count_skeleton_contours: {str(e)}' | |
| def bboxes2centroids(bboxes): | |
| """ | |
| Description: | |
| Convert bounding boxes from [x_min, y_min, x_max, y_max] format | |
| to centroid coordinates (x, y). | |
| Parameters: | |
| bboxes (list[list[float]]): | |
| A list of bounding boxes, each defined as [x_min, y_min, x_max, y_max]. | |
| Returns: | |
| centroids (list[tuple[float, float]]): | |
| A list of centroid coordinates, each in (x, y) format. | |
| Example: | |
| >>> bboxes2centroids([[0, 0, 10, 20], [5, 5, 15, 15]]) | |
| [(5.0, 10.0), (10.0, 10.0)] | |
| """ | |
| try: | |
| return [((x1 + x2) / 2, (y1 + y2) / 2) for x1, y1, x2, y2 in bboxes] | |
| except Exception as e: | |
| return f'Error in bboxes2centroids: {str(e)}' | |
| def centroid_distance_extremes(centroids): | |
| """ | |
| Description: | |
| Compute pairwise distances between centroids and return both the closest | |
| and farthest pairs with their indices and distances. | |
| Parameters: | |
| centroids (list[tuple[float, float]] or np.ndarray): | |
| A list or NumPy array of centroid coordinates in (x, y) format. | |
| Returns: | |
| result (dict): | |
| A dictionary containing: | |
| - 'min': (index1, index2, distance) | |
| Indices of the closest centroid pair and their distance. | |
| - 'max': (index1, index2, distance) | |
| Indices of the farthest centroid pair and their distance. | |
| Example: | |
| >>> centroids = [(0, 0), (3, 4), (10, 0)] | |
| >>> centroid_distance_extremes(centroids) | |
| {'min': (0, 1, 5.0), 'max': (1, 2, 7.211102550927978)} | |
| """ | |
| try: | |
| import numpy as np | |
| points = np.array(centroids) | |
| diff = points[:, None, :] - points[None, :, :] | |
| dist_matrix = np.sqrt(np.sum(diff ** 2, axis=-1)) | |
| np.fill_diagonal(dist_matrix, np.inf) | |
| min_idx = np.unravel_index(np.argmin(dist_matrix), dist_matrix.shape) | |
| min_dist = dist_matrix[min_idx] | |
| np.fill_diagonal(dist_matrix, -np.inf) | |
| max_idx = np.unravel_index(np.argmax(dist_matrix), dist_matrix.shape) | |
| max_dist = dist_matrix[max_idx] | |
| return { | |
| "min": (int(min_idx[0]), int(min_idx[1]), float(min_dist)), | |
| "max": (int(max_idx[0]), int(max_idx[1]), float(max_dist)) | |
| } | |
| except Exception as e: | |
| return f'Error in centroid_distance_extremes: {str(e)}' | |
| def calculate_bbox_area(bboxes, gsd=None): | |
| """ | |
| Description: | |
| Calculate the total area of a list of bounding boxes in [x1, y1, x2, y2] format. | |
| Parameters: | |
| bboxes (list[list[float]]): | |
| A list of bounding boxes, where each box is defined as [x1, y1, x2, y2]. | |
| - x1, y1 → top-left corner coordinates | |
| - x2, y2 → bottom-right corner coordinates | |
| gsd (float, optional): | |
| Ground sample distance (meters per pixel). | |
| - If provided, the result is in square meters (m²). | |
| - If None, the result is in square pixels (pixel²). Default = None. | |
| Returns: | |
| total_area (float): | |
| The total area of all bounding boxes, in m² if gsd is provided, otherwise in pixel². | |
| Example: | |
| >>> calculate_bbox_area([[0, 0, 10, 20], [5, 5, 20, 15]]) | |
| 300.0 | |
| >>> calculate_bbox_area([[0, 0, 10, 20]], gsd=0.5) | |
| 50.0 | |
| """ | |
| try: | |
| total_area = 0.0 | |
| for bbox in bboxes: | |
| if len(bbox) != 4: | |
| raise ValueError(f"Invalid bbox format: {bbox}. Expected [x1, y1, x2, y2].") | |
| x1, y1, x2, y2 = bbox | |
| width = max(0.0, x2 - x1) | |
| height = max(0.0, y2 - y1) | |
| area = width * height | |
| total_area += area | |
| if gsd is not None: | |
| total_area *= gsd * gsd | |
| return total_area | |
| except Exception as e: | |
| return f'Error in calculate_bbox_area: {str(e)}' | |
| def bboxes_equal(bboxes1, bboxes2, diff_threshold=0.001): | |
| """ | |
| Determine whether two sets of bounding boxes are equivalent by rasterizing them into masks | |
| and comparing pixel-wise differences. | |
| Args: | |
| bboxes1 (list of list of float): First list of bounding boxes [[x1, y1, x2, y2], ...]. | |
| bboxes2 (list of list of float): Second list of bounding boxes. | |
| diff_threshold (float): Maximum allowed ratio of differing pixels. | |
| Returns: | |
| bool: True if masks are sufficiently similar, otherwise False. | |
| """ | |
| import numpy as np | |
| if len(bboxes1) != len(bboxes2): | |
| return False | |
| all_boxes = bboxes1 + bboxes2 | |
| max_x = max(max(b[0], b[2]) for b in all_boxes) | |
| max_y = max(max(b[1], b[3]) for b in all_boxes) | |
| W = int(np.ceil(max_x)) + 1 | |
| H = int(np.ceil(max_y)) + 1 | |
| if W <= 0 or H <= 0: | |
| return False | |
| def draw_mask(bboxes): | |
| mask = np.zeros((H, W), dtype=np.uint8) | |
| for box in bboxes: | |
| x1, y1, x2, y2 = box | |
| x1 = int(round(x1)) | |
| y1 = int(round(y1)) | |
| x2 = int(round(x2)) | |
| y2 = int(round(y2)) | |
| x1 = max(0, min(W, x1)) | |
| x2 = max(0, min(W, x2)) | |
| y1 = max(0, min(H, y1)) | |
| y2 = max(0, min(H, y2)) | |
| if x2 > x1 and y2 > y1: | |
| mask[y1:y2, x1:x2] = 1 | |
| return mask | |
| mask1 = draw_mask(bboxes1) | |
| mask2 = draw_mask(bboxes2) | |
| diff = np.abs(mask1 - mask2) | |
| diff_ratio = np.sum(diff) / diff.size | |
| return diff_ratio <= diff_threshold | |
| def _split_at_benchmark(path): | |
| """Return dataset root and the CSV lookup key for a data path. | |
| ``model_results.csv`` keys files by their dataset-relative path | |
| (``benchmark/data/questionN/X.jpg``), but the agent -- and the toolserver's | |
| physical-path remap -- pass absolute paths. Return ``(dataset_root, | |
| 'benchmark/...'-relative)`` so lookups and precomputed output files resolve | |
| portably. | |
| """ | |
| if not isinstance(path, str): | |
| return None, path | |
| parts = Path(path).parts | |
| # Native benchmark layout: .../Earth-BenchV2/benchmark/data/questionN/X.jpg | |
| idx = None | |
| for i, part in enumerate(parts): | |
| if part == 'benchmark': | |
| idx = i # last 'benchmark' component wins | |
| if idx is not None: | |
| dataset_root = Path(*parts[:idx]) if idx > 0 else Path('.') | |
| relative = str(Path(*parts[idx:])) | |
| return dataset_root, relative | |
| # V2 local RGB questions are stored at .../Earth-BenchV2/data/questionN/X.jpg, | |
| # while model_results.csv still uses benchmark/data/questionN/X.jpg keys. | |
| dataset_idx = None | |
| for i, part in enumerate(parts): | |
| if part in {'Earth-BenchV2', 'Earth-Bench'}: | |
| dataset_idx = i | |
| if dataset_idx is not None: | |
| dataset_root = Path(*parts[:dataset_idx + 1]) | |
| tail = parts[dataset_idx + 1:] | |
| if tail and tail[0] == 'data': | |
| return dataset_root, str(Path('benchmark', *tail)) | |
| # Relative local-data paths can also arrive as data/questionN/X.jpg. | |
| if parts and parts[0] == 'data': | |
| return None, str(Path('benchmark', *parts)) | |
| return None, path | |
| def _resolve_model_results_csv(dataset_root): | |
| """Locate model_results.csv portably. | |
| Precedence: ``EARTH_BENCH_MODEL_RESULTS`` env override -> | |
| ``<dataset_root>/benchmark/model_results.csv`` derived from the image path -> | |
| the legacy CWD-relative path. | |
| """ | |
| import os | |
| override = os.environ.get('EARTH_BENCH_MODEL_RESULTS') | |
| if override: | |
| return override | |
| if dataset_root is not None: | |
| candidates = [ | |
| dataset_root / 'benchmark' / 'model_results.csv', | |
| dataset_root / 'model_results.csv', | |
| ] | |
| for candidate in candidates: | |
| if candidate.is_file(): | |
| return str(candidate) | |
| for candidate in ( | |
| _REPO_ROOT / 'Earth-BenchV2' / 'model_results.csv', | |
| _REPO_ROOT / 'Earth-Bench' / 'model_results.csv', | |
| ): | |
| if candidate.is_file(): | |
| return str(candidate) | |
| return 'benchmark/model_results.csv' | |
| def get_model_output(model_name: str, input_image_path: str, **args): | |
| import json | |
| import re | |
| import shutil | |
| import pandas as pd | |
| # Resolve the lookup table and the matching key portably: the agent / the | |
| # toolserver remap pass absolute paths, while the CSV is keyed by | |
| # 'benchmark/...'-relative paths. | |
| dataset_root, key = _split_at_benchmark(input_image_path) | |
| results = pd.read_csv(_resolve_model_results_csv(dataset_root), sep=';') | |
| result = None | |
| def _resolve_output(rel_path): | |
| # Precomputed output files are stored relative to the dataset root; | |
| # resolve them so shutil.copy can find the source. | |
| candidates = [] | |
| if dataset_root is not None: | |
| candidates.append(dataset_root / rel_path) | |
| rel_parts = Path(rel_path).parts | |
| if rel_parts[:2] == ('benchmark', 'model_out'): | |
| candidates.append(dataset_root / Path(*rel_parts[1:])) | |
| rel_parts = Path(rel_path).parts | |
| if rel_parts[:2] == ('benchmark', 'model_out'): | |
| candidates.append(_REPO_ROOT / 'Earth-BenchV2' / Path(*rel_parts[1:])) | |
| candidates.append(_REPO_ROOT / 'Earth-Bench' / Path(*rel_parts[1:])) | |
| for candidate in candidates: | |
| if candidate.exists(): | |
| return str(candidate) | |
| return rel_path | |
| def _prompt_key(text): | |
| text = str(text or '').lower().replace('-', ' ').replace('_', ' ') | |
| text = re.sub(r'[^a-z0-9]+', ' ', text) | |
| words = [] | |
| for word in text.split(): | |
| if word in {'a', 'an', 'the'}: | |
| continue | |
| if len(word) > 3 and word.endswith('s'): | |
| word = word[:-1] | |
| words.append(word) | |
| return ' '.join(words) | |
| def _match_text_prompt(frame, prompt): | |
| exact = frame[frame['text_prompt'] == prompt] | |
| if not exact.empty: | |
| return exact | |
| if len(frame) == 1: | |
| return frame | |
| target = _prompt_key(prompt) | |
| if target: | |
| normalized = frame['text_prompt'].map(_prompt_key) | |
| fuzzy = frame[normalized == target] | |
| if len(fuzzy) == 1: | |
| return fuzzy | |
| return exact | |
| try: | |
| # classification | |
| if model_name in ['MSCN', 'RemoteCLIP']: | |
| result = results[(results['model'] == model_name) & (results['file_path'] == key)]['result'].values[0] | |
| # detection | |
| elif model_name in ['Strip-R-CNN', 'SM3Det']: | |
| result = results[(results['model'] == model_name) & (results['file_path'] == key)] | |
| result = _match_text_prompt(result, args['text_prompt'])['result'].values[0] | |
| result = json.loads(result) | |
| # visual grounding & counting | |
| elif model_name in ['RemoteSAM', 'InstructSAM']: | |
| result = results[(results['model'] == model_name) & (results['file_path'] == key)] | |
| result = _match_text_prompt(result, args['text_prompt'])['result'].values[0] | |
| result = json.loads(result) | |
| # segmentation | |
| elif model_name == 'SAM2': | |
| result = results[(results['model'] == model_name) & (results['file_path'] == key)] | |
| bbox_csv = result['bbox'].values[0] | |
| bbox_input = json.loads(args['bbox']) if isinstance(args['bbox'], str) else args['bbox'] | |
| if bboxes_equal(json.loads(bbox_csv), bbox_input): | |
| result = _resolve_output(result['result'].values[0]) | |
| (TEMP_DIR / args['output_path']).parent.mkdir(parents=True, exist_ok=True) | |
| shutil.copy(result, TEMP_DIR / args['output_path']) | |
| result = 'Result save at {}'.format(TEMP_DIR / args['output_path']) | |
| else: | |
| result = None | |
| # change detection | |
| elif model_name == 'ChangeOS': | |
| _, post_key = _split_at_benchmark(args['post_image_path']) | |
| file_pair = '({}, {})'.format(key, post_key) | |
| result = results[(results['model'] == model_name) & (results['file_path'] == file_pair)] | |
| if result.empty: | |
| reversed_pair = '({}, {})'.format(post_key, key) | |
| result = results[(results['model'] == model_name) & (results['file_path'] == reversed_pair)] | |
| result = result['result'].values[0] | |
| result = _resolve_output(result) | |
| (TEMP_DIR / args['output_path']).parent.mkdir(parents=True, exist_ok=True) | |
| shutil.copy(result, TEMP_DIR / args['output_path']) | |
| result = 'Result save at {}'.format(TEMP_DIR / args['output_path']) | |
| # change detection for building extraction | |
| elif model_name == 'ChangeOS_Building_Extraction': | |
| result = results[(results['model'] == 'ChangeOS') & (results['file_path'] == key)]['result'].values[0] | |
| result = _resolve_output(result) | |
| (TEMP_DIR / args['output_path']).parent.mkdir(parents=True, exist_ok=True) | |
| shutil.copy(result, TEMP_DIR / args['output_path']) | |
| result = 'Result save at {}'.format(TEMP_DIR / args['output_path']) | |
| if result is None: | |
| return 'Failed to call model' | |
| else: | |
| return result | |
| except: | |
| return 'Failed to call model' | |
| def MSCN(input_image_path): | |
| try: | |
| return get_model_output('MSCN', input_image_path) | |
| except Exception as e: | |
| return f'Error in MSCN: {str(e)}' | |
| def RemoteCLIP(input_image_path): | |
| try: | |
| return get_model_output('RemoteCLIP', input_image_path) | |
| except Exception as e: | |
| return f'Error in RemoteCLIP: {str(e)}' | |
| def Strip_R_CNN(input_image_path, text_prompt): | |
| try: | |
| return get_model_output('Strip-R-CNN', input_image_path, text_prompt=text_prompt) | |
| except Exception as e: | |
| return f'Error in Strip_R_CNN: {str(e)}' | |
| def SM3Det(input_image_path, text_prompt): | |
| try: | |
| return get_model_output('SM3Det', input_image_path, text_prompt=text_prompt) | |
| except Exception as e: | |
| return f'Error in SM3Det: {str(e)}' | |
| def RemoteSAM(input_image_path, text_prompt): | |
| try: | |
| return get_model_output('RemoteSAM', input_image_path, text_prompt=text_prompt) | |
| except Exception as e: | |
| return f'Error in RemoteSAM: {str(e)}' | |
| def InstructSAM(input_image_path, text_prompt): | |
| try: | |
| return get_model_output('InstructSAM', input_image_path, text_prompt=text_prompt) | |
| except Exception as e: | |
| return f'Error in InstructSAM: {str(e)}' | |
| def SAM2(input_image_path, bboxes, output_path): | |
| try: | |
| return get_model_output('SAM2', input_image_path, bbox=bboxes, output_path=output_path) | |
| except Exception as e: | |
| return f'Error in SAM2: {str(e)}' | |
| def ChangeOS(pre_image_path: str, post_image_path: str, output_path: str): | |
| try: | |
| if pre_image_path == post_image_path: | |
| return get_model_output('ChangeOS_Building_Extraction', pre_image_path, output_path=output_path) | |
| else: | |
| return get_model_output('ChangeOS', pre_image_path, post_image_path=post_image_path, output_path=output_path) | |
| except Exception as e: | |
| return f'Error in ChangeOS: {str(e)}' | |
| if __name__ == "__main__": | |
| mcp.run(transport="http", host="127.0.0.1", port=args.port) | |