diff --git a/HyperVision/__init__.py b/HyperVision/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d593571d49a489dab4670347215a5b04b51d72ec --- /dev/null +++ b/HyperVision/__init__.py @@ -0,0 +1,11 @@ +from .build_HyperVision import ( + _build_HyperVision, + build_HyperVision, + build_HyperVision_h, + build_HyperVision_l, + build_HyperVision_b, + HyperVision_model_registry, +) + +from .predictor import HyperVision_Predictor +from .automatic_mask_generator import SamAutomaticMaskGenerator diff --git a/HyperVision/__pycache__/__init__.cpython-310.pyc b/HyperVision/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..948d7a5adf73b52fa0158a4611055a09b96401ac Binary files /dev/null and b/HyperVision/__pycache__/__init__.cpython-310.pyc differ diff --git a/HyperVision/__pycache__/__init__.cpython-311.pyc b/HyperVision/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ae689054358ba96f7f0263d738990c7713d81d5 Binary files /dev/null and b/HyperVision/__pycache__/__init__.cpython-311.pyc differ diff --git a/HyperVision/__pycache__/__init__.cpython-313.pyc b/HyperVision/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64e61efdc61759374568c69d8a7d4a6423ed715d Binary files /dev/null and b/HyperVision/__pycache__/__init__.cpython-313.pyc differ diff --git a/HyperVision/__pycache__/automatic_mask_generator.cpython-310.pyc b/HyperVision/__pycache__/automatic_mask_generator.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7df86ec0a1c977e0afb02bbdd8f763811c40e42 Binary files /dev/null and b/HyperVision/__pycache__/automatic_mask_generator.cpython-310.pyc differ diff --git a/HyperVision/__pycache__/automatic_mask_generator.cpython-311.pyc b/HyperVision/__pycache__/automatic_mask_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e98055a1012e6ae0720385445fc0f46d85e5035 Binary files /dev/null and b/HyperVision/__pycache__/automatic_mask_generator.cpython-311.pyc differ diff --git a/HyperVision/__pycache__/build_HyperFree.cpython-311.pyc b/HyperVision/__pycache__/build_HyperFree.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f984592eeb92f68824a833c2d0bba9540a05a04 Binary files /dev/null and b/HyperVision/__pycache__/build_HyperFree.cpython-311.pyc differ diff --git a/HyperVision/__pycache__/build_HyperVision.cpython-310.pyc b/HyperVision/__pycache__/build_HyperVision.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8507ca84ee69c1da9f233c141048dfa82418900 Binary files /dev/null and b/HyperVision/__pycache__/build_HyperVision.cpython-310.pyc differ diff --git a/HyperVision/__pycache__/build_HyperVision.cpython-313.pyc b/HyperVision/__pycache__/build_HyperVision.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f375bf37dafd5d5efd4e92970e053ea99f2cb94b Binary files /dev/null and b/HyperVision/__pycache__/build_HyperVision.cpython-313.pyc differ diff --git a/HyperVision/__pycache__/predictor.cpython-310.pyc b/HyperVision/__pycache__/predictor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53265b314cb1c97953245c815cdb1b48c62747cf Binary files /dev/null and b/HyperVision/__pycache__/predictor.cpython-310.pyc differ diff --git a/HyperVision/__pycache__/predictor.cpython-311.pyc b/HyperVision/__pycache__/predictor.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0fb0a367ea0bd40d06233c4939b5698348c110b5 Binary files /dev/null and b/HyperVision/__pycache__/predictor.cpython-311.pyc differ diff --git a/HyperVision/automatic_mask_generator.py b/HyperVision/automatic_mask_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..a1cf70efc6b68c11b7497bdf3887e905a1d96839 --- /dev/null +++ b/HyperVision/automatic_mask_generator.py @@ -0,0 +1,395 @@ +import numpy as np +import torch +from torchvision.ops.boxes import batched_nms, box_area # type: ignore + +from typing import Any, Dict, List, Optional, Tuple +import torch.nn.functional as F +from .modeling import Sam +from .predictor import HyperVision_Predictor +from .utils.amg import ( + MaskData, + area_from_rle, + batch_iterator, + batched_mask_to_box, + box_xyxy_to_xywh, + build_all_layer_point_grids, + calculate_stability_score, + coco_encode_rle, + generate_crop_boxes, + is_box_near_crop_edge, + mask_to_rle_pytorch, + remove_small_regions, + rle_to_mask, + uncrop_boxes_xyxy, + uncrop_masks, + uncrop_points, +) + + +class SamAutomaticMaskGenerator: + def __init__( + self, + model: Sam, + points_per_side: Optional[int] = 32, + points_per_batch: int = 64, + pred_iou_thresh: float = 0.88, + stability_score_thresh: float = 0.95, + stability_score_offset: float = 1.0, + box_nms_thresh: float = 0.7, + crop_n_layers: int = 0, + crop_nms_thresh: float = 0.7, + crop_overlap_ratio: float = 512 / 1500, + crop_n_points_downscale_factor: int = 1, + point_grids: Optional[List[np.ndarray]] = None, + min_mask_region_area: int = 0, + output_mode: str = "binary_mask", + ) -> None: + """ + Using a SAM model, generates masks for the entire image. + Generates a grid of point prompts over the image, then filters + low quality and duplicate mask[s. The default settings are chosen + for SAM with a ViT-H backbone. + + Arguments: + model (Sam): The SAM model to use for mask prediction. + points_per_side (int or None): The number of points to be sampled + along one side of the image. The total number of points is + points_per_side**2. If None, 'point_grids' must provide explicit + point sampling. + points_per_batch (int): Sets the number of points run simultaneously + by the model. Higher numbers may be faster but use more GPU memory. + pred_iou_thresh (float): A filtering threshold in [0,1], using the + model's predicted mask quality. + stability_score_thresh (float): A filtering threshold in [0,1], using + the stability of the mask under changes to the cutoff used to binarize + the model's mask predictions. + stability_score_offset (float): The amount to shift the cutoff when + calculated the stability score. + box_nms_thresh (float): The box IoU cutoff used by non-maximal + suppression to filter duplicate masks. + crop_n_layers (int): If >0, mask prediction will be run again on + crops of the image. Sets the number of layers to run, where each + layer has 2**i_layer number of image crops. + crop_nms_thresh (float): The box IoU cutoff used by non-maximal + suppression to filter duplicate masks between different crops. + crop_overlap_ratio (float): Sets the degree to which crops overlap. + In the first crop layer, crops will overlap by this fraction of + the image length. Later layers with more crops scale down this overlap. + crop_n_points_downscale_factor (int): The number of points-per-side + sampled in layer n is scaled down by crop_n_points_downscale_factor**n. + point_grids (list(np.ndarray) or None): A list over explicit grids + of points used for sampling, normalized to [0,1]. The nth grid in the + list is used in the nth crop layer. Exclusive with points_per_side. + min_mask_region_area (int): If >0, postprocessing will be applied + to remove disconnected regions and holes in masks with area smaller + than min_mask_region_area. Requires opencv. + output_mode (str): The form masks are returned in. Can be 'binary_mask', + 'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools. + For large resolutions, 'binary_mask' may consume large amounts of + memory. + """ + + assert (points_per_side is None) != ( + point_grids is None + ), "Exactly one of points_per_side or point_grid must be provided." + if points_per_side is not None: + self.point_grids = build_all_layer_point_grids( + points_per_side, + crop_n_layers, + crop_n_points_downscale_factor, + ) + elif point_grids is not None: + self.point_grids = point_grids + else: + raise ValueError("Can't have both points_per_side and point_grid be None.") + + assert output_mode in [ + "binary_mask", + "uncompressed_rle", + "coco_rle", + ], f"Unknown output_mode {output_mode}." + if output_mode == "coco_rle": + from pycocotools import mask as mask_utils # type: ignore # noqa: F401 + + if min_mask_region_area > 0: + import cv2 # type: ignore # noqa: F401 + + self.predictor = HyperVision_Predictor(model) + self.points_per_batch = points_per_batch + self.pred_iou_thresh = pred_iou_thresh + self.stability_score_thresh = stability_score_thresh + self.stability_score_offset = stability_score_offset + self.box_nms_thresh = box_nms_thresh + self.crop_n_layers = crop_n_layers + self.crop_nms_thresh = crop_nms_thresh + self.crop_overlap_ratio = crop_overlap_ratio + self.crop_n_points_downscale_factor = crop_n_points_downscale_factor + self.min_mask_region_area = min_mask_region_area + self.output_mode = output_mode + + @torch.no_grad() + def generate(self, image: np.ndarray, spectral_lengths = None, GSD=None) -> List[Dict[str, Any]]: + """ + Generates masks for the given image. + + Arguments: + image (np.ndarray): The image to generate masks for, in HWC uint8 format. + + Returns: + list(dict(str, any)): A list over records for masks. Each record is + a dict containing the following keys: + segmentation (dict(str, any) or np.ndarray): The mask. If + output_mode='binary_mask', is an array of shape HW. Otherwise, + is a dictionary containing the RLE. + bbox (list(float)): The box around the mask, in XYWH format. + area (int): The area in pixels of the mask. + predicted_iou (float): The model's own prediction of the mask's + quality. This is filtered by the pred_iou_thresh parameter. + point_coords (list(list(float))): The point coordinates input + to the model to generate this mask. + stability_score (float): A measure of the mask's quality. This + is filtered on using the stability_score_thresh parameter. + crop_box (list(float)): The crop of the image used to generate + the mask, given in XYWH format. + """ + + # Generate masks + mask_data = self._generate_masks(image, spectral_lengths, GSD) + + # Filter small disconnected regions and holes in masks + if self.min_mask_region_area > 0: + mask_data = self.postprocess_small_regions( + mask_data, + self.min_mask_region_area, + max(self.box_nms_thresh, self.crop_nms_thresh), + ) + + # Encode masks + if self.output_mode == "coco_rle": + mask_data["segmentations"] = [coco_encode_rle(rle) for rle in mask_data["rles"]] + elif self.output_mode == "binary_mask": + mask_data["segmentations"] = [rle_to_mask(rle) for rle in mask_data["rles"]] + else: + mask_data["segmentations"] = mask_data["rles"] + + # Write mask records + curr_anns = [] + for idx in range(len(mask_data["segmentations"])): + ann = { + "segmentation": mask_data["segmentations"][idx], + "area": area_from_rle(mask_data["rles"][idx]), + "bbox": box_xyxy_to_xywh(mask_data["boxes"][idx]).tolist(), + "predicted_iou": mask_data["iou_preds"][idx].item(), + "point_coords": [mask_data["points"][idx].tolist()], + "stability_score": mask_data["stability_score"][idx].item(), + "crop_box": box_xyxy_to_xywh(mask_data["crop_boxes"][idx]).tolist(), + } + curr_anns.append(ann) + + return curr_anns + + def anns2mask(self, anns): + if len(anns) == 0: + print("len=0") + return + sorted_anns = sorted(anns, key=(lambda x: x['area']), reverse=True) + res = np.zeros((1, anns[0]['segmentation'].shape[0], anns[0]['segmentation'].shape[1])) + + for ann in sorted_anns: + m = ann['segmentation'] + area_ratio = (ann['area']) / (anns[0]['segmentation'].shape[0] * anns[0]['segmentation'].shape[1]) + if area_ratio > 0.9: + continue + locs = np.where(m == True) + res_t = np.zeros((1, anns[0]['segmentation'].shape[0], anns[0]['segmentation'].shape[1])) + res_t[0, locs[0], locs[1]] = 1 + res = np.concatenate([res_t, res], axis=0) + return res + + def cosine_similarity(self, vector1, vector2): + + dot_product = np.dot(vector1, vector2) + + norm_v1 = np.linalg.norm(vector1) + norm_v2 = np.linalg.norm(vector2) + # 计算余弦相似度 + return dot_product / (norm_v1 * norm_v2) + + def _generate_masks(self, image: np.ndarray, spectral_lengths=None, GSD=None) -> MaskData: + orig_size = image.shape[:2] + crop_boxes, layer_idxs = generate_crop_boxes( + orig_size, self.crop_n_layers, self.crop_overlap_ratio + ) + + # Iterate over image crops + data = MaskData() + for crop_box, layer_idx in zip(crop_boxes, layer_idxs): + crop_data = self._process_crop(image, crop_box, layer_idx, orig_size, spectral_lengths, GSD) + data.cat(crop_data) + + # Remove duplicate masks between crops + if len(crop_boxes) > 1: + # Prefer masks from smaller crops + scores = 1 / box_area(data["crop_boxes"]) + scores = scores.to(data["boxes"].device) + keep_by_nms = batched_nms( + data["boxes"].float(), + scores, + torch.zeros_like(data["boxes"][:, 0]), # categories + iou_threshold=self.crop_nms_thresh, + ) + data.filter(keep_by_nms) + + data.to_numpy() + return data + + def _process_crop( + self, + image: np.ndarray, + crop_box: List[int], + crop_layer_idx: int, + orig_size: Tuple[int, ...], + spectral_lengths = None, + GSD=None, + ) -> MaskData: + # Crop the image and calculate embeddings + x0, y0, x1, y1 = crop_box + cropped_im = image[y0:y1, x0:x1, :] + cropped_im_size = cropped_im.shape[:2] + self.predictor.set_image(cropped_im, True, spectral_lengths, GSD) + + # Get points for this crop + points_scale = np.array(cropped_im_size)[None, ::-1] + points_for_image = self.point_grids[crop_layer_idx] * points_scale + + # Generate masks for this crop in batches + data = MaskData() + for (points,) in batch_iterator(self.points_per_batch, points_for_image): + batch_data = self._process_batch(points, cropped_im_size, crop_box, orig_size) + data.cat(batch_data) + del batch_data + self.predictor.reset_image() + + # Remove duplicates within this crop. + keep_by_nms = batched_nms( + data["boxes"].float(), + data["iou_preds"], + torch.zeros_like(data["boxes"][:, 0]), # categories + iou_threshold=self.box_nms_thresh, + ) + data.filter(keep_by_nms) + + # Return to the original image frame + data["boxes"] = uncrop_boxes_xyxy(data["boxes"], crop_box) + data["points"] = uncrop_points(data["points"], crop_box) + data["crop_boxes"] = torch.tensor([crop_box for _ in range(len(data["rles"]))]) + + return data + + def _process_batch( + self, + points: np.ndarray, + im_size: Tuple[int, ...], + crop_box: List[int], + orig_size: Tuple[int, ...], + ) -> MaskData: + orig_h, orig_w = orig_size + + # Run model on this batch + transformed_points = self.predictor.transform.apply_coords(points, im_size) + in_points = torch.as_tensor(transformed_points, device=self.predictor.device) + in_labels = torch.ones(in_points.shape[0], dtype=torch.int, device=in_points.device) + masks, iou_preds, _ = self.predictor.predict_torch( + in_points[:, None, :], + in_labels[:, None], + multimask_output=True, + return_logits=True, + ) + + # Serialize predictions and store in MaskData + data = MaskData( + masks=masks.flatten(0, 1), + iou_preds=iou_preds.flatten(0, 1), + points=torch.as_tensor(points.repeat(masks.shape[1], axis=0)), + ) + del masks + + # Filter by predicted IoU + if self.pred_iou_thresh > 0.0: + keep_mask = data["iou_preds"] > self.pred_iou_thresh + data.filter(keep_mask) + + # Calculate stability score + data["stability_score"] = calculate_stability_score( + data["masks"], self.predictor.model.mask_threshold, self.stability_score_offset + ) + if self.stability_score_thresh > 0.0: + keep_mask = data["stability_score"] >= self.stability_score_thresh + data.filter(keep_mask) + + # Threshold masks and calculate boxes + data["masks"] = data["masks"] > self.predictor.model.mask_threshold + data["boxes"] = batched_mask_to_box(data["masks"]) + + # Filter boxes that touch crop boundaries + keep_mask = ~is_box_near_crop_edge(data["boxes"], crop_box, [0, 0, orig_w, orig_h]) + if not torch.all(keep_mask): + data.filter(keep_mask) + + # Compress to RLE + data["masks"] = uncrop_masks(data["masks"], crop_box, orig_h, orig_w) + data["rles"] = mask_to_rle_pytorch(data["masks"]) + del data["masks"] + + return data + + @staticmethod + def postprocess_small_regions( + mask_data: MaskData, min_area: int, nms_thresh: float + ) -> MaskData: + """ + Removes small disconnected regions and holes in masks, then reruns + box NMS to remove any new duplicates. + + Edits mask_data in place. + + Requires open-cv as a dependency. + """ + if len(mask_data["rles"]) == 0: + return mask_data + + # Filter small disconnected regions and holes + new_masks = [] + scores = [] + for rle in mask_data["rles"]: + mask = rle_to_mask(rle) + + mask, changed = remove_small_regions(mask, min_area, mode="holes") + unchanged = not changed + mask, changed = remove_small_regions(mask, min_area, mode="islands") + unchanged = unchanged and not changed + + new_masks.append(torch.as_tensor(mask).unsqueeze(0)) + # Give score=0 to changed masks and score=1 to unchanged masks + # so NMS will prefer ones that didn't need postprocessing + scores.append(float(unchanged)) + + # Recalculate boxes and remove any new duplicates + masks = torch.cat(new_masks, dim=0) + boxes = batched_mask_to_box(masks) + keep_by_nms = batched_nms( + boxes.float(), + torch.as_tensor(scores), + torch.zeros_like(boxes[:, 0]), # categories + iou_threshold=nms_thresh, + ) + + # Only recalculate RLEs for masks that have changed + for i_mask in keep_by_nms: + if scores[i_mask] == 0.0: + mask_torch = masks[i_mask].unsqueeze(0) + mask_data["rles"][i_mask] = mask_to_rle_pytorch(mask_torch)[0] + mask_data["boxes"][i_mask] = boxes[i_mask] # update res directly + mask_data.filter(keep_by_nms) + + return mask_data \ No newline at end of file diff --git a/HyperVision/build_HyperVision.py b/HyperVision/build_HyperVision.py new file mode 100644 index 0000000000000000000000000000000000000000..a61d41fbe7f7f86c13ac632181c7d6bc66dd2a06 --- /dev/null +++ b/HyperVision/build_HyperVision.py @@ -0,0 +1,136 @@ +import torch +import torch.nn.functional as F +from functools import partial +from HyperVision.modeling import ImageEncoderViT, MaskDecoder, PromptEncoder, Sam, TwoWayTransformer + + +def build_HyperVision_h(checkpoint=None, image_size=1024, vit_patch_size = 16, +encoder_global_attn_indexes=[15, 23, 31], merge_indexs=[8, 32], class_number = -1): + return _build_HyperVision( + encoder_embed_dim=1280, + encoder_depth=32, + encoder_num_heads=16, + encoder_global_attn_indexes=[7, 15, 23, 31] if encoder_global_attn_indexes == -1 else encoder_global_attn_indexes, + merge_indexs=merge_indexs, + vit_patch_size=vit_patch_size, + image_size=image_size, + checkpoint=checkpoint, + class_number = class_number, + ) + + +build_HyperVision = build_HyperVision_h + + +def build_HyperVision_l(checkpoint=None, image_size=1024, vit_patch_size = 16, +encoder_global_attn_indexes=[11, 17, 23], merge_indexs=[6, 24], class_number = -1): + return _build_HyperVision( + encoder_embed_dim=1024, + encoder_depth=24, + encoder_num_heads=16, + encoder_global_attn_indexes=[5, 11, 17, 23] if encoder_global_attn_indexes == -1 else encoder_global_attn_indexes, + merge_indexs=merge_indexs, + vit_patch_size=vit_patch_size, + image_size=image_size, + checkpoint=checkpoint, + class_number = class_number, + ) + + +def build_HyperVision_b(checkpoint=None, image_size=1024, vit_patch_size = 16, +encoder_global_attn_indexes=[5, 8, 11], merge_indexs=[3, 12], class_number = -1): + return _build_HyperVision( + encoder_embed_dim=768, + encoder_depth=12, + encoder_num_heads=12, + encoder_global_attn_indexes=[2, 5, 8, 11] if encoder_global_attn_indexes == -1 else encoder_global_attn_indexes, + merge_indexs=merge_indexs, + vit_patch_size=vit_patch_size, + image_size=image_size, + checkpoint=checkpoint, + class_number = class_number, + ) + + +HyperVision_model_registry = { + "default": build_HyperVision_h, + "vit_h": build_HyperVision_h, + "vit_l": build_HyperVision_l, + "vit_b": build_HyperVision_b, +} + + +def load_and_resize_params(model, checkpoint_path): + checkpoint = torch.load(checkpoint_path, map_location='cpu') + model_dict = model.state_dict() + + for k, v in checkpoint.items(): + if k in model_dict: + if v.shape != model_dict[k].shape: + if 'pos_embed' in k: + v = F.interpolate(v.permute((0,3,1,2)), size=(model_dict[k].shape[1], model_dict[k].shape[2]), mode='nearest').permute((0,2,3,1)) + elif 'rel_pos' in k: + v = F.interpolate(v.unsqueeze(0).unsqueeze(0), size=(model_dict[k].shape[0], model_dict[k].shape[1]),).squeeze(0).squeeze(0) + elif 'weight_bank' in k: + v = F.interpolate(v, size=(model_dict[k].shape[2], model_dict[k].shape[3]), mode='nearest') + + model_dict[k] = v + + model.load_state_dict(model_dict, strict=False) + return model + + +def _build_HyperVision( + encoder_embed_dim, + encoder_depth, + encoder_num_heads, + encoder_global_attn_indexes, + merge_indexs, + vit_patch_size, + checkpoint=None, + image_size=1024, + class_number = -1, +): + prompt_embed_dim = 256 + image_embedding_size = image_size // vit_patch_size + hypervision = Sam( + image_encoder=ImageEncoderViT( + depth=encoder_depth, + embed_dim=encoder_embed_dim, + img_size=image_size, + mlp_ratio=4, + norm_layer=partial(torch.nn.LayerNorm, eps=1e-6), + num_heads=encoder_num_heads, + patch_size=vit_patch_size, + qkv_bias=True, + use_rel_pos=True, + global_attn_indexes=encoder_global_attn_indexes, + merge_indexs = merge_indexs, + window_size=14, + out_chans=prompt_embed_dim, + ), + prompt_encoder=PromptEncoder( + embed_dim=prompt_embed_dim, + image_embedding_size=(image_embedding_size, image_embedding_size), + input_image_size=(image_size, image_size), + mask_in_chans=16, + ), + mask_decoder=MaskDecoder( + num_multimask_outputs=3, + transformer=TwoWayTransformer( + depth=2, + embedding_dim=prompt_embed_dim, + mlp_dim=2048, + num_heads=8, + ), + transformer_dim=prompt_embed_dim, + iou_head_depth=3, + iou_head_hidden_dim=256, + class_number = class_number + ), + ) + + hypervision.eval() + if checkpoint is not None: + load_and_resize_params(hypervision, checkpoint) + return hypervision diff --git a/HyperVision/modeling/__init__.py b/HyperVision/modeling/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..38e906243d898d7fc071c0fe218338c5cace3ea1 --- /dev/null +++ b/HyperVision/modeling/__init__.py @@ -0,0 +1,11 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from .sam import Sam +from .image_encoder import ImageEncoderViT +from .mask_decoder import MaskDecoder +from .prompt_encoder import PromptEncoder +from .transformer import TwoWayTransformer diff --git a/HyperVision/modeling/__pycache__/__init__.cpython-310.pyc b/HyperVision/modeling/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16ab478f2e13ad25b7d145597842cfc9bc054284 Binary files /dev/null and b/HyperVision/modeling/__pycache__/__init__.cpython-310.pyc differ diff --git a/HyperVision/modeling/__pycache__/__init__.cpython-311.pyc b/HyperVision/modeling/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24c0b6a74e31c8d43fc058147d08e2c6b1527e09 Binary files /dev/null and b/HyperVision/modeling/__pycache__/__init__.cpython-311.pyc differ diff --git a/HyperVision/modeling/__pycache__/common.cpython-310.pyc b/HyperVision/modeling/__pycache__/common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a3d51327acbcafc67852a390d76655064384fee Binary files /dev/null and b/HyperVision/modeling/__pycache__/common.cpython-310.pyc differ diff --git a/HyperVision/modeling/__pycache__/common.cpython-311.pyc b/HyperVision/modeling/__pycache__/common.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2db80e0d2f2cea355ef49b1006ed1d9e31f48fb1 Binary files /dev/null and b/HyperVision/modeling/__pycache__/common.cpython-311.pyc differ diff --git a/HyperVision/modeling/__pycache__/image_encoder.cpython-310.pyc b/HyperVision/modeling/__pycache__/image_encoder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6344d7ae157f9e2a22cc65035d2623903b77c8f7 Binary files /dev/null and b/HyperVision/modeling/__pycache__/image_encoder.cpython-310.pyc differ diff --git a/HyperVision/modeling/__pycache__/image_encoder.cpython-311.pyc b/HyperVision/modeling/__pycache__/image_encoder.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04d444a2e366fa287fe03df01bfe421b3e447f55 Binary files /dev/null and b/HyperVision/modeling/__pycache__/image_encoder.cpython-311.pyc differ diff --git a/HyperVision/modeling/__pycache__/mask_decoder.cpython-310.pyc b/HyperVision/modeling/__pycache__/mask_decoder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1caf390a9935386a703d6304757048fdef9080ca Binary files /dev/null and b/HyperVision/modeling/__pycache__/mask_decoder.cpython-310.pyc differ diff --git a/HyperVision/modeling/__pycache__/mask_decoder.cpython-311.pyc b/HyperVision/modeling/__pycache__/mask_decoder.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9aa122ce5aca4b6ca31fc1b0f11f7188d0adf729 Binary files /dev/null and b/HyperVision/modeling/__pycache__/mask_decoder.cpython-311.pyc differ diff --git a/HyperVision/modeling/__pycache__/prompt_encoder.cpython-310.pyc b/HyperVision/modeling/__pycache__/prompt_encoder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c43295aec38b3401077dede76283d1c4b4d5a43c Binary files /dev/null and b/HyperVision/modeling/__pycache__/prompt_encoder.cpython-310.pyc differ diff --git a/HyperVision/modeling/__pycache__/prompt_encoder.cpython-311.pyc b/HyperVision/modeling/__pycache__/prompt_encoder.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ab3fd3058f1cb3ba87e9492915a90c0ab141ee1 Binary files /dev/null and b/HyperVision/modeling/__pycache__/prompt_encoder.cpython-311.pyc differ diff --git a/HyperVision/modeling/__pycache__/sam.cpython-310.pyc b/HyperVision/modeling/__pycache__/sam.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dcc7dae417238e4155dd219fcd442c766c664bc4 Binary files /dev/null and b/HyperVision/modeling/__pycache__/sam.cpython-310.pyc differ diff --git a/HyperVision/modeling/__pycache__/sam.cpython-311.pyc b/HyperVision/modeling/__pycache__/sam.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..052e6658b6ee8b9a6fe05ba5a503c961ad838b2c Binary files /dev/null and b/HyperVision/modeling/__pycache__/sam.cpython-311.pyc differ diff --git a/HyperVision/modeling/__pycache__/scale_aware_PE.cpython-310.pyc b/HyperVision/modeling/__pycache__/scale_aware_PE.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9af4a02de7239dddd6ce2082f8ba27ddf24ee8c Binary files /dev/null and b/HyperVision/modeling/__pycache__/scale_aware_PE.cpython-310.pyc differ diff --git a/HyperVision/modeling/__pycache__/scale_aware_PE.cpython-311.pyc b/HyperVision/modeling/__pycache__/scale_aware_PE.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8c85ded3bfca5424fa7f6bcf51141ef7f273361 Binary files /dev/null and b/HyperVision/modeling/__pycache__/scale_aware_PE.cpython-311.pyc differ diff --git a/HyperVision/modeling/__pycache__/transformer.cpython-310.pyc b/HyperVision/modeling/__pycache__/transformer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2fe22c662731ce7f247c2535311c42604ed73ea Binary files /dev/null and b/HyperVision/modeling/__pycache__/transformer.cpython-310.pyc differ diff --git a/HyperVision/modeling/__pycache__/transformer.cpython-311.pyc b/HyperVision/modeling/__pycache__/transformer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd85a004e5336a99215c41f76047598ebbe54ba8 Binary files /dev/null and b/HyperVision/modeling/__pycache__/transformer.cpython-311.pyc differ diff --git a/HyperVision/modeling/common.py b/HyperVision/modeling/common.py new file mode 100644 index 0000000000000000000000000000000000000000..ab66daaed5dc700bc25dcb7793c7015d991a1f22 --- /dev/null +++ b/HyperVision/modeling/common.py @@ -0,0 +1,37 @@ +import torch +import torch.nn as nn + +from typing import Type + + +class MLPBlock(nn.Module): + def __init__( + self, + embedding_dim: int, + mlp_dim: int, + act: Type[nn.Module] = nn.GELU, + ) -> None: + super().__init__() + self.lin1 = nn.Linear(embedding_dim, mlp_dim) + self.lin2 = nn.Linear(mlp_dim, embedding_dim) + self.act = act() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.lin2(self.act(self.lin1(x))) + + +# From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa +# Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa +class LayerNorm2d(nn.Module): + def __init__(self, num_channels: int, eps: float = 1e-6) -> None: + super().__init__() + self.weight = nn.Parameter(torch.ones(num_channels)) + self.bias = nn.Parameter(torch.zeros(num_channels)) + self.eps = eps + + def forward(self, x: torch.Tensor) -> torch.Tensor: + u = x.mean(1, keepdim=True) + s = (x - u).pow(2).mean(1, keepdim=True) + x = (x - u) / torch.sqrt(s + self.eps) + x = self.weight[:, None, None] * x + self.bias[:, None, None] + return x diff --git a/HyperVision/modeling/image_encoder.py b/HyperVision/modeling/image_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..35cf075577e34e49890d756436188bf7cfcaa916 --- /dev/null +++ b/HyperVision/modeling/image_encoder.py @@ -0,0 +1,672 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + +from typing import Optional, Tuple, Type +from .common import LayerNorm2d, MLPBlock +import math +import warnings +import numpy as np +import random +from itertools import repeat +TORCH_MAJOR = int(torch.__version__.split('.')[0]) +TORCH_MINOR = int(torch.__version__.split('.')[1]) +if TORCH_MAJOR == 1 and TORCH_MINOR < 8: + from torch._six import container_abcs +else: + import collections.abc as container_abcs +from ..utils.spectral_process_utils import * +from .scale_aware_PE import get_2d_sincos_pos_embed_with_resolution + + +class MLP(nn.Module): + def __init__( + self, + input_dim: int, + hidden_dim: int, + output_dim: int, + num_layers: int, + sigmoid_output: bool = False, + ) -> None: + super().__init__() + self.num_layers = num_layers + h = [hidden_dim] * (num_layers - 1) + self.layers = nn.ModuleList( + nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]) + ) + self.sigmoid_output = sigmoid_output + + def forward(self, x): + for i, layer in enumerate(self.layers): + x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x) + if self.sigmoid_output: + x = F.sigmoid(x) + return x + + +class ImageEncoderViT(nn.Module): + def __init__( + self, + img_size: int = 1024, + patch_size: int = 16, + in_chans: int = 3, + embed_dim: int = 768, + depth: int = 12, + num_heads: int = 12, + mlp_ratio: float = 4.0, + out_chans: int = 256, + qkv_bias: bool = True, + norm_layer: Type[nn.Module] = nn.LayerNorm, + act_layer: Type[nn.Module] = nn.GELU, + use_abs_pos: bool = False, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + window_size: int = 0, + global_attn_indexes: Tuple[int, ...] = (), + in_chans_spectral = 85, + merge_indexs = [3, 6, 8, 11], # for Vit-b version + ) -> None: + """ + Args: + img_size (int): Input image size. + patch_size (int): Patch size. + in_chans (int): Number of input image channels. + embed_dim (int): Patch embedding dimension. + depth (int): Depth of ViT. + num_heads (int): Number of attention heads in each ViT block. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool): If True, add a learnable bias to query, key, value. + norm_layer (nn.Module): Normalization layer. + act_layer (nn.Module): Activation layer. + use_abs_pos (bool): If True, use absolute positional embeddings. + use_rel_pos (bool): If True, add relative positional embeddings to the attention map. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + window_size (int): Window size for window attention blocks. + global_attn_indexes (list): Indexes for blocks using global attention. + """ + super().__init__() + self.in_chans = in_chans + self.img_size = img_size + self.embed_dim = embed_dim + self.depth = depth + self.patch_size = patch_size + self.out_chans = out_chans + + self.pos_embed_mlp = MLP(self.embed_dim, self.embed_dim//2, self.embed_dim, 3, sigmoid_output=False) + + self.blocks = nn.ModuleList() + for i in range(depth): + block = Block( + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + norm_layer=norm_layer, + act_layer=act_layer, + use_rel_pos=use_rel_pos, + rel_pos_zero_init=rel_pos_zero_init, + window_size=window_size if i not in global_attn_indexes else 0, + input_size=(img_size // patch_size, img_size // patch_size), + ) + self.blocks.append(block) + + self.contras_modules = nn.ModuleList() + for i in range(2): + block = Block( + dim=256, + num_heads=8, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + norm_layer=norm_layer, + act_layer=act_layer, + use_rel_pos=use_rel_pos, + rel_pos_zero_init=rel_pos_zero_init, + window_size=16, + input_size=(img_size // patch_size, img_size // patch_size), + ) + self.contras_modules.append(block) + + self.neck = nn.Sequential( + nn.Conv2d( + embed_dim, + out_chans, + kernel_size=1, + bias=False, + ), + LayerNorm2d(out_chans), + nn.Conv2d( + out_chans, + out_chans, + kernel_size=3, + padding=1, + bias=False, + ), + LayerNorm2d(out_chans), + ) + + self.nm_dis = 10 + self.Band_feature_indices_hy, self.unmatch_indices_hy, self.point_bank_indices_hy = find_corresponding_indices(input_wavelengths_hy, spectral_wavelength,self.nm_dis) + self.Band_feature_indices_mu, self.unmatch_indices_mu, self.point_bank_indices_mu = find_corresponding_indices(input_wavelengths_mu, spectral_wavelength,self.nm_dis) + self.weight_bank_data_indices_hy, _, self.weight_bank_indices_hy = find_corresponding_indices(input_wavelengths_hy, weight_bank_wavelength,self.nm_dis) + + self.point_spectral_weight_bank_w = nn.Parameter(torch.randn((self.embed_dim, len(spectral_wavelength), patch_size, patch_size))) + self.point_spectral_weight_bank_b = nn.Parameter(torch.randn(self.embed_dim)) + self.block_spectral_weight_bank_w = nn.Parameter(torch.randn((self.embed_dim, len(weight_bank_wavelength), patch_size, patch_size))) + self.block_spectral_weight_bank_b = nn.Parameter(torch.randn(self.embed_dim)) + + self.merge_indexs = merge_indexs + self.global_attn_indexes = global_attn_indexes + # self.multi_scale_convs = nn.ModuleList([ + # nn.Sequential( + # nn.Conv2d(embed_dim, embed_dim, kernel_size=3, stride=2, padding=1, bias=True), # 保持特征图尺寸‌:ml-citation{ref="6" data="citationList"} + # nn.GELU() + # ) + # for _ in range(len(self.merge_indexs))]) if self.merge_indexs != None else None + self.multi_scale_convs = nn.ModuleList([ + PatchMerging(dim=embed_dim) + for i in range(len(self.merge_indexs))]) if self.merge_indexs != None else None + + def convert_semantic_feature(self, backbone_features): + backbone_features = backbone_features.permute((0,2,3,1)) + + for i, blk in enumerate(self.contras_modules): + backbone_features = blk(backbone_features) + + contras_features = (backbone_features.permute(0, 3, 1, 2)) + return contras_features + + + def find_indices_not_in_A(self, A, B): + set_A = set(A) + result_indices = [] + for index, element in enumerate(B): + if element not in set_A: + result_indices.append(index) + return result_indices + + + def forward(self, x: torch.Tensor, test_mode=False, input_wavelength=None, GSD=None) -> torch.Tensor: + + """ + Args: + x (tensor): input image with [B, C, H, W]. + test_mode (bool): If true, all the input channels would be used. + If false, we would randomly select 40 channels for each iteration + input_wavelength: list, storing wavelengths for each hyperspectral channel + GSD: ground sampling distance (m/pixel). list, such as [1.0] or tensor, such as torch.tensor([1.0]) + + Returns: multi-stage backbone features + """ + + + is_hy = False + is_mu = False + + if x.shape[1] < 20: + is_mu = True + else: + is_hy = True + + if input_wavelength != None and is_hy: + input_wavelengths_hy = input_wavelength + self.Band_feature_indices_hy, self.unmatch_indices_hy, self.point_bank_indices_hy = find_corresponding_indices(input_wavelengths_hy, spectral_wavelength,self.nm_dis) + self.weight_bank_data_indices_hy, _, self.weight_bank_indices_hy = find_corresponding_indices(input_wavelengths_hy, weight_bank_wavelength,self.nm_dis) + elif input_wavelength != None and is_mu: + input_wavelengths_mu = input_wavelength + self.Band_feature_indices_mu, self.unmatch_indices_mu, self.point_bank_indices_mu = find_corresponding_indices(input_wavelengths_mu, spectral_wavelength,self.nm_dis) + + if is_hy: + if not test_mode: + random_indices = generate_random_indices(len(self.weight_bank_data_indices_hy)-1, 40) + random_indices.sort() + indices = [self.Band_feature_indices_hy, self.point_bank_indices_hy, np.array(self.weight_bank_data_indices_hy)[random_indices].tolist(), np.array(self.weight_bank_indices_hy)[random_indices].tolist()] + else: + indices = [self.Band_feature_indices_hy, self.point_bank_indices_hy, self.weight_bank_data_indices_hy, self.weight_bank_indices_hy] + block_indices = self.find_indices_not_in_A(indices[0], indices[2]) + indices[2] = np.array(indices[2])[block_indices].tolist() + indices[3] = np.array(indices[3])[block_indices].tolist() + self.last_indices = indices + elif is_mu: + indices = [self.Band_feature_indices_mu, self.point_bank_indices_mu, [], []] + self.last_indices = indices + + if GSD == None: + GSD = [1.0] + if not torch.is_tensor(GSD): + GSD = torch.tensor(GSD) + + point_feature = F.conv2d( + x[:,indices[0],:,:], + weight=self.point_spectral_weight_bank_w[:,indices[1],:,:], + bias=self.point_spectral_weight_bank_b, + stride=(self.patch_size, self.patch_size), + padding=(0,0) + ) + + if len(indices[2]) > 0: + block_feature = F.conv2d( + x[:,indices[2],:,:], + weight=self.block_spectral_weight_bank_w[:,indices[3],:,:], + bias=self.block_spectral_weight_bank_b, + stride=(self.patch_size, self.patch_size), + ) + + if len(indices[2]) > 0: + x_feature = point_feature + block_feature + else: + x_feature = point_feature + + scale_aware_pos_embed = get_2d_sincos_pos_embed_with_resolution(self.embed_dim, int(self.img_size/self.patch_size), GSD, device=x.device) + scale_aware_pos_embed = self.pos_embed_mlp(scale_aware_pos_embed) + scale_aware_pos_embed = scale_aware_pos_embed.reshape((x.shape[0], int(self.img_size/self.patch_size), int(self.img_size/self.patch_size), self.embed_dim)) + + x_feature = x_feature.permute((0,2,3,1)) + x_feature = x_feature + scale_aware_pos_embed + + self.multi_stage_features = [] + + multi_scale_merge_index = 0 + for i, blk in enumerate(self.blocks): + if self.patch_size <= 8: + x_feature = torch.utils.checkpoint.checkpoint(blk, x_feature, use_reentrant=True) + else: + x_feature = blk(x_feature) + + if self.merge_indexs != None: + if i in [self.merge_indexs[0], self.global_attn_indexes[0], self.global_attn_indexes[2]]: + self.multi_stage_features.append(x_feature.permute(0, 3, 1, 2)) + + if i in self.merge_indexs: + x_feature = self.multi_scale_convs[multi_scale_merge_index](x_feature) + multi_scale_merge_index += 1 + elif i in self.global_attn_indexes: + self.multi_stage_features.append(x_feature.permute(0, 3, 1, 2)) + + x_feature = self.neck(x_feature.permute(0, 3, 1, 2)) + self.multi_stage_features.append(x_feature) + + return self.multi_stage_features + + +def to_2tuple(x): + if isinstance(x, container_abcs.Iterable): + return x + return tuple(repeat(x, 2)) + + +def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.): + + """Fills the input Tensor with values drawn from a truncated + normal distribution. The values are effectively drawn from the + normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)` + with values outside :math:`[a, b]` redrawn until they are within + the bounds. The method used for generating the random values works + best when :math:`a \leq \text{mean} \leq b`. + Args: + tensor: an n-dimensional `torch.Tensor` + mean: the mean of the normal distribution + std: the standard deviation of the normal distribution + a: the minimum cutoff value + b: the maximum cutoff value + Examples: + >>> w = torch.empty(3, 5) + >>> nn.init.trunc_normal_(w) + """ + return _no_grad_trunc_normal_(tensor, mean, std, a, b) + + +def _no_grad_trunc_normal_(tensor, mean, std, a, b): + # Cut & paste from PyTorch official master until it's in a few official releases - RW + # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf + def norm_cdf(x): + # Computes standard normal cumulative distribution function + return (1. + math.erf(x / math.sqrt(2.))) / 2. + + if (mean < a - 2 * std) or (mean > b + 2 * std): + warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. " + "The distribution of values may be incorrect.", + stacklevel=2) + + with torch.no_grad(): + # Values are generated by using a truncated uniform distribution and + # then using the inverse CDF for the normal distribution. + # Get upper and lower cdf values + l = norm_cdf((a - mean) / std) + u = norm_cdf((b - mean) / std) + + # Uniformly fill tensor with values from [l, u], then translate to + # [2l-1, 2u-1]. + tensor.uniform_(2 * l - 1, 2 * u - 1) + + # Use inverse cdf transform for normal distribution to get truncated + # standard normal + tensor.erfinv_() + + # Transform to proper mean, std + tensor.mul_(std * math.sqrt(2.)) + tensor.add_(mean) + + +class Block(nn.Module): + """Transformer blocks with support of window attention and residual propagation blocks""" + + def __init__( + self, + dim: int, + num_heads: int, + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + norm_layer: Type[nn.Module] = nn.LayerNorm, + act_layer: Type[nn.Module] = nn.GELU, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + window_size: int = 0, + input_size: Optional[Tuple[int, int]] = None, + ) -> None: + """ + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads in each ViT block. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool): If True, add a learnable bias to query, key, value. + norm_layer (nn.Module): Normalization layer. + act_layer (nn.Module): Activation layer. + use_rel_pos (bool): If True, add relative positional embeddings to the attention map. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + window_size (int): Window size for window attention blocks. If it equals 0, then + use global attention. + input_size (tuple(int, int) or None): Input resolution for calculating the relative + positional parameter size. + """ + super().__init__() + self.norm1 = norm_layer(dim) + self.attn = Attention( + dim, + num_heads=num_heads, + qkv_bias=qkv_bias, + use_rel_pos=use_rel_pos, + rel_pos_zero_init=rel_pos_zero_init, + input_size=input_size if window_size == 0 else (window_size, window_size), + ) + + self.norm2 = norm_layer(dim) + self.mlp = MLPBlock(embedding_dim=dim, mlp_dim=int(dim * mlp_ratio), act=act_layer) + + self.window_size = window_size + + def forward(self, x: torch.Tensor) -> torch.Tensor: + shortcut = x + x = self.norm1(x) + # Window partition + if self.window_size > 0: + H, W = x.shape[1], x.shape[2] + x, pad_hw = window_partition(x, self.window_size) + + x = self.attn(x) + # Reverse window partition + if self.window_size > 0: + x = window_unpartition(x, self.window_size, pad_hw, (H, W)) + + x = shortcut + x + x = x + self.mlp(self.norm2(x)) + + return x + + +class Attention(nn.Module): + """Multi-head Attention block with relative position embeddings.""" + + def __init__( + self, + dim: int, + num_heads: int = 8, + qkv_bias: bool = True, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + input_size: Optional[Tuple[int, int]] = None, + ) -> None: + """ + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads. + qkv_bias (bool): If True, add a learnable bias to query, key, value. + rel_pos (bool): If True, add relative positional embeddings to the attention map. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + input_size (tuple(int, int) or None): Input resolution for calculating the relative + positional parameter size. + """ + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = head_dim**-0.5 + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.proj = nn.Linear(dim, dim) + + self.use_rel_pos = use_rel_pos + if self.use_rel_pos: + assert ( + input_size is not None + ), "Input size must be provided if using relative positional encoding." + # initialize relative positional embeddings + self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim)) + self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + B, H, W, _ = x.shape + # qkv with shape (3, B, nHead, H * W, C) + qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) + # q, k, v with shape (B * nHead, H * W, C) + q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0) + + attn = (q * self.scale) @ k.transpose(-2, -1) + + if self.use_rel_pos: + attn = add_decomposed_rel_pos(attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W)) + + attn = attn.softmax(dim=-1) + x = (attn @ v).view(B, self.num_heads, H, W, -1).permute(0, 2, 3, 1, 4).reshape(B, H, W, -1) + x = self.proj(x) + + return x + + +def window_partition(x: torch.Tensor, window_size: int) -> Tuple[torch.Tensor, Tuple[int, int]]: + """ + Partition into non-overlapping windows with padding if needed. + Args: + x (tensor): input tokens with [B, H, W, C]. + window_size (int): window size. + + Returns: + windows: windows after partition with [B * num_windows, window_size, window_size, C]. + (Hp, Wp): padded height and width before partition + """ + B, H, W, C = x.shape + + pad_h = (window_size - H % window_size) % window_size + pad_w = (window_size - W % window_size) % window_size + if pad_h > 0 or pad_w > 0: + x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h)) + Hp, Wp = H + pad_h, W + pad_w + + x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C) + windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) + return windows, (Hp, Wp) + + +def window_unpartition( + windows: torch.Tensor, window_size: int, pad_hw: Tuple[int, int], hw: Tuple[int, int] +) -> torch.Tensor: + """ + Window unpartition into original sequences and removing padding. + Args: + windows (tensor): input tokens with [B * num_windows, window_size, window_size, C]. + window_size (int): window size. + pad_hw (Tuple): padded height and width (Hp, Wp). + hw (Tuple): original height and width (H, W) before padding. + + Returns: + x: unpartitioned sequences with [B, H, W, C]. + """ + Hp, Wp = pad_hw + H, W = hw + B = windows.shape[0] // (Hp * Wp // window_size // window_size) + x = windows.view(B, Hp // window_size, Wp // window_size, window_size, window_size, -1) + x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1) + + if Hp > H or Wp > W: + x = x[:, :H, :W, :].contiguous() + return x + + +def get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor: + """ + Get relative positional embeddings according to the relative positions of + query and key sizes. + Args: + q_size (int): size of query q. + k_size (int): size of key k. + rel_pos (Tensor): relative position embeddings (L, C). + + Returns: + Extracted positional embeddings according to relative positions. + """ + max_rel_dist = int(2 * max(q_size, k_size) - 1) + # Interpolate rel pos if needed. + if rel_pos.shape[0] != max_rel_dist: + # Interpolate rel pos. + rel_pos_resized = F.interpolate( + rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1), + size=max_rel_dist, + mode="linear", + ) + rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0) + else: + rel_pos_resized = rel_pos + + # Scale the coords with short length if shapes for q and k are different. + q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0) + k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0) + relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0) + + return rel_pos_resized[relative_coords.long()] + + +def add_decomposed_rel_pos( + attn: torch.Tensor, + q: torch.Tensor, + rel_pos_h: torch.Tensor, + rel_pos_w: torch.Tensor, + q_size: Tuple[int, int], + k_size: Tuple[int, int], +) -> torch.Tensor: + """ + Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`. + https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py # noqa B950 + Args: + attn (Tensor): attention map. + q (Tensor): query q in the attention layer with shape (B, q_h * q_w, C). + rel_pos_h (Tensor): relative position embeddings (Lh, C) for height axis. + rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis. + q_size (Tuple): spatial sequence size of query q with (q_h, q_w). + k_size (Tuple): spatial sequence size of key k with (k_h, k_w). + + Returns: + attn (Tensor): attention map with added relative positional embeddings. + """ + q_h, q_w = q_size + k_h, k_w = k_size + Rh = get_rel_pos(q_h, k_h, rel_pos_h) + Rw = get_rel_pos(q_w, k_w, rel_pos_w) + + B, _, dim = q.shape + r_q = q.reshape(B, q_h, q_w, dim) + rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh) + rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw) + + attn = ( + attn.view(B, q_h, q_w, k_h, k_w) + rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :] + ).view(B, q_h * q_w, k_h * k_w) + + return attn + + +class PatchMerging(nn.Module): + r""" Patch Merging Layer. + + Args: + input_resolution (tuple[int]): Resolution of input feature. + dim (int): Number of input channels. + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + """ + + def __init__(self, dim, norm_layer=nn.LayerNorm): + super().__init__() + self.dim = dim + self.reduction = nn.Linear(4 * dim, dim, bias=False) + self.norm = norm_layer(4 * dim) + + def forward(self, x): + """ + x: B, H*W, C + """ + B, H, W, C = x.shape + assert H % 2 == 0 and W % 2 == 0, f"x size ({H}*{W}) are not even." + + x = x.view(B, H, W, C) + + x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C + x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C + x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C + x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C + x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C + x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C + + x = self.norm(x) + x = self.reduction(x) + x = x.view(B, H // 2, W // 2, C) + + return x + + def extra_repr(self) -> str: + return f"input_resolution={self.input_resolution}, dim={self.dim}" + + def flops(self): + H, W = self.input_resolution + flops = H * W * self.dim + flops += (H // 2) * (W // 2) * 4 * self.dim * 2 * self.dim + return flops + +class PatchEmbed(nn.Module): + """ + Image to Patch Embedding. + """ + + def __init__( + self, + kernel_size: Tuple[int, int] = (16, 16), + stride: Tuple[int, int] = (16, 16), + padding: Tuple[int, int] = (0, 0), + in_chans: int = 3, + embed_dim: int = 768, + ) -> None: + """ + Args: + kernel_size (Tuple): kernel size of the projection layer. + stride (Tuple): stride of the projection layer. + padding (Tuple): padding size of the projection layer. + in_chans (int): Number of input image channels. + embed_dim (int): Patch embedding dimension. + """ + super().__init__() + + self.proj = nn.Conv2d( + in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.proj(x) + # B C H W -> B H W C + x = x.permute(0, 2, 3, 1) + return x diff --git a/HyperVision/modeling/mask_decoder.py b/HyperVision/modeling/mask_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..16b57c42dc817c601e305281174445acc56268af --- /dev/null +++ b/HyperVision/modeling/mask_decoder.py @@ -0,0 +1,180 @@ +import torch +from torch import nn +from torch.nn import functional as F +from typing import List, Tuple, Type +from .common import LayerNorm2d + + +class MaskDecoder(nn.Module): + def __init__( + self, + *, + transformer_dim: int, + transformer: nn.Module, + num_multimask_outputs: int = 3, + activation: Type[nn.Module] = nn.GELU, + iou_head_depth: int = 3, + iou_head_hidden_dim: int = 256, + class_number = -1, + ) -> None: + """ + Predicts masks given an image and prompt embeddings, using a + transformer architecture. + + Arguments: + transformer_dim (int): the channel dimension of the transformer + transformer (nn.Module): the transformer used to predict masks + num_multimask_outputs (int): the number of masks to predict + when disambiguating masks + activation (nn.Module): the type of activation to use when + upscaling masks + iou_head_depth (int): the depth of the MLP used to predict + mask quality + iou_head_hidden_dim (int): the hidden dimension of the MLP + used to predict mask quality + class_number: the number of semantic classes for decoder-only tuning + """ + super().__init__() + self.transformer_dim = transformer_dim + self.transformer = transformer + + self.num_multimask_outputs = num_multimask_outputs + + self.iou_token = nn.Embedding(1, transformer_dim) + self.num_mask_tokens = num_multimask_outputs + 1 + self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim) + self.class_number = class_number + + self.output_upscaling = nn.Sequential( + nn.ConvTranspose2d(transformer_dim, transformer_dim // 4, kernel_size=2, stride=2), + LayerNorm2d(transformer_dim // 4), + activation(), + nn.ConvTranspose2d(transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2), + activation(), + ) + self.output_hypernetworks_mlps = nn.ModuleList( + [ + MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3) + for i in range(self.num_mask_tokens) + ] + ) + + self.iou_prediction_head = MLP( + transformer_dim, iou_head_hidden_dim, self.num_mask_tokens, iou_head_depth + ) + + if self.class_number != -1: + self.class_seg_head = nn.Conv2d(transformer_dim // 8, self.class_number, 3, 1, 1) + + def forward( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + multimask_output: bool, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Predict masks given image and prompt embeddings. + + Arguments: + image_embeddings (torch.Tensor): the embeddings from the image encoder + image_pe (torch.Tensor): positional encoding with the shape of image_embeddings + sparse_prompt_embeddings (torch.Tensor): the embeddings of the points and boxes + dense_prompt_embeddings (torch.Tensor): the embeddings of the mask inputs + multimask_output (bool): Whether to return multiple masks or a single + mask. + + Returns: + torch.Tensor: batched predicted masks + torch.Tensor: batched predictions of mask quality + """ + masks, iou_pred = self.predict_masks( + image_embeddings=image_embeddings, + image_pe=image_pe, + sparse_prompt_embeddings=sparse_prompt_embeddings, + dense_prompt_embeddings=dense_prompt_embeddings, + ) + + # Select the correct mask or masks for output + + if self.class_number != -1: + return masks + + if multimask_output: + mask_slice = slice(1, None) + else: + mask_slice = slice(0, 1) + masks = masks[:, mask_slice, :, :] + iou_pred = iou_pred[:, mask_slice] + + # Prepare output + return masks, iou_pred + + def predict_masks( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Predicts masks. See 'forward' for more details.""" + # Concatenate output tokens + output_tokens = torch.cat([self.iou_token.weight, self.mask_tokens.weight], dim=0) + output_tokens = output_tokens.unsqueeze(0).expand(sparse_prompt_embeddings.size(0), -1, -1) + tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1) + + src = torch.repeat_interleave(image_embeddings, 1, dim=0) + + src = src + dense_prompt_embeddings + pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0) + b, c, h, w = src.shape + + # Run the transformer + hs, src = self.transformer(src, pos_src, tokens) + iou_token_out = hs[:, 0, :] + mask_tokens_out = hs[:, 1 : (1 + self.num_mask_tokens), :] + + # Upscale mask embeddings and predict masks using the mask tokens + src = src.transpose(1, 2).view(b, c, h, w) + self.upscaled_embedding = self.output_upscaling(src) + b, c, h, w = self.upscaled_embedding.shape + if self.class_number == -1: + hyper_in_list: List[torch.Tensor] = [] + for i in range(self.num_mask_tokens): + hyper_in_list.append(self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :])) + hyper_in = torch.stack(hyper_in_list, dim=1) + masks = (hyper_in @ self.upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w) + else: + masks = self.class_seg_head(self.upscaled_embedding) + + # Generate mask quality predictions + iou_pred = self.iou_prediction_head(iou_token_out) + return masks, iou_pred + + +# Lightly adapted from +# https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py # noqa +class MLP(nn.Module): + def __init__( + self, + input_dim: int, + hidden_dim: int, + output_dim: int, + num_layers: int, + sigmoid_output: bool = False, + ) -> None: + super().__init__() + self.num_layers = num_layers + h = [hidden_dim] * (num_layers - 1) + self.layers = nn.ModuleList( + nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]) + ) + self.sigmoid_output = sigmoid_output + + def forward(self, x): + for i, layer in enumerate(self.layers): + x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x) + if self.sigmoid_output: + x = F.sigmoid(x) + return x diff --git a/HyperVision/modeling/prompt_encoder.py b/HyperVision/modeling/prompt_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..f02b3c46ccf26655512a3bb9922ded6c0ca45423 --- /dev/null +++ b/HyperVision/modeling/prompt_encoder.py @@ -0,0 +1,214 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np +import torch +from torch import nn + +from typing import Any, Optional, Tuple, Type +from .mask_decoder import MLP +from .common import LayerNorm2d + + +class PromptEncoder(nn.Module): + def __init__( + self, + embed_dim: int, + image_embedding_size: Tuple[int, int], + input_image_size: Tuple[int, int], + mask_in_chans: int, + activation: Type[nn.Module] = nn.GELU, + ) -> None: + """ + Encodes prompts for input to SAM's mask decoder. + + Arguments: + embed_dim (int): The prompts' embedding dimension + image_embedding_size (tuple(int, int)): The spatial size of the + image embedding, as (H, W). + input_image_size (int): The padded size of the image as input + to the image encoder, as (H, W). + mask_in_chans (int): The number of hidden channels used for + encoding input masks. + activation (nn.Module): The activation to use when encoding + input masks. + """ + super().__init__() + self.embed_dim = embed_dim + self.input_image_size = input_image_size + self.image_embedding_size = image_embedding_size + self.pe_layer = PositionEmbeddingRandom(embed_dim // 2) + + self.num_point_embeddings: int = 4 # pos/neg point + 2 box corners + point_embeddings = [nn.Embedding(1, embed_dim) for i in range(self.num_point_embeddings)] + self.point_embeddings = nn.ModuleList(point_embeddings) + self.not_a_point_embed = nn.Embedding(1, embed_dim) + + self.mask_input_size = (4 * image_embedding_size[0], 4 * image_embedding_size[1]) + self.mask_downscaling = nn.Sequential( + nn.Conv2d(1, mask_in_chans // 4, kernel_size=2, stride=2), + LayerNorm2d(mask_in_chans // 4), + activation(), + nn.Conv2d(mask_in_chans // 4, mask_in_chans, kernel_size=2, stride=2), + LayerNorm2d(mask_in_chans), + activation(), + nn.Conv2d(mask_in_chans, embed_dim, kernel_size=1), + ) + self.no_mask_embed = nn.Embedding(1, embed_dim) + + def get_dense_pe(self) -> torch.Tensor: + """ + Returns the positional encoding used to encode point prompts, + applied to a dense set of points the shape of the image encoding. + + Returns: + torch.Tensor: Positional encoding with shape + 1x(embed_dim)x(embedding_h)x(embedding_w) + """ + return self.pe_layer(self.image_embedding_size).unsqueeze(0) + + def _embed_points( + self, + points: torch.Tensor, + labels: torch.Tensor, + pad: bool, + ) -> torch.Tensor: + """Embeds point prompts.""" + points = points + 0.5 # Shift to center of pixel + if pad: + padding_point = torch.zeros((points.shape[0], 1, 2), device=points.device) + padding_label = -torch.ones((labels.shape[0], 1), device=labels.device) + points = torch.cat([points, padding_point], dim=1) + labels = torch.cat([labels, padding_label], dim=1) + point_embedding = self.pe_layer.forward_with_coords(points, self.input_image_size) + point_embedding[labels == -1] = 0.0 + point_embedding[labels == -1] += self.not_a_point_embed.weight + point_embedding[labels == 0] += self.point_embeddings[0].weight + point_embedding[labels == 1] += self.point_embeddings[1].weight + return point_embedding + + def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor: + """Embeds box prompts.""" + boxes = boxes + 0.5 # Shift to center of pixel + coords = boxes.reshape(-1, 2, 2) + corner_embedding = self.pe_layer.forward_with_coords(coords, self.input_image_size) + corner_embedding[:, 0, :] += self.point_embeddings[2].weight + corner_embedding[:, 1, :] += self.point_embeddings[3].weight + return corner_embedding + + def _embed_masks(self, masks: torch.Tensor) -> torch.Tensor: + """Embeds mask inputs.""" + mask_embedding = self.mask_downscaling(masks) + return mask_embedding + + def _get_batch_size( + self, + points: Optional[Tuple[torch.Tensor, torch.Tensor]], + boxes: Optional[torch.Tensor], + masks: Optional[torch.Tensor], + ) -> int: + """ + Gets the batch size of the output given the batch size of the input prompts. + """ + if points is not None: + return points[0].shape[0] + elif boxes is not None: + return boxes.shape[0] + elif masks is not None: + return masks.shape[0] + else: + return 1 + + def _get_device(self) -> torch.device: + return self.point_embeddings[0].weight.device + + def forward( + self, + points: Optional[Tuple[torch.Tensor, torch.Tensor]], + boxes: Optional[torch.Tensor], + masks: Optional[torch.Tensor], + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Embeds different types of prompts, returning both sparse and dense + embeddings. + + Arguments: + points (tuple(torch.Tensor, torch.Tensor) or none): point coordinates + and labels to embed. + boxes (torch.Tensor or none): boxes to embed + masks (torch.Tensor or none): masks to embed + + Returns: + torch.Tensor: sparse embeddings for the points and boxes, with shape + BxNx(embed_dim), where N is determined by the number of input points + and boxes. + torch.Tensor: dense embeddings for the masks, in the shape + Bx(embed_dim)x(embed_H)x(embed_W) + """ + bs = self._get_batch_size(points, boxes, masks) + sparse_embeddings = torch.empty((bs, 0, self.embed_dim), device=self._get_device()) + if points is not None: + coords, labels = points + point_embeddings = self._embed_points(coords, labels, pad=(boxes is None)) + sparse_embeddings = torch.cat([sparse_embeddings, point_embeddings], dim=1) + if boxes is not None: + box_embeddings = self._embed_boxes(boxes) + sparse_embeddings = torch.cat([sparse_embeddings, box_embeddings], dim=1) + + if masks is not None: + dense_embeddings = self._embed_masks(masks) + else: + dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).expand( + bs, -1, self.image_embedding_size[0], self.image_embedding_size[1] + ) + + return sparse_embeddings, dense_embeddings + + +class PositionEmbeddingRandom(nn.Module): + """ + Positional encoding using random spatial frequencies. + """ + + def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None: + super().__init__() + if scale is None or scale <= 0.0: + scale = 1.0 + self.register_buffer( + "positional_encoding_gaussian_matrix", + scale * torch.randn((2, num_pos_feats)), + ) + + def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor: + """Positionally encode points that are normalized to [0,1].""" + # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape + coords = 2 * coords - 1 + coords = coords @ self.positional_encoding_gaussian_matrix + coords = 2 * np.pi * coords + # outputs d_1 x ... x d_n x C shape + return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1) + + def forward(self, size: Tuple[int, int]) -> torch.Tensor: + """Generate positional encoding for a grid of the specified size.""" + h, w = size + device: Any = self.positional_encoding_gaussian_matrix.device + grid = torch.ones((h, w), device=device, dtype=torch.float32) + y_embed = grid.cumsum(dim=0) - 0.5 + x_embed = grid.cumsum(dim=1) - 0.5 + y_embed = y_embed / h + x_embed = x_embed / w + + pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1)) + return pe.permute(2, 0, 1) # C x H x W + + def forward_with_coords( + self, coords_input: torch.Tensor, image_size: Tuple[int, int] + ) -> torch.Tensor: + """Positionally encode points that are not normalized to [0,1].""" + coords = coords_input.clone() + coords[:, :, 0] = coords[:, :, 0] / image_size[1] + coords[:, :, 1] = coords[:, :, 1] / image_size[0] + return self._pe_encoding(coords.to(torch.float)) # B x N x C \ No newline at end of file diff --git a/HyperVision/modeling/sam.py b/HyperVision/modeling/sam.py new file mode 100644 index 0000000000000000000000000000000000000000..48a36803071bec4100caa1d76e7504803717c868 --- /dev/null +++ b/HyperVision/modeling/sam.py @@ -0,0 +1,163 @@ +import torch +from torch import nn +from torch.nn import functional as F + +from typing import Any, Dict, List, Tuple + +from .image_encoder import ImageEncoderViT +from .mask_decoder import MaskDecoder +from .prompt_encoder import PromptEncoder + +""" +We use the meta-architecture of SAM. +""" + +class Sam(nn.Module): + mask_threshold: float = 0.0 + + def __init__( + self, + image_encoder: ImageEncoderViT, + prompt_encoder: PromptEncoder, + mask_decoder: MaskDecoder, + ) -> None: + """ + SAM predicts object masks from an image and input prompts. + + Arguments: + image_encoder (ImageEncoderViT): The backbone used to encode the + image into image embeddings that allow for efficient mask prediction. + prompt_encoder (PromptEncoder): Encodes various types of input prompts. + mask_decoder (MaskDecoder): Predicts masks from the image embeddings + and encoded prompts. + + """ + super().__init__() + self.image_encoder = image_encoder + self.prompt_encoder = prompt_encoder + self.mask_decoder = mask_decoder + + @property + def device(self) -> Any: + return self.image_encoder.point_spectral_weight_bank_w.device + + @torch.no_grad() + def forward( + self, + batched_input: List[Dict[str, Any]], + multimask_output: bool, + ) -> List[Dict[str, torch.Tensor]]: + """ + Predicts masks end-to-end from provided images and prompts. + If prompts are not known in advance, using SamPredictor is + recommended over calling the model directly. + + Arguments: + batched_input (list(dict)): A list over input images, each a + dictionary with the following keys. A prompt key can be + excluded if it is not present. + 'image': The image as a torch tensor in 3xHxW format, + already transformed for input to the model. + 'original_size': (tuple(int, int)) The original size of + the image before transformation, as (H, W). + 'point_coords': (torch.Tensor) Batched point prompts for + this image, with shape BxNx2. Already transformed to the + input frame of the model. + 'point_labels': (torch.Tensor) Batched labels for point prompts, + with shape BxN. + 'boxes': (torch.Tensor) Batched box inputs, with shape Bx4. + Already transformed to the input frame of the model. + 'mask_inputs': (torch.Tensor) Batched mask inputs to the model, + in the form Bx1xHxW. + multimask_output (bool): Whether the model should predict multiple + disambiguating masks, or return a single mask. + + Returns: + (list(dict)): A list over input images, where each element is + as dictionary with the following keys. + 'masks': (torch.Tensor) Batched binary mask predictions, + with shape BxCxHxW, where B is the number of input prompts, + C is determined by multimask_output, and (H, W) is the + original size of the image. + 'iou_predictions': (torch.Tensor) The model's predictions + of mask quality, in shape BxC. + 'low_res_logits': (torch.Tensor) Low resolution logits with + shape BxCxHxW, where H=W=256. Can be passed as mask input + to subsequent iterations of prediction. + """ + input_images = torch.stack([self.preprocess(x["image"]) for x in batched_input], dim=0) + image_embeddings = self.image_encoder(input_images) + + outputs = [] + for image_record, curr_embedding in zip(batched_input, image_embeddings): + if "point_coords" in image_record: + points = (image_record["point_coords"], image_record["point_labels"]) + else: + points = None + sparse_embeddings, dense_embeddings = self.prompt_encoder( + points=points, + boxes=image_record.get("boxes", None), + masks=image_record.get("mask_inputs", None), + ) + low_res_masks, iou_predictions = self.mask_decoder( + image_embeddings=curr_embedding.unsqueeze(0), + image_pe=self.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + ) + masks = self.postprocess_masks( + low_res_masks, + input_size=image_record["image"].shape[-2:], + original_size=image_record["original_size"], + ) + masks = masks > self.mask_threshold + outputs.append( + { + "masks": masks, + "iou_predictions": iou_predictions, + "low_res_logits": low_res_masks, + } + ) + return outputs + + def postprocess_masks( + self, + masks: torch.Tensor, + input_size: Tuple[int, ...], + original_size: Tuple[int, ...], + ) -> torch.Tensor: + """ + Remove padding and upscale masks to the original image size. + + Arguments: + masks (torch.Tensor): Batched masks from the mask_decoder, + in BxCxHxW format. + input_size (tuple(int, int)): The size of the image input to the + model, in (H, W) format. Used to remove padding. + original_size (tuple(int, int)): The original size of the image + before resizing for input to the model, in (H, W) format. + + Returns: + (torch.Tensor): Batched masks in BxCxHxW format, where (H, W) + is given by original_size. + """ + masks = F.interpolate( + masks, + (self.image_encoder.img_size, self.image_encoder.img_size), + mode="bilinear", + align_corners=False, + ) + masks = masks[..., : input_size[0], : input_size[1]] + masks = F.interpolate(masks, original_size, mode="bilinear", align_corners=False) + return masks + + def preprocess(self, x: torch.Tensor) -> torch.Tensor: + """Normalize pixel values and pad to a square input.""" + + x = x/x.max() + h, w = x.shape[-2:] + padh = self.image_encoder.img_size - h + padw = self.image_encoder.img_size - w + x = F.pad(x, (0, padw, 0, padh)) + return x \ No newline at end of file diff --git a/HyperVision/modeling/scale_aware_PE.py b/HyperVision/modeling/scale_aware_PE.py new file mode 100644 index 0000000000000000000000000000000000000000..a16f06473cee983a448966fd9c875981b99fe407 --- /dev/null +++ b/HyperVision/modeling/scale_aware_PE.py @@ -0,0 +1,65 @@ +import numpy as np +import torch + + +def get_1d_sincos_pos_embed_from_grid_torch(embed_dim, pos): + """ + embed_dim: output dimension for each position + pos: a list of positions to be encoded: size (M,) + out: (M, D) + """ + assert embed_dim % 2 == 0 + old_shape = pos + omega = torch.arange(embed_dim // 2, dtype=torch.float32, device=pos.device) + omega /= embed_dim / 2.0 + omega = 1.0 / 10000**omega # (D/2,) + + pos = pos.reshape(-1) # (M,) + out = torch.einsum("m,d->md", pos, omega) # (M, D/2), outer product + + emb_sin = torch.sin(out) # (M, D/2) + emb_cos = torch.cos(out) # (M, D/2) + + emb = torch.cat([emb_sin, emb_cos], dim=1) # (M, D) + return emb + +def get_2d_sincos_pos_embed_from_grid_torch(embed_dim, grid): + assert embed_dim % 2 == 0 + + # use half of dimensions to encode grid_h + emb_h = get_1d_sincos_pos_embed_from_grid_torch( + embed_dim // 2, grid[0] + ) # (H*W, D/2) + emb_w = get_1d_sincos_pos_embed_from_grid_torch( + embed_dim // 2, grid[1] + ) # (H*W, D/2) + + emb = torch.cat([emb_h, emb_w], dim=1) # (H*W, D) + return emb + +def get_2d_sincos_pos_embed_with_resolution( + embed_dim, grid_size, res, device="cpu" +): + """ + grid_size: int of the grid height and width + res: array of size n, representing the resolution of a pixel (say, in meters), + return: + pos_embed: [n,grid_size*grid_size, embed_dim] or [n,1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token) + """ + # res = torch.FloatTensor(res).to(device) + res = res.to(device) + grid_h = torch.arange(grid_size, dtype=torch.float32, device=device) + grid_w = torch.arange(grid_size, dtype=torch.float32, device=device) + grid = torch.meshgrid( + grid_w, grid_h, indexing="xy" + ) # here h goes first,direction reversed for numpy + grid = torch.stack(grid, dim=0) # 2 x h x w + + # grid = grid.reshape([2, 1, grid_size, grid_size]) + grid = torch.einsum("chw,n->cnhw", grid, res) # 2 x n x h x w + _, n, h, w = grid.shape + pos_embed = get_2d_sincos_pos_embed_from_grid_torch( + embed_dim, grid + ) # # (nxH*W, D/2) + pos_embed = pos_embed.reshape(n, h*w, embed_dim) + return pos_embed diff --git a/HyperVision/modeling/transformer.py b/HyperVision/modeling/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..845f088a3142c91958131ebdb2e0f24062526807 --- /dev/null +++ b/HyperVision/modeling/transformer.py @@ -0,0 +1,234 @@ +import torch +from torch import Tensor, nn + +import math +from typing import Tuple, Type + +from .common import MLPBlock + + +class TwoWayTransformer(nn.Module): + def __init__( + self, + depth: int, + embedding_dim: int, + num_heads: int, + mlp_dim: int, + activation: Type[nn.Module] = nn.ReLU, + attention_downsample_rate: int = 2, + ) -> None: + """ + A transformer decoder that attends to an input image using + queries whose positional embedding is supplied. + + Args: + depth (int): number of layers in the transformer + embedding_dim (int): the channel dimension for the input embeddings + num_heads (int): the number of heads for multihead attention. Must + divide embedding_dim + mlp_dim (int): the channel dimension internal to the MLP block + activation (nn.Module): the activation to use in the MLP block + """ + super().__init__() + self.depth = depth + self.embedding_dim = embedding_dim + self.num_heads = num_heads + self.mlp_dim = mlp_dim + self.layers = nn.ModuleList() + + for i in range(depth): + self.layers.append( + TwoWayAttentionBlock( + embedding_dim=embedding_dim, + num_heads=num_heads, + mlp_dim=mlp_dim, + activation=activation, + attention_downsample_rate=attention_downsample_rate, + skip_first_layer_pe=(i == 0), + ) + ) + + self.final_attn_token_to_image = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + self.norm_final_attn = nn.LayerNorm(embedding_dim) + + def forward( + self, + image_embedding: Tensor, + image_pe: Tensor, + point_embedding: Tensor, + ) -> Tuple[Tensor, Tensor]: + """ + Args: + image_embedding (torch.Tensor): image to attend to. Should be shape + B x embedding_dim x h x w for any h and w. + image_pe (torch.Tensor): the positional encoding to add to the image. Must + have the same shape as image_embedding. + point_embedding (torch.Tensor): the embedding to add to the query points. + Must have shape B x N_points x embedding_dim for any N_points. + + Returns: + torch.Tensor: the processed point_embedding + torch.Tensor: the processed image_embedding + """ + # BxCxHxW -> BxHWxC == B x N_image_tokens x C + bs, c, h, w = image_embedding.shape + image_embedding = image_embedding.flatten(2).permute(0, 2, 1) + image_pe = image_pe.flatten(2).permute(0, 2, 1) + + # Prepare queries + queries = point_embedding + keys = image_embedding + + # Apply transformer blocks and final layernorm + for layer in self.layers: + queries, keys = layer( + queries=queries, + keys=keys, + query_pe=point_embedding, + key_pe=image_pe, + ) + + # Apply the final attention layer from the points to the image + q = queries + point_embedding + k = keys + image_pe + attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys) + queries = queries + attn_out + queries = self.norm_final_attn(queries) + + return queries, keys + + +class TwoWayAttentionBlock(nn.Module): + def __init__( + self, + embedding_dim: int, + num_heads: int, + mlp_dim: int = 2048, + activation: Type[nn.Module] = nn.ReLU, + attention_downsample_rate: int = 2, + skip_first_layer_pe: bool = False, + ) -> None: + """ + A transformer block with four layers: (1) self-attention of sparse + inputs, (2) cross attention of sparse inputs to dense inputs, (3) mlp + block on sparse inputs, and (4) cross attention of dense inputs to sparse + inputs. + + Arguments: + embedding_dim (int): the channel dimension of the embeddings + num_heads (int): the number of heads in the attention layers + mlp_dim (int): the hidden dimension of the mlp block + activation (nn.Module): the activation of the mlp block + skip_first_layer_pe (bool): skip the PE on the first layer + """ + super().__init__() + self.self_attn = Attention(embedding_dim, num_heads) + self.norm1 = nn.LayerNorm(embedding_dim) + + self.cross_attn_token_to_image = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + self.norm2 = nn.LayerNorm(embedding_dim) + + self.mlp = MLPBlock(embedding_dim, mlp_dim, activation) + self.norm3 = nn.LayerNorm(embedding_dim) + + self.norm4 = nn.LayerNorm(embedding_dim) + self.cross_attn_image_to_token = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + + self.skip_first_layer_pe = skip_first_layer_pe + + def forward( + self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor + ) -> Tuple[Tensor, Tensor]: + # Self attention block + if self.skip_first_layer_pe: + queries = self.self_attn(q=queries, k=queries, v=queries) + else: + q = queries + query_pe + attn_out = self.self_attn(q=q, k=q, v=queries) + queries = queries + attn_out + queries = self.norm1(queries) + + # Cross attention block, tokens attending to image embedding + q = queries + query_pe + k = keys + key_pe + attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys) + queries = queries + attn_out + queries = self.norm2(queries) + + # MLP block + mlp_out = self.mlp(queries) + queries = queries + mlp_out + queries = self.norm3(queries) + + # Cross attention block, image embedding attending to tokens + q = queries + query_pe + k = keys + key_pe + attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries) + keys = keys + attn_out + keys = self.norm4(keys) + + return queries, keys + + +class Attention(nn.Module): + """ + An attention layer that allows for downscaling the size of the embedding + after projection to queries, keys, and values. + """ + + def __init__( + self, + embedding_dim: int, + num_heads: int, + downsample_rate: int = 1, + ) -> None: + super().__init__() + self.embedding_dim = embedding_dim + self.internal_dim = embedding_dim // downsample_rate + self.num_heads = num_heads + assert self.internal_dim % num_heads == 0, "num_heads must divide embedding_dim." + + self.q_proj = nn.Linear(embedding_dim, self.internal_dim) + self.k_proj = nn.Linear(embedding_dim, self.internal_dim) + self.v_proj = nn.Linear(embedding_dim, self.internal_dim) + self.out_proj = nn.Linear(self.internal_dim, embedding_dim) + + def _separate_heads(self, x: Tensor, num_heads: int) -> Tensor: + b, n, c = x.shape + x = x.reshape(b, n, num_heads, c // num_heads) + return x.transpose(1, 2) # B x N_heads x N_tokens x C_per_head + + def _recombine_heads(self, x: Tensor) -> Tensor: + b, n_heads, n_tokens, c_per_head = x.shape + x = x.transpose(1, 2) + return x.reshape(b, n_tokens, n_heads * c_per_head) # B x N_tokens x C + + def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor: + # Input projections + q = self.q_proj(q) + k = self.k_proj(k) + v = self.v_proj(v) + + # Separate into heads + q = self._separate_heads(q, self.num_heads) + k = self._separate_heads(k, self.num_heads) + v = self._separate_heads(v, self.num_heads) + + # Attention + _, _, _, c_per_head = q.shape + attn = q @ k.permute(0, 1, 3, 2) # B x N_heads x N_tokens x N_tokens + attn = attn / math.sqrt(c_per_head) + attn = torch.softmax(attn, dim=-1) + + # Get output + out = attn @ v + out = self._recombine_heads(out) + out = self.out_proj(out) + + return out \ No newline at end of file diff --git a/HyperVision/predictor.py b/HyperVision/predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..2cbd6a2781f57395aa10ab8c015d0dcfe5fe1c5a --- /dev/null +++ b/HyperVision/predictor.py @@ -0,0 +1,310 @@ +import numpy as np +import torch + +from HyperVision.modeling import Sam + +from typing import Optional, Tuple + +from HyperVision.utils.transforms import ResizeLongestSide + + +class HyperVision_Predictor: + def __init__( + self, + sam_model: Sam, + ) -> None: + """ + Uses SAM to calculate the image embedding for an image, and then + allow repeated, efficient mask prediction given prompts. + + Arguments: + sam_model (Sam): The model to use for mask prediction. + """ + super().__init__() + self.model = sam_model + self.transform = ResizeLongestSide(sam_model.image_encoder.img_size) + self.reset_image() + + def set_image( + self, + image: np.ndarray, + #image_format: str = "RGB", + test_mode = False, + spectral_lengths = None, + GSD = None + ) -> None: + """ + Calculates the image embeddings for the provided image, allowing + masks to be predicted with the 'predict' method. + + Arguments: + image (np.ndarray): The image for calculating masks. Expects an + image in HWC uint8 format, with pixel values in [0, 255]. + image_format (str): The color format of the image, in ['RGB', 'BGR']. + """ + + if not torch.is_tensor(image): + image = torch.as_tensor(image, device=self.device).permute((2,0,1)).unsqueeze(0).float() + input_image = self.transform.apply_image_torch(image.float()) + input_image = input_image.to(self.device) + self.set_torch_image(input_image, image.shape[-2:], test_mode, spectral_lengths,GSD=GSD) + + + def set_torch_image( + self, + transformed_image: torch.Tensor, + original_image_size: Tuple[int, ...], + test_mode=False, + spectral_lengths=None, + GSD=None, + ) -> None: + """ + Calculates the image embeddings for the provided image, allowing + masks to be predicted with the 'predict' method. Expects the input + image to be already transformed to the format expected by the model. + + Arguments: + transformed_image (torch.Tensor): The input image, with shape + 1x3xHxW, which has been transformed with ResizeLongestSide. + original_image_size (tuple(int, int)): The size of the image + before transformation, in (H, W) format. + """ + # assert ( + # len(transformed_image.shape) == 4 + # and transformed_image.shape[1] == 3 + # and max(*transformed_image.shape[2:]) == self.model.image_encoder.img_size + # ), f"set_torch_image input must be BCHW with long side {self.model.image_encoder.img_size}." + self.reset_image() + + self.original_size = original_image_size + self.input_size = tuple(transformed_image.shape[-2:]) + input_image = self.model.preprocess(transformed_image) + self.multi_scale_features= self.model.image_encoder(input_image, test_mode, spectral_lengths, GSD) + self.features = self.multi_scale_features[-1] + self.is_image_set = True + + + def set_image2( + self, + image: np.ndarray, + #image_format: str = "RGB", + test_mode = False, + spectral_lengths = None, + GSD = None, + ) -> None: + """ + Calculates the image embeddings for the provided image, allowing + masks to be predicted with the 'predict' method. + + Arguments: + image (np.ndarray): The image for calculating masks. Expects an + image in HWC uint8 format, with pixel values in [0, 255]. + image_format (str): The color format of the image, in ['RGB', 'BGR']. + """ + + if not torch.is_tensor(image): + image = torch.as_tensor(image, device=self.device).permute((2,0,1)).unsqueeze(0).float() + input_image = self.transform.apply_image_torch(image.float()) + input_image = input_image.to(self.device) + self.set_torch_image2(input_image, image.shape[-2:], test_mode, spectral_lengths, GSD=GSD) + + + def set_torch_image2( + self, + transformed_image: torch.Tensor, + original_image_size: Tuple[int, ...], + test_mode=False, + spectral_lengths=None, + GSD=None + ) -> None: + input_image = self.model.preprocess(transformed_image) + self.features2 = self.model.image_encoder(input_image, test_mode, spectral_lengths, GSD)[-1] + + + def predict( + self, + point_coords: Optional[np.ndarray] = None, + point_labels: Optional[np.ndarray] = None, + box: Optional[np.ndarray] = None, + mask_input: Optional[np.ndarray] = None, + multimask_output: bool = True, + return_logits: bool = False, + ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """ + Predict masks for the given input prompts, using the currently set image. + + Arguments: + point_coords (np.ndarray or None): A Nx2 array of point prompts to the + model. Each point is in (X,Y) in pixels. + point_labels (np.ndarray or None): A length N array of labels for the + point prompts. 1 indicates a foreground point and 0 indicates a + background point. + box (np.ndarray or None): A length 4 array given a box prompt to the + model, in XYXY format. + mask_input (np.ndarray): A low resolution mask input to the model, typically + coming from a previous prediction iteration. Has form 1xHxW, where + for SAM, H=W=256. + multimask_output (bool): If true, the model will return three masks. + For ambiguous input prompts (such as a single click), this will often + produce better masks than a single prediction. If only a single + mask is needed, the model's predicted quality score can be used + to select the best mask. For non-ambiguous prompts, such as multiple + input prompts, multimask_output=False can give better results. + return_logits (bool): If true, returns un-thresholded masks logits + instead of a binary mask. + + Returns: + (np.ndarray): The output masks in CxHxW format, where C is the + number of masks, and (H, W) is the original image size. + (np.ndarray): An array of length C containing the model's + predictions for the quality of each mask. + (np.ndarray): An array of shape CxHxW, where C is the number + of masks and H=W=256. These low resolution logits can be passed to + a subsequent iteration as mask input. + """ + if not self.is_image_set: + raise RuntimeError("An image must be set with .set_image(...) before mask prediction.") + + # Transform input prompts + coords_torch, labels_torch, box_torch, mask_input_torch = None, None, None, None + if point_coords is not None: + assert ( + point_labels is not None + ), "point_labels must be supplied if point_coords is supplied." + point_coords = self.transform.apply_coords(point_coords, self.original_size) + coords_torch = torch.as_tensor(point_coords, dtype=torch.float, device=self.device) + labels_torch = torch.as_tensor(point_labels, dtype=torch.int, device=self.device) + if len(coords_torch.shape) != 3: # + coords_torch, labels_torch = coords_torch[None, :, :], labels_torch[None, :] + if box is not None: + box = self.transform.apply_boxes(box, self.original_size) + box_torch = torch.as_tensor(box, dtype=torch.float, device=self.device) + if len(box_torch.shape) != 2: + box_torch = box_torch[None, :] + if mask_input is not None: + mask_input_torch = torch.as_tensor(mask_input, dtype=torch.float, device=self.device) + mask_input_torch = mask_input_torch[None, :, :, :] + + masks, iou_predictions, low_res_masks = self.predict_torch( + coords_torch, + labels_torch, + box_torch, + mask_input_torch, + multimask_output, + return_logits=return_logits, + ) + # masks_torch = masks[0] # 1 3 H W + # iou_predictions_torch = iou_predictions[0] + # low_res_masks_torch = low_res_masks[0] + + masks_torch = masks # 2 3 H W + iou_predictions_torch = iou_predictions + low_res_masks_torch = low_res_masks + return masks_torch, iou_predictions_torch, low_res_masks_torch + # masks_np = masks[0].detach().cpu().numpy() + # iou_predictions_np = iou_predictions[0].detach().cpu().numpy() + # low_res_masks_np = low_res_masks[0].detach().cpu().numpy() + # return masks_np, iou_predictions_np, low_res_masks_np + + #@torch.no_grad() + def predict_torch( + self, + point_coords: Optional[torch.Tensor], + point_labels: Optional[torch.Tensor], + boxes: Optional[torch.Tensor] = None, + mask_input: Optional[torch.Tensor] = None, + multimask_output: bool = True, + return_logits: bool = False, + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Predict masks for the given input prompts, using the currently set image. + Input prompts are batched torch tensors and are expected to already be + transformed to the input frame using ResizeLongestSide. + + Arguments: + point_coords (torch.Tensor or None): A BxNx2 array of point prompts to the + model. Each point is in (X,Y) in pixels. + point_labels (torch.Tensor or None): A BxN array of labels for the + point prompts. 1 indicates a foreground point and 0 indicates a + background point. + boxes (np.ndarray or None): A Bx4 array given a box prompt to the + model, in XYXY format. + mask_input (np.ndarray): A low resolution mask input to the model, typically + coming from a previous prediction iteration. Has form Bx1xHxW, where + for SAM, H=W=256. Masks returned by a previous iteration of the + predict method do not need further transformation. + multimask_output (bool): If true, the model will return three masks. + For ambiguous input prompts (such as a single click), this will often + produce better masks than a single prediction. If only a single + mask is needed, the model's predicted quality score can be used + to select the best mask. For non-ambiguous prompts, such as multiple + input prompts, multimask_output=False can give better results. + return_logits (bool): If true, returns un-thresholded masks logits + instead of a binary mask. + + Returns: + (torch.Tensor): The output masks in BxCxHxW format, where C is the + number of masks, and (H, W) is the original image size. + (torch.Tensor): An array of shape BxC containing the model's + predictions for the quality of each mask. + (torch.Tensor): An array of shape BxCxHxW, where C is the number + of masks and H=W=256. These low res logits can be passed to + a subsequent iteration as mask input. + """ + if not self.is_image_set: + raise RuntimeError("An image must be set with .set_image(...) before mask prediction.") + + if point_coords is not None: + points = (point_coords, point_labels) + else: + points = None + + # Embed prompts + sparse_embeddings, dense_embeddings = self.model.prompt_encoder( + points=points, + boxes=boxes, + masks=mask_input, + ) + + # Predict masks + low_res_masks, iou_predictions = self.model.mask_decoder( + image_embeddings=self.features, + image_pe=self.model.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + ) + + # Upscale the masks to the original image resolution + masks = self.model.postprocess_masks(low_res_masks, self.input_size, self.original_size) + + if not return_logits: + masks = masks > self.model.mask_threshold + + return masks, iou_predictions, low_res_masks + + def get_image_embedding(self) -> torch.Tensor: + """ + Returns the image embeddings for the currently set image, with + shape 1xCxHxW, where C is the embedding dimension and (H,W) are + the embedding spatial dimension of SAM (typically C=256, H=W=64). + """ + if not self.is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) to generate an embedding." + ) + assert self.features is not None, "Features must exist if an image has been set." + return self.features + + @property + def device(self) -> torch.device: + return self.model.device + + def reset_image(self) -> None: + """Resets the currently set image.""" + self.is_image_set = False + self.features = None + self.orig_h = None + self.orig_w = None + self.input_h = None + self.input_w = None diff --git a/HyperVision/utils/__init__.py b/HyperVision/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5277f46157403e47fd830fc519144b97ef69d4ae --- /dev/null +++ b/HyperVision/utils/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. diff --git a/HyperVision/utils/__pycache__/__init__.cpython-310.pyc b/HyperVision/utils/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d05103a8d41ed810baf429366f52f5a14b1052f4 Binary files /dev/null and b/HyperVision/utils/__pycache__/__init__.cpython-310.pyc differ diff --git a/HyperVision/utils/__pycache__/__init__.cpython-311.pyc b/HyperVision/utils/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ba327805843f6aa19430daf64e630c8ea214365 Binary files /dev/null and b/HyperVision/utils/__pycache__/__init__.cpython-311.pyc differ diff --git a/HyperVision/utils/__pycache__/amg.cpython-310.pyc b/HyperVision/utils/__pycache__/amg.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..464b299537a4beb6e770a63f281f49262e537865 Binary files /dev/null and b/HyperVision/utils/__pycache__/amg.cpython-310.pyc differ diff --git a/HyperVision/utils/__pycache__/amg.cpython-311.pyc b/HyperVision/utils/__pycache__/amg.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a101d44ececa2beac215f5812e792f8097d3c4f6 Binary files /dev/null and b/HyperVision/utils/__pycache__/amg.cpython-311.pyc differ diff --git a/HyperVision/utils/__pycache__/spectral_process_utils.cpython-310.pyc b/HyperVision/utils/__pycache__/spectral_process_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..261fa83261b8319288b04f8a1137940b75475a96 Binary files /dev/null and b/HyperVision/utils/__pycache__/spectral_process_utils.cpython-310.pyc differ diff --git a/HyperVision/utils/__pycache__/spectral_process_utils.cpython-311.pyc b/HyperVision/utils/__pycache__/spectral_process_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ee76308d1ebe1bc47ffc73a1573c3cf769d887c Binary files /dev/null and b/HyperVision/utils/__pycache__/spectral_process_utils.cpython-311.pyc differ diff --git a/HyperVision/utils/__pycache__/transforms.cpython-310.pyc b/HyperVision/utils/__pycache__/transforms.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a19f9b22cd29a4ba6226c2243c4c2a6073f5b18 Binary files /dev/null and b/HyperVision/utils/__pycache__/transforms.cpython-310.pyc differ diff --git a/HyperVision/utils/__pycache__/transforms.cpython-311.pyc b/HyperVision/utils/__pycache__/transforms.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b02daff25163cfa7b56f5300e9422d364615af29 Binary files /dev/null and b/HyperVision/utils/__pycache__/transforms.cpython-311.pyc differ diff --git a/HyperVision/utils/amg.py b/HyperVision/utils/amg.py new file mode 100644 index 0000000000000000000000000000000000000000..be064071ef399fea96c673ad173689656c23534a --- /dev/null +++ b/HyperVision/utils/amg.py @@ -0,0 +1,346 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np +import torch + +import math +from copy import deepcopy +from itertools import product +from typing import Any, Dict, Generator, ItemsView, List, Tuple + + +class MaskData: + """ + A structure for storing masks and their related data in batched format. + Implements basic filtering and concatenation. + """ + + def __init__(self, **kwargs) -> None: + for v in kwargs.values(): + assert isinstance( + v, (list, np.ndarray, torch.Tensor) + ), "MaskData only supports list, numpy arrays, and torch tensors." + self._stats = dict(**kwargs) + + def __setitem__(self, key: str, item: Any) -> None: + assert isinstance( + item, (list, np.ndarray, torch.Tensor) + ), "MaskData only supports list, numpy arrays, and torch tensors." + self._stats[key] = item + + def __delitem__(self, key: str) -> None: + del self._stats[key] + + def __getitem__(self, key: str) -> Any: + return self._stats[key] + + def items(self) -> ItemsView[str, Any]: + return self._stats.items() + + def filter(self, keep: torch.Tensor) -> None: + for k, v in self._stats.items(): + if v is None: + self._stats[k] = None + elif isinstance(v, torch.Tensor): + self._stats[k] = v[torch.as_tensor(keep, device=v.device)] + elif isinstance(v, np.ndarray): + self._stats[k] = v[keep.detach().cpu().numpy()] + elif isinstance(v, list) and keep.dtype == torch.bool: + self._stats[k] = [a for i, a in enumerate(v) if keep[i]] + elif isinstance(v, list): + self._stats[k] = [v[i] for i in keep] + else: + raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.") + + def cat(self, new_stats: "MaskData") -> None: + for k, v in new_stats.items(): + if k not in self._stats or self._stats[k] is None: + self._stats[k] = deepcopy(v) + elif isinstance(v, torch.Tensor): + self._stats[k] = torch.cat([self._stats[k], v], dim=0) + elif isinstance(v, np.ndarray): + self._stats[k] = np.concatenate([self._stats[k], v], axis=0) + elif isinstance(v, list): + self._stats[k] = self._stats[k] + deepcopy(v) + else: + raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.") + + def to_numpy(self) -> None: + for k, v in self._stats.items(): + if isinstance(v, torch.Tensor): + self._stats[k] = v.detach().cpu().numpy() + + +def is_box_near_crop_edge( + boxes: torch.Tensor, crop_box: List[int], orig_box: List[int], atol: float = 20.0 +) -> torch.Tensor: + """Filter masks at the edge of a crop, but not at the edge of the original image.""" + crop_box_torch = torch.as_tensor(crop_box, dtype=torch.float, device=boxes.device) + orig_box_torch = torch.as_tensor(orig_box, dtype=torch.float, device=boxes.device) + boxes = uncrop_boxes_xyxy(boxes, crop_box).float() + near_crop_edge = torch.isclose(boxes, crop_box_torch[None, :], atol=atol, rtol=0) + near_image_edge = torch.isclose(boxes, orig_box_torch[None, :], atol=atol, rtol=0) + near_crop_edge = torch.logical_and(near_crop_edge, ~near_image_edge) + return torch.any(near_crop_edge, dim=1) + + +def box_xyxy_to_xywh(box_xyxy: torch.Tensor) -> torch.Tensor: + box_xywh = deepcopy(box_xyxy) + box_xywh[2] = box_xywh[2] - box_xywh[0] + box_xywh[3] = box_xywh[3] - box_xywh[1] + return box_xywh + + +def batch_iterator(batch_size: int, *args) -> Generator[List[Any], None, None]: + assert len(args) > 0 and all( + len(a) == len(args[0]) for a in args + ), "Batched iteration must have inputs of all the same size." + n_batches = len(args[0]) // batch_size + int(len(args[0]) % batch_size != 0) + for b in range(n_batches): + yield [arg[b * batch_size : (b + 1) * batch_size] for arg in args] + + +def mask_to_rle_pytorch(tensor: torch.Tensor) -> List[Dict[str, Any]]: + """ + Encodes masks to an uncompressed RLE, in the format expected by + pycoco tools. + """ + # Put in fortran order and flatten h,w + b, h, w = tensor.shape + tensor = tensor.permute(0, 2, 1).flatten(1) + + # Compute change indices + diff = tensor[:, 1:] ^ tensor[:, :-1] + change_indices = diff.nonzero() + + # Encode run length + out = [] + for i in range(b): + cur_idxs = change_indices[change_indices[:, 0] == i, 1] + cur_idxs = torch.cat( + [ + torch.tensor([0], dtype=cur_idxs.dtype, device=cur_idxs.device), + cur_idxs + 1, + torch.tensor([h * w], dtype=cur_idxs.dtype, device=cur_idxs.device), + ] + ) + btw_idxs = cur_idxs[1:] - cur_idxs[:-1] + counts = [] if tensor[i, 0] == 0 else [0] + counts.extend(btw_idxs.detach().cpu().tolist()) + out.append({"size": [h, w], "counts": counts}) + return out + + +def rle_to_mask(rle: Dict[str, Any]) -> np.ndarray: + """Compute a binary mask from an uncompressed RLE.""" + h, w = rle["size"] + mask = np.empty(h * w, dtype=bool) + idx = 0 + parity = False + for count in rle["counts"]: + mask[idx : idx + count] = parity + idx += count + parity ^= True + mask = mask.reshape(w, h) + return mask.transpose() # Put in C order + + +def area_from_rle(rle: Dict[str, Any]) -> int: + return sum(rle["counts"][1::2]) + + +def calculate_stability_score( + masks: torch.Tensor, mask_threshold: float, threshold_offset: float +) -> torch.Tensor: + """ + Computes the stability score for a batch of masks. The stability + score is the IoU between the binary masks obtained by thresholding + the predicted mask logits at high and low values. + """ + # One mask is always contained inside the other. + # Save memory by preventing unnecessary cast to torch.int64 + intersections = ( + (masks > (mask_threshold + threshold_offset)) + .sum(-1, dtype=torch.int16) + .sum(-1, dtype=torch.int32) + ) + unions = ( + (masks > (mask_threshold - threshold_offset)) + .sum(-1, dtype=torch.int16) + .sum(-1, dtype=torch.int32) + ) + return intersections / unions + + +def build_point_grid(n_per_side: int) -> np.ndarray: + """Generates a 2D grid of points evenly spaced in [0,1]x[0,1].""" + offset = 1 / (2 * n_per_side) + points_one_side = np.linspace(offset, 1 - offset, n_per_side) + points_x = np.tile(points_one_side[None, :], (n_per_side, 1)) + points_y = np.tile(points_one_side[:, None], (1, n_per_side)) + points = np.stack([points_x, points_y], axis=-1).reshape(-1, 2) + return points + + +def build_all_layer_point_grids( + n_per_side: int, n_layers: int, scale_per_layer: int +) -> List[np.ndarray]: + """Generates point grids for all crop layers.""" + points_by_layer = [] + for i in range(n_layers + 1): + n_points = int(n_per_side / (scale_per_layer**i)) + points_by_layer.append(build_point_grid(n_points)) + return points_by_layer + + +def generate_crop_boxes( + im_size: Tuple[int, ...], n_layers: int, overlap_ratio: float +) -> Tuple[List[List[int]], List[int]]: + """ + Generates a list of crop boxes of different sizes. Each layer + has (2**i)**2 boxes for the ith layer. + """ + crop_boxes, layer_idxs = [], [] + im_h, im_w = im_size + short_side = min(im_h, im_w) + + # Original image + crop_boxes.append([0, 0, im_w, im_h]) + layer_idxs.append(0) + + def crop_len(orig_len, n_crops, overlap): + return int(math.ceil((overlap * (n_crops - 1) + orig_len) / n_crops)) + + for i_layer in range(n_layers): + n_crops_per_side = 2 ** (i_layer + 1) + overlap = int(overlap_ratio * short_side * (2 / n_crops_per_side)) + + crop_w = crop_len(im_w, n_crops_per_side, overlap) + crop_h = crop_len(im_h, n_crops_per_side, overlap) + + crop_box_x0 = [int((crop_w - overlap) * i) for i in range(n_crops_per_side)] + crop_box_y0 = [int((crop_h - overlap) * i) for i in range(n_crops_per_side)] + + # Crops in XYWH format + for x0, y0 in product(crop_box_x0, crop_box_y0): + box = [x0, y0, min(x0 + crop_w, im_w), min(y0 + crop_h, im_h)] + crop_boxes.append(box) + layer_idxs.append(i_layer + 1) + + return crop_boxes, layer_idxs + + +def uncrop_boxes_xyxy(boxes: torch.Tensor, crop_box: List[int]) -> torch.Tensor: + x0, y0, _, _ = crop_box + offset = torch.tensor([[x0, y0, x0, y0]], device=boxes.device) + # Check if boxes has a channel dimension + if len(boxes.shape) == 3: + offset = offset.unsqueeze(1) + return boxes + offset + + +def uncrop_points(points: torch.Tensor, crop_box: List[int]) -> torch.Tensor: + x0, y0, _, _ = crop_box + offset = torch.tensor([[x0, y0]], device=points.device) + # Check if points has a channel dimension + if len(points.shape) == 3: + offset = offset.unsqueeze(1) + return points + offset + + +def uncrop_masks( + masks: torch.Tensor, crop_box: List[int], orig_h: int, orig_w: int +) -> torch.Tensor: + x0, y0, x1, y1 = crop_box + if x0 == 0 and y0 == 0 and x1 == orig_w and y1 == orig_h: + return masks + # Coordinate transform masks + pad_x, pad_y = orig_w - (x1 - x0), orig_h - (y1 - y0) + pad = (x0, pad_x - x0, y0, pad_y - y0) + return torch.nn.functional.pad(masks, pad, value=0) + + +def remove_small_regions( + mask: np.ndarray, area_thresh: float, mode: str +) -> Tuple[np.ndarray, bool]: + """ + Removes small disconnected regions and holes in a mask. Returns the + mask and an indicator of if the mask has been modified. + """ + import cv2 # type: ignore + + assert mode in ["holes", "islands"] + correct_holes = mode == "holes" + working_mask = (correct_holes ^ mask).astype(np.uint8) + n_labels, regions, stats, _ = cv2.connectedComponentsWithStats(working_mask, 8) + sizes = stats[:, -1][1:] # Row 0 is background label + small_regions = [i + 1 for i, s in enumerate(sizes) if s < area_thresh] + if len(small_regions) == 0: + return mask, False + fill_labels = [0] + small_regions + if not correct_holes: + fill_labels = [i for i in range(n_labels) if i not in fill_labels] + # If every region is below threshold, keep largest + if len(fill_labels) == 0: + fill_labels = [int(np.argmax(sizes)) + 1] + mask = np.isin(regions, fill_labels) + return mask, True + + +def coco_encode_rle(uncompressed_rle: Dict[str, Any]) -> Dict[str, Any]: + from pycocotools import mask as mask_utils # type: ignore + + h, w = uncompressed_rle["size"] + rle = mask_utils.frPyObjects(uncompressed_rle, h, w) + rle["counts"] = rle["counts"].decode("utf-8") # Necessary to serialize with json + return rle + + +def batched_mask_to_box(masks: torch.Tensor) -> torch.Tensor: + """ + Calculates boxes in XYXY format around masks. Return [0,0,0,0] for + an empty mask. For input shape C1xC2x...xHxW, the output shape is C1xC2x...x4. + """ + # torch.max below raises an error on empty inputs, just skip in this case + if torch.numel(masks) == 0: + return torch.zeros(*masks.shape[:-2], 4, device=masks.device) + + # Normalize shape to CxHxW + shape = masks.shape + h, w = shape[-2:] + if len(shape) > 2: + masks = masks.flatten(0, -3) + else: + masks = masks.unsqueeze(0) + + # Get top and bottom edges + in_height, _ = torch.max(masks, dim=-1) + in_height_coords = in_height * torch.arange(h, device=in_height.device)[None, :] + bottom_edges, _ = torch.max(in_height_coords, dim=-1) + in_height_coords = in_height_coords + h * (~in_height) + top_edges, _ = torch.min(in_height_coords, dim=-1) + + # Get left and right edges + in_width, _ = torch.max(masks, dim=-2) + in_width_coords = in_width * torch.arange(w, device=in_width.device)[None, :] + right_edges, _ = torch.max(in_width_coords, dim=-1) + in_width_coords = in_width_coords + w * (~in_width) + left_edges, _ = torch.min(in_width_coords, dim=-1) + + # If the mask is empty the right edge will be to the left of the left edge. + # Replace these boxes with [0, 0, 0, 0] + empty_filter = (right_edges < left_edges) | (bottom_edges < top_edges) + out = torch.stack([left_edges, top_edges, right_edges, bottom_edges], dim=-1) + out = out * (~empty_filter).unsqueeze(-1) + + # Return to original shape + if len(shape) > 2: + out = out.reshape(*shape[:-2], 4) + else: + out = out[0] + + return out diff --git a/HyperVision/utils/spectral_process_utils.py b/HyperVision/utils/spectral_process_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1609e57a55fe2cd2210cfbb877ee2a84130f2ad7 --- /dev/null +++ b/HyperVision/utils/spectral_process_utils.py @@ -0,0 +1,146 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +import random +TORCH_MAJOR = int(torch.__version__.split('.')[0]) +TORCH_MINOR = int(torch.__version__.split('.')[1]) +from osgeo import gdal + +# Preset wavelengths of key bands +spectral_wavelength = [400, 412.5, 429.5, 443, 455, 467.5, 473.375, 481.25, 488.25, + 500, 520, 531, 536, 545, 550.5, 561.25, 564.75, 565.5, 575, 580, + 596, 605, 610, 612, 626, 627.5, 630, 635, 640, 645, 650, 655, 656, + 660, 664.5, 665, 667, 671.25, 677.5, 686, 700, 705, 710, 716, 725, + 730, 740, 748.5, 760, 764.25, 776, 783, 790, 808, 820, 825, 830, + 835.3125, 842, 850, 858.5, 865, 866, 869.5, 880, 896, 905, 910, 926, + 938, 945, 950, 959, 1240, 1375, 1575, 1575.5, 1610, 1640, 1650, 2050.25, + 2130, 2195, 2217.5,2500] + +# Preset wavelength indices for weight dictionary from 400-2500 +weight_bank_wavelength = np.arange(400,2510,10).tolist() + +# Wavelengths for training AVIRIS hyperspectral data +input_wavelengths_hy=[ 404.6129, 414.2946, 423.9808, 433.6713, 443.3662, 453.0655, + 462.7692, 472.4773, 482.1898, 491.9066, 501.6279, 511.3535, 521.0836, 530.818, 540.5568, 550.3, + 560.0477, 569.7996, 579.556, 589.3168, 599.0819, 608.8515, 618.6254, 628.4037, 638.1865, 647.9736, + 657.7651, 667.561, 655.2923, 665.0994, 674.9012, 684.6979, 694.4894, 704.2756, 714.0566, 723.8325, + 733.6031, 743.3685, 753.1287, 762.8837, 772.6335, 782.3781, 792.1174, 801.8516, 811.5805, 821.3043, + 831.0228, 840.7361, 850.4442, 860.1471, 869.8448, 879.5372, 889.2245, 898.9066, 908.5834, 918.2551, + 927.9214, 937.5827, 947.2387, 956.8895, 966.5351, 976.1755, 985.8106, 995.4406, 1005.065, 1014.685, + 1024.299, 1033.908, 1043.512, 1053.111, 1062.704, 1072.293, 1081.876, 1091.454, 1101.026, 1110.594, + 1120.156, 1129.713, 1139.265, 1148.811, 1158.353, 1167.889, 1177.42, 1186.946, 1196.466, 1205.982, + 1215.492, 1224.997, 1234.496, 1243.991, 1253.48, 1262.964, 1253.373, 1263.346, 1273.318, 1283.291, + 1293.262, 1303.234, 1313.206, 1323.177, 1333.148, 1343.119, 1353.089, 1363.06, 1373.03, 1383.0, + 1392.969, 1402.939, 1412.908, 1422.877, 1432.845, 1442.814, 1452.782, 1462.75, 1472.718, 1482.685, + 1492.652, 1502.619, 1512.586, 1522.552, 1532.518, 1542.484, 1552.45, 1562.416, 1572.381, 1582.346, + 1592.311, 1602.275, 1612.24, 1622.204, 1632.167, 1642.131, 1652.094, 1662.057, 1672.02, 1681.983, + 1691.945, 1701.907, 1711.869, 1721.831, 1731.792, 1741.753, 1751.714, 1761.675, 1771.635, 1781.596, + 1791.556, 1801.515, 1811.475, 1821.434, 1831.393, 1841.352, 1851.31, 1861.269, 1871.227, 1880.184, + 1874.164, 1884.225, 1894.285, 1904.342, 1914.396, 1924.448, 1934.499, 1944.546, 1954.592, 1964.635, + 1974.675, 1984.714, 1994.75, 2004.784, 2014.815, 2024.845, 2034.872, 2044.896, 2054.919, 2064.939, + 2074.956, 2084.972, 2094.985, 2104.996, 2115.004, 2125.01, 2135.014, 2145.016, 2155.015, 2165.012, + 2175.007, 2184.999, 2194.989, 2204.977, 2214.962, 2224.945, 2234.926, 2244.905, 2254.881, 2264.854, + 2274.826, 2284.795, 2294.762, 2304.727, 2314.689, 2324.649, 2334.607, 2344.562, 2354.516, 2364.467, + 2374.415, 2384.361, 2394.305, 2404.247, 2414.186, 2424.123, 2434.058, 2443.99, 2453.92, 2463.848, + 2473.773, 2483.696, 2493.617, 2503.536] + + +# Wavelengths for training multispectral data +input_wavelengths_mu=[ + 425,480,545,605,660,725,835,950 +] + +def generate_random_indices(N, T): + indices = [] + for _ in range(T): + index = random.randint(0, N) + indices.append(index) + return indices + + +#bandfeature = [4,5,7,8,9] +def split_by_wavelengths(tensor, indices, num_blocks,input_wavelengths): + B, C, H, W = tensor.shape + blocks = [] + # 遍历光谱波长 + for i in range(len(spectral_wavelength) - 1): + start_wavelength = spectral_wavelength[i] + end_wavelength = spectral_wavelength[i + 1] + + block_indices = [] + #is_first = True + for j, wavelength in enumerate(input_wavelengths): + if start_wavelength <= wavelength <= end_wavelength and j not in indices: + block_indices.append(j) + if not block_indices: + blocks.append(torch.empty(B, 0, H, W, device=tensor.device)) + else: + block = tensor[:, block_indices, :, :] + blocks.append(block) + + if len(blocks) < num_blocks: + blocks.append(torch.empty(B, 0, H, W, device=tensor.device)) + + return blocks + + +def find_corresponding_indices(input_wavelengths, target_wavelengths,dis): + corresponding_indices = [] + unmatched_indices = [] + matched_indices = [] + for target_index, target_wavelength in enumerate(target_wavelengths): + found_corresponding = False + for input_index, input_wavelength in enumerate(input_wavelengths): + if abs(target_wavelength - input_wavelength) <= dis: + corresponding_indices.append(input_index) + found_corresponding = True + matched_indices.append(target_index) + break + if not found_corresponding: + unmatched_indices.append(target_index) + return corresponding_indices, unmatched_indices, matched_indices + + +def read_img(img_path: str): + """ + Read imagery as ndarray + :param img_path: + :param gdal_read: + :return: + """ + dataset = gdal.Open(img_path) + w, h = dataset.RasterXSize, dataset.RasterYSize + img = dataset.ReadAsArray(0, 0, w, h) + if len(img.shape) == 3: + img = np.transpose(img, axes=(1, 2, 0)) # [c,h,w]->[h,w,c] + return img + + +def write_img(img: np.ndarray, save_path: str): + """ + Save ndarray as imagery + :param img: + :param save_path: + :param gdal_write: + :return: + """ + if 'int8' in img.dtype.name: + datatype = gdal.GDT_Byte + elif 'int16' in img.dtype.name: + datatype = gdal.GDT_UInt16 + else: + datatype = gdal.GDT_Float32 + + if len(img.shape) == 3: + img = np.transpose(img, axes=(2, 0, 1)) # [h,w,c]->[c,h,w] + elif len(img.shape) == 2: + img = np.expand_dims(img, axis=0) + + img_bands, img_height, img_width = img.shape + + driver = gdal.GetDriverByName("GTiff") + dataset = driver.Create(save_path, int(img_width), int(img_height), int(img_bands), datatype) + for i in range(img_bands): + dataset.GetRasterBand(i + 1).WriteArray(img[i]) + del dataset \ No newline at end of file diff --git a/HyperVision/utils/transforms.py b/HyperVision/utils/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..0cdd0e02b123bd508180e3697a94e1af1a1aa570 --- /dev/null +++ b/HyperVision/utils/transforms.py @@ -0,0 +1,102 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np +import torch +from torch.nn import functional as F +from torchvision.transforms.functional import resize, to_pil_image # type: ignore + +from copy import deepcopy +from typing import Tuple + + +class ResizeLongestSide: + """ + Resizes images to the longest side 'target_length', as well as provides + methods for resizing coordinates and boxes. Provides methods for + transforming both numpy array and batched torch tensors. + """ + + def __init__(self, target_length: int) -> None: + self.target_length = target_length + + def apply_image(self, image: np.ndarray) -> np.ndarray: + """ + Expects a numpy array with shape HxWxC in uint8 format. + """ + target_size = self.get_preprocess_shape(image.shape[0], image.shape[1], self.target_length) + return np.array(resize(to_pil_image(image), target_size)) + + def apply_coords(self, coords: np.ndarray, original_size: Tuple[int, ...]) -> np.ndarray: + """ + Expects a numpy array of length 2 in the final dimension. Requires the + original image size in (H, W) format. + """ + old_h, old_w = original_size + new_h, new_w = self.get_preprocess_shape( + original_size[0], original_size[1], self.target_length + ) + coords = deepcopy(coords).astype(float) + coords[..., 0] = coords[..., 0] * (new_w / old_w) + coords[..., 1] = coords[..., 1] * (new_h / old_h) + return coords + + def apply_boxes(self, boxes: np.ndarray, original_size: Tuple[int, ...]) -> np.ndarray: + """ + Expects a numpy array shape Bx4. Requires the original image size + in (H, W) format. + """ + boxes = self.apply_coords(boxes.reshape(-1, 2, 2), original_size) + return boxes.reshape(-1, 4) + + def apply_image_torch(self, image: torch.Tensor) -> torch.Tensor: + """ + Expects batched images with shape BxCxHxW and float format. This + transformation may not exactly match apply_image. apply_image is + the transformation expected by the model. + """ + # Expects an image in BCHW format. May not exactly match apply_image. + target_size = self.get_preprocess_shape(image.shape[2], image.shape[3], self.target_length) + return F.interpolate( + image, target_size, mode="bilinear", align_corners=False, antialias=True + ) + + def apply_coords_torch( + self, coords: torch.Tensor, original_size: Tuple[int, ...] + ) -> torch.Tensor: + """ + Expects a torch tensor with length 2 in the last dimension. Requires the + original image size in (H, W) format. + """ + old_h, old_w = original_size + new_h, new_w = self.get_preprocess_shape( + original_size[0], original_size[1], self.target_length + ) + coords = deepcopy(coords).to(torch.float) + coords[..., 0] = coords[..., 0] * (new_w / old_w) + coords[..., 1] = coords[..., 1] * (new_h / old_h) + return coords + + def apply_boxes_torch( + self, boxes: torch.Tensor, original_size: Tuple[int, ...] + ) -> torch.Tensor: + """ + Expects a torch tensor with shape Bx4. Requires the original image + size in (H, W) format. + """ + boxes = self.apply_coords_torch(boxes.reshape(-1, 2, 2), original_size) + return boxes.reshape(-1, 4) + + @staticmethod + def get_preprocess_shape(oldh: int, oldw: int, long_side_length: int) -> Tuple[int, int]: + """ + Compute the output size given input size and target long side length. + """ + scale = long_side_length * 1.0 / max(oldh, oldw) + newh, neww = oldh * scale, oldw * scale + neww = int(neww + 0.5) + newh = int(newh + 0.5) + return (newh, neww) \ No newline at end of file diff --git a/README.md b/README.md index 154df8298fab5ecf322016157858e08cd1bccbe1..dfa3feef8f8015ee70f02050ea77ed826076a983 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,147 @@ +# HyperVision: Channel-Adaptive Ground-Based Hyperspectral Vision Foundation Models + +*This is the official repository for the paper "HyperVision: Channel-Adaptive Ground-Based Hyperspectral Vision Foundation Models".* +https://arxiv.org/abs/2605.17286 + --- -license: apache-2.0 + +🚀 **News:** +- **[Coming Soon]** We will soon open-source the official implementation and pre-trained foundation models! Please stay tuned! + --- + +## 📖 Abstract + +While hyperspectral imaging provides rich spatial-spectral information across hundreds of narrow wavelength bands for precise material identification, ground-based hyperspectral pre-trained backbones remain absent, constrained by varying spectral configurations across sensors, the scarcity and inconsistency of labels, and the limited scale and scene diversity of existing datasets. To address these challenges and enable universal perception, we propose HyperVision, the first ground-based hyperspectral pre-trained backbone. First, to handle varying spectral configurations, HyperVision adopts a channel-adaptive dynamic embedding mechanism to map heterogeneous inputs into a unified token space. Second, to address the scarcity and inconsistency of labels, we introduce a multi-source pseudo-labeling method that fuses semantic representations from both spatial structures generated by SAM2 and fine-grained spectral material information extracted by HyperFree. Third, to compensate for limited dataset scale and enrich scene diversity, a cross-modal knowledge distillation mechanism is utilized to transfer rich semantic representations from a pre-trained RGB vision model to our hyperspectral backbone. Pre-trained on a collection of 15k images from 26 diverse ground-based datasets, HyperVision demonstrates exceptional generalization. Requiring only efficient head-only adaptation without adjusting backbone parameters, it achieves state-of-the-art performance compared to task-specific methods across three downstream tasks under varying sensor configurations, yielding up to a 16.3% relative improvement in hyperspectral semantic segmentation $\text{Acc}_{\text{M}}$, a 2.1% relative gain in object tracking AUC, and a 35.5% reduction in salient object detection MAE. The source code and pre-trained model will be publicly available online. + +## 🛠️ Main Code (HyperVision) + +The core architecture and model initialization utilities are located under the [HyperVision](./HyperVision) directory. + +To initialize the model, you can use the model builder functions from [HyperVision/build_HyperVision.py](./HyperVision/build_HyperVision.py). We support different model configurations: +- **HyperVision-B**: `build_HyperVision_b` +- **HyperVision-L**: `build_HyperVision_l` +- **HyperVision-H** (Default): `build_HyperVision_h` + +### Python Example: +```python +import torch +from HyperVision import build_HyperVision_h, HyperVision_Predictor +from hyperspectral_image_reader.read_dataset_image import load_hypervision_matrix +from hyperspectral_image_reader.hyperspectral_pipelines import LoadHyperspectralImage + +device = "cuda" if torch.cuda.is_available() else "cpu" +image_size = 512 + +# 1. Build the HyperVision model (HyperVision-H configuration shown below) +model = build_HyperVision_h( + checkpoint="path/to/hypervision_distilled_h.pth", # Optional checkpoint path (.pth weights) + image_size=512, # Input resolution + vit_patch_size=16, # Patch size of the backbone + encoder_global_attn_indexes=[15, 23, 31], # Layers using global attention (can be adjusted for debugging/tuning) + merge_indexs=[8, 32], # Layers doing patch merging (can be adjusted for debugging/tuning) + class_number=-1 # Number of classes for mask decoder +) +model = model.to(device) +model.eval() + +# 2. Use HyperVision_Predictor to manage preprocessing and feature extraction +predictor = HyperVision_Predictor(model) + +# 3. Load the preprocessed HSI image as a numpy array using load_hypervision_matrix +# Preprocessed shape: (H_ori, W_ori, C_hsi) with values in range [0, 255] +img_matrix = load_hypervision_matrix("path/to/image.mat", dataset_name="harvard") + +# 4. Automatically retrieve the wavelengths list from the dataset pipeline config +loader = LoadHyperspectralImage(dataset_type="harvard") +wavelengths = loader.wavelengths + +# 5. Call predictor.set_image to preprocess the image and extract features (calculating embeddings) +# GSD represents Ground Sampling Distance (defaults to 0.01) +with torch.no_grad(): + predictor.set_image(img_matrix, test_mode=False, spectral_lengths=wavelengths, GSD=0.01) + +# 6. Extract multi-scale features from the predictor +multi_stage_features = predictor.multi_scale_features +``` + +--- + +## 📊 Dataset Reading & Processing + +We provide [read_dataset_image.py](./hyperspectral_image_reader/read_dataset_image.py) to read and preprocess hyperspectral images from various datasets. The script utilizes the custom data pipeline class `LoadHyperspectralImage` from [configs/hypervision/hyperspectral_pipelines.py](./configs/hypervision/hyperspectral_pipelines.py) to normalize the images (scaled to `[0, 255]`) and reshape them into the format expected by HyperVision: `(H_ori, W_ori, C_hsi)`. + +### Python API Usage: +```python +from hyperspectral_image_reader.read_dataset_image import load_hypervision_matrix + +# Load and preprocess HSI matrix +# dataset_name must be one of the supported dataset identifiers (e.g., 'harvard', 'arad_1k_31') +img_matrix = load_hypervision_matrix("path/to/image.mat", dataset_name="harvard") +print("Processed shape (H, W, C):", img_matrix.shape) +``` + +### Command Line Interface: +You can also run the script from the command line to load an HSI image and optionally save the processed matrix as a `.npy` file: +```bash +python hyperspectral_image_reader/read_dataset_image.py --path /path/to/image.mat --dataset harvard --output output.npy +``` + +--- + +## 🗃️ Supported Datasets + +Below is a summary of the ground-based hyperspectral datasets supported by our pipeline, along with their respective keys to be used for the `--dataset` parameter: + +| Dataset Name | `--dataset` Key | # Bands | Wavelengths | # Images | Expected Extension | File Loader Detail / Required Accompanying Files | +| :--- | :--- | :---: | :---: | :---: | :---: | :--- | +| **50 Outdoor** | `fiftyoutdoor` | 33 | 400–720 nm | 50 | `.mat` | Custom Mat loader | +| **Agricultural Plant** | `aphid` | 237 | 436–965 nm | 361 | `.npy` | NumPy array loader | +| **ARAD1K16** | `arad_1k_16` | 16 | 400–1000 nm | 950 | `.mat` | HDF5 H5PY loader | +| **ARAD1K31** | `arad_1k_31` | 31 | 400–700 nm | 949 | `.mat` | HDF5 H5PY loader | +| **CAVE** | `cave` | 31 | 400–700 nm | 32 | `.mat` | Mat loader | +| **DeepHS-NIR** | `deephsnir` | 252 | 950–1700 nm | 718 | `.bin` | ENVI binary (requires corresponding `.hdr` file in the same directory) | +| **DeepHS-VIS** | `deephsvis` | 224 | 400–1000 nm | 3405 | `.bin` | ENVI binary (requires corresponding `.hdr` file in the same directory) | +| **DeepHS-VISCOR** | `deephsviscor` | 249 | 400–1000 nm | 1566 | `.bin` | ENVI binary (requires corresponding `.hdr` file in the same directory) | +| **Harvard** | `harvard` | 31 | 420–720 nm | 77 | `.mat` | Mat loader | +| **HOT-2024-NIR** | `hotnir` | 25 | 665–960 nm | 477 | `.png` | PNG frame loader (requires corresponding false-color `.jpg` file) | +| **HOT-2024-RedNIR** | `hotrednir` | 15 | 600–850 nm | 348 | `.png` | PNG frame loader (requires corresponding false-color `.jpg` file) | +| **HOT-2024-VIS** | `hotvis` | 16 | 470–600 nm | 1070 | `.png` | PNG frame loader (requires corresponding false-color `.jpg` file) | +| **HSI Drive v2.0** | `hsidrive20` | 25 | 600–975 nm | 752 | `.npy` | NumPy loader (requires corresponding pseudocolor `.png` file) | +| **HSI Road** | `hsiroad` | 25 | 600–960 nm | 380 | `.tif` | TIF image loader | +| **HSODBIT v2** | `hsodbitv2` | 200 | 400–1000 nm | 500 | `.mat` | HDF5 H5PY loader (requires corresponding color `.jpg` file) | +| **HSSOD** | `hs_sod` | 81 | 380–720 nm | 60 | `.h5` | HDF5 H5PY loader (requires corresponding color `.jpg` file) | +| **HyKo v2-NIR** | `hykov2nir` | 25 | 600–975 nm | 78 | `.mat` | Mat loader | +| **HyKo v2-VIS** | `hykov2vis` | 16 | 470–630 nm | 163 | `.mat` | Mat loader | +| **HyperBlood** | `hyperblood` | 128 | 377–1046 nm | 14 | `.mat` | Custom Mat loader | +| **HyperDrive-VNIR** | `hyperdrivevnir` | 24 | 660–900 nm | 504 | `.npz` | NumPy archive (must contain `cube.npy` file inside) | +| **HyperspectralCity v2** | `hyperspectralcityv2` | 128 | 450–950 nm | 1330 | `.hsd` | HSD raw data loader | +| **ICVL** | `icvl` | 31 | 400–700 nm | 187 | `.h5` | HDF5 H5PY loader | +| **LIB-HSI** | `libhsi` | 204 | 400–1000 nm | 393 | `.hdr` | ENVI header (requires corresponding raw binary data `.raw`/`.dat` file) | +| **UM-EMM** | `umemm` | 33 | 400–720 nm | 3 | `.mat` | Mat loader | +| **UM-LD 2015** | `umld2015` | 33 | 400–720 nm | 20 | `.mat` | Mat loader | +| **UM-NS 2002** | `umns2002` | 31 | 410–710 nm | 8 | `.mat` | Mat loader | +| **UM-NS 2004** | `umns2004` | 33 | 400–720 nm | 10 | `.mat` | Mat loader | +| **UM-OS** | `umos` | 33 | 400–720 nm | 50 | `.mat` | Mat loader | +| **UM-RI 2015** | `umri2015` | 33 | 400–720 nm | 33 | `.mat` | Mat loader | +| **Virginia Tech Tree** | `virginia_tech_tree` | 420 | 400–1000 nm | 51 | `.hdr` | ENVI header (requires corresponding raw binary data file) | +| **Apple Fire Blight** | `vnihdhiatlimafb` | 204 | 400–1000 nm | 420 | `.hdr` | ENVI header (requires corresponding raw binary data file) | + +--- + +## 📝 Citation + +If you find our work or this project helpful, please consider citing our paper: + +```bibtex +@misc{fu2026hypervisionf, + title={HyperVision: A Channel-Adaptive Ground-Based Hyperspectral Vision Pre-trained Backbone}, + author={Guanyiman Fu and Jingtao Li and Zihang Cheng and Zhuanfeng Li and Diqi Chen and Yan Xu and Fengchao Xiong and Jianfeng Lu and Jun Zhou}, + year={2026}, + eprint={2605.17286}, + archivePrefix={arXiv}, + primaryClass={cs.CV}, + url={https://arxiv.org/abs/2605.17286}, +} +``` +*(Note: Citation details will be updated upon official publication)* diff --git a/checkpoints/hypervision_distilled_b.pth b/checkpoints/hypervision_distilled_b.pth new file mode 100644 index 0000000000000000000000000000000000000000..948da5b8887989ce4bc77cbfdb2e86fc7cbd6323 --- /dev/null +++ b/checkpoints/hypervision_distilled_b.pth @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:749f50ca026f4d53523c42e939590d3e4418f199824b42bf366c9dea8e72e7c0 +size 602041524 diff --git a/checkpoints/hypervision_distilled_h.pth b/checkpoints/hypervision_distilled_h.pth new file mode 100644 index 0000000000000000000000000000000000000000..068e4b708a1cee69b794f1688d0634e2393d6cd1 --- /dev/null +++ b/checkpoints/hypervision_distilled_h.pth @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f31d90bbbb9f805454d6516da121e1175c90e0dbbb8e22d2f170e32931a41a13 +size 2941990780 diff --git a/checkpoints/hypervision_distilled_l.pth b/checkpoints/hypervision_distilled_l.pth new file mode 100644 index 0000000000000000000000000000000000000000..a090bf34b9c6f8a43c6d22581e0bdb0886a00965 --- /dev/null +++ b/checkpoints/hypervision_distilled_l.pth @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c2692a83934cf3019172cb949c121d31e7801733283f50167263e5c32d04f7bd +size 1358168064 diff --git a/environment.yml b/environment.yml new file mode 100644 index 0000000000000000000000000000000000000000..aebdc932ec2206b7d149ef474a81b7d02af1d4d8 --- /dev/null +++ b/environment.yml @@ -0,0 +1,183 @@ +name: hypervision +channels: + - defaults + - conda-forge +dependencies: + - _libgcc_mutex=0.1=main + - _openmp_mutex=5.1=52_gnu + - aom=3.13.2=h664349e_0 + - blas=1.0=mkl + - blosc=1.21.6=hef167b5_0 + - bzip2=1.0.8=h5eee18b_6 + - c-ares=1.34.6=hb03c661_0 + - ca-certificates=2026.6.17=hbd8a1cb_0 + - cairo=1.18.4=ha82d1dd_1 + - dav1d=1.5.3=h3e43c27_0 + - fontconfig=2.17.1=h062c814_0 + - freetype=2.14.1=hf5b9546_0 + - freexl=2.0.0=h9dce30a_2 + - fribidi=1.0.16=h10f3c28_1 + - gdal=3.13.0=py310h0d13066_0 + - geos=3.10.6=h9db6f96_0 + - geotiff=1.7.4=h1000f5c_4 + - giflib=6.1.3=h621bd71_1 + - graphite2=1.3.15=h9ba177b_0 + - harfbuzz=12.3.0=h572a7f1_2 + - icu=78.3=h84d19a5_0 + - imageio=2.37.3=py310h7040dfc_0 + - intel-openmp=2025.0.0=h06a4308_1172 + - json-c=0.18=h6688a6e_0 + - keyutils=1.6.3=hb9d3cd8_0 + - krb5=1.22.2=hbde042b_1 + - lazy_loader=0.5=py310h06a4308_0 + - lcms2=2.19.1=h425df66_1 + - ld_impl_linux-64=2.44=h9e0c5a2_3 + - lerc=4.1.0=h7354ed3_2 + - libarchive=3.8.7=hb3cce40_0 + - libavif=1.3.0=h2b90b00_1 + - libcurl=8.21.0=hae6b9f4_2 + - libdeflate=1.22=h5eee18b_0 + - libedit=3.1.20250104=pl5321h7949ede_0 + - libev=4.33=hd590300_2 + - libexpat=2.8.1=h7354ed3_1 + - libffi=3.4.8=h06d3fd0_3 + - libgcc=15.2.0=h69a1729_8 + - libgcc-ng=15.2.0=h166f726_8 + - libgdal-core=3.13.0=h36498ad_0 + - libgfortran=15.2.0=h166f726_8 + - libgfortran5=15.2.0=hc633d37_8 + - libglib=2.86.3=ha16e27a_1 + - libgomp=15.2.0=h4751f2c_8 + - libiconv=1.18=h75a1612_0 + - libjpeg-turbo=3.1.3=h47b2149_0 + - libkml=1.3.0=haa4a5bd_1023 + - libnghttp2=1.68.1=h877daf1_0 + - libnsl=2.0.0=h5eee18b_0 + - libopenjpeg=2.5.4=h47b2149_2 + - libpng=1.6.56=h22898a0_0 + - libpsl=0.22.0=hd9031aa_0 + - libspatialite=5.1.0=h9696827_4 + - libsqlite=3.53.3=h0c1763c_0 + - libssh2=1.11.1=hcf80075_0 + - libstdcxx=15.2.0=h39759b7_8 + - libstdcxx-ng=15.2.0=hc03a8fd_8 + - libtiff=4.7.1=h2b43d3b_1 + - libuuid=1.41.5=h5eee18b_0 + - libwebp-base=1.6.0=hb7bb969_0 + - libxcb=1.17.0=h9b100fa_0 + - libxml2=2.14.6=hf2a51f9_1 + - libzlib=1.3.2=h47b2149_0 + - lz4-c=1.9.4=h7354ed3_3 + - minizip=4.2.1=h7e49174_0 + - mkl=2025.0.0=h6d8faa4_942 + - mkl-service=2.7.2=py310h365c7f6_0 + - mkl_fft=2.2.0=py310h44c8d7b_0 + - mkl_random=1.4.1=py310h86c3e14_0 + - ncurses=6.5=h7934f7d_0 + - networkx=3.4.2=py310h06a4308_0 + - numpy-base=2.2.5=py310h00548fb_3 + - openssl=3.6.3=h35e630c_0 + - packaging=26.0=py310h06a4308_0 + - pcre2=10.46=hf426167_0 + - pillow=12.2.0=py310ha780b37_1 + - pip=26.1.2=pyhc872135_0 + - pixman=0.46.4=h86ba9f7_1 + - proj=9.7.1=he0df7b0_3 + - pthread-stubs=0.3=h0ce48e5_1 + - python=3.10.20=h17756b0_1 + - readline=8.3=hc2a1206_0 + - scikit-image=0.25.2=py310h86c3e14_1 + - scipy=1.15.3=py310h4c24699_2 + - snappy=1.2.2=h03e3b7b_1 + - sqlite=3.53.2=h795bf6d_0 + - tbb=2022.0.0=hdb19cb5_0 + - tbb-devel=2022.0.0=hdb19cb5_0 + - tk=8.6.15=h54e0aa7_0 + - uriparser=0.9.8=hac33072_0 + - wheel=0.47.0=py310h06a4308_0 + - xerces-c=3.3.0=h8929472_1 + - xorg-libx11=1.8.12=h9b100fa_1 + - xorg-libxau=1.0.12=h9b100fa_0 + - xorg-libxdmcp=1.1.5=h9b100fa_0 + - xorg-libxext=1.3.6=h9b100fa_0 + - xorg-libxrender=0.9.12=h9b100fa_0 + - xorg-xorgproto=2024.1=h5eee18b_1 + - xz=5.8.2=h448239c_0 + - zlib=1.3.2=h47b2149_0 + - zstd=1.5.7=h11fc155_0 + - pip: + - addict==2.4.0 + - affine==2.4.0 + - attrs==26.1.0 + - certifi==2026.6.17 + - click==8.4.2 + - click-plugins==1.1.1.2 + - cligj==0.7.2 + - contourpy==1.3.2 + - cuda-bindings==12.9.4 + - cuda-pathfinder==1.5.6 + - cupy-cuda12x==14.1.1 + - cycler==0.12.1 + - filelock==3.29.0 + - fonttools==4.63.0 + - fsspec==2026.4.0 + - h5py==3.16.0 + - hdf5plugin==7.0.0 + - jinja2==3.1.6 + - kiwisolver==1.5.0 + - markdown-it-py==4.2.0 + - markupsafe==3.0.3 + - matplotlib==3.10.9 + - mdurl==0.1.2 + - mmcv==2.1.0 + - mmcv-lite==2.1.0 + - mmdet==3.3.0 + - mmengine==0.10.7 + - mpmath==1.3.0 + - numpy==2.2.6 + - nvidia-cublas-cu12==12.8.4.1 + - nvidia-cuda-cupti-cu12==12.8.90 + - nvidia-cuda-nvrtc-cu12==12.8.93 + - nvidia-cuda-runtime-cu12==12.8.90 + - nvidia-cudnn-cu12==9.10.2.21 + - nvidia-cufft-cu12==11.3.3.83 + - nvidia-cufile-cu12==1.13.1.3 + - nvidia-curand-cu12==10.3.9.90 + - nvidia-cusolver-cu12==11.7.3.90 + - nvidia-cusparse-cu12==12.5.8.93 + - nvidia-cusparselt-cu12==0.7.1 + - nvidia-nccl-cu12==2.27.5 + - nvidia-nvjitlink-cu12==12.8.93 + - nvidia-nvshmem-cu12==3.4.5 + - nvidia-nvtx-cu12==12.8.90 + - opencv-python==4.13.0.92 + - pandas==2.3.3 + - platformdirs==4.10.0 + - pycocotools==2.0.11 + - pygments==2.20.0 + - pyparsing==3.3.2 + - python-dateutil==2.9.0.post0 + - pytz==2026.2 + - pyyaml==6.0.3 + - rasterio==1.4.4 + - rich==15.0.0 + - setuptools==69.5.1 + - setuptools-scm==10.2.0 + - shapely==2.1.2 + - six==1.17.0 + - spectral==0.24 + - sympy==1.14.0 + - termcolor==3.3.0 + - terminaltables==3.1.10 + - tifffile==2025.5.10 + - tomli==2.4.1 + - torch==2.10.0+cu128 + - torchaudio==2.10.0+cu128 + - torchvision==0.25.0+cu128 + - tqdm==4.68.3 + - triton==3.6.0 + - typing-extensions==4.15.0 + - tzdata==2026.2 + - vcs-versioning==2.2.0 + - yapf==0.43.0 +prefix: /home/gym/.conda/envs/hypervision diff --git a/hyperspectral_image_reader/__pycache__/hyperspectral_pipelines.cpython-310.pyc b/hyperspectral_image_reader/__pycache__/hyperspectral_pipelines.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4f12eec791de9f6e99bd4fdd2d20eb096adc96c Binary files /dev/null and b/hyperspectral_image_reader/__pycache__/hyperspectral_pipelines.cpython-310.pyc differ diff --git a/hyperspectral_image_reader/__pycache__/hyperspectral_pipelines.cpython-313.pyc b/hyperspectral_image_reader/__pycache__/hyperspectral_pipelines.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..237290a0b2b4bd7c281edc2d03572301045cea8c Binary files /dev/null and b/hyperspectral_image_reader/__pycache__/hyperspectral_pipelines.cpython-313.pyc differ diff --git a/hyperspectral_image_reader/__pycache__/read_dataset_image.cpython-310.pyc b/hyperspectral_image_reader/__pycache__/read_dataset_image.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29f6f332435025561bf49ad0a9a7b2fb7beee1b5 Binary files /dev/null and b/hyperspectral_image_reader/__pycache__/read_dataset_image.cpython-310.pyc differ diff --git a/hyperspectral_image_reader/__pycache__/read_dataset_image.cpython-313.pyc b/hyperspectral_image_reader/__pycache__/read_dataset_image.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d7e7d38a60be7188567869c0b75522294829fdb Binary files /dev/null and b/hyperspectral_image_reader/__pycache__/read_dataset_image.cpython-313.pyc differ diff --git a/hyperspectral_image_reader/hyperspectral_pipelines.py b/hyperspectral_image_reader/hyperspectral_pipelines.py new file mode 100644 index 0000000000000000000000000000000000000000..6e72038b2982c92165612b2598ee40e05d3e0abb --- /dev/null +++ b/hyperspectral_image_reader/hyperspectral_pipelines.py @@ -0,0 +1,2188 @@ +# Copyright (c) OpenMMLab. All rights reserved. +""" +Hyperspectral Dataset Pipelines for MMDetection + +This file contains data pipelines for various hyperspectral datasets +adapted from the ARMhsi/utils/datasets_maskgen.py file. +""" + +import numpy as np +from skimage.transform import resize as sk_resize +import torch +import torch.distributed as dist +from scipy.io import loadmat +import mmcv +from mmcv.transforms import BaseTransform +from mmcv.transforms.utils import cache_randomness +from mmdet.registry import TRANSFORMS +from mmdet.datasets.transforms import LoadAnnotations +import mmengine +from mmengine.registry import TRANSFORMS as MMENGINE_TRANSFORMS +from mmengine.fileio import get +import os +from PIL import Image +import cv2 +import h5py +import hdf5plugin +import rasterio +import spectral.io.envi as envi +import tifffile +import random +from configs.hypervision import ds_load +from configs.hypervision.hsi3d import get_image_loader +import cupy as cp +from typing import Dict, Iterable, List, Optional, Sequence, Tuple, Union +import logging +# from mmengine.logging import MMLogger + +from mmengine.logging import MMLogger +from mmengine.runner import Runner + +_PIPELINE_RANK_LOGGERS: Dict[str, logging.Logger] = {} + + +def _get_rank_logger( + base_name: str = 'pipeline', + logger_cache: Optional[Dict[str, logging.Logger]] = None, + enable: bool = False, +) -> tuple[int, Optional[logging.Logger]]: + if dist.is_available() and dist.is_initialized(): + rank = dist.get_rank() + else: + rank = 0 + + if not enable: + return rank, None + + cache = logger_cache if logger_cache is not None else _PIPELINE_RANK_LOGGERS + + logger_key = f'{base_name}.rank{rank}' + logger = cache.get(logger_key) + if logger is not None: + return rank, logger + + work_dir = os.environ.get('MMDET_WORK_DIR', './work_dirs') + try: + runner = Runner.get_instance() + if runner is not None and getattr(runner, 'work_dir', None): + work_dir = runner.work_dir + except Exception: + pass + + log_dir = os.path.join(work_dir, 'rank_logs') + os.makedirs(log_dir, exist_ok=True) + log_path = os.path.join(log_dir, f'{base_name}_rank{rank}.log') + + logger = logging.getLogger(logger_key) + if not logger.handlers: + logger.setLevel(logging.INFO) + logger.propagate = False + handler = logging.FileHandler(log_path) + formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') + handler.setFormatter(formatter) + logger.addHandler(handler) + + cache[logger_key] = logger + return rank, logger + +def read_HSD(filename): + data = np.fromfile('%s' % filename, dtype=np.int32) + height = data[0] + width = data[1] + SR = data[2] + D = data[3] + + data = np.fromfile('%s' % filename, dtype=np.float32) + a = 7 + average = data[a:a + SR.item()] + a = a + SR.item() + coeff = data[a:a + D.item() * SR.item()].reshape((D.item(), SR.item())) + a = a + D.item() * SR.item() + scoredata = data[a:a + height.item() * width.item() * D.item()].reshape((height.item() * width.item(), D.item())) + + temp = np.dot(scoredata, coeff) + data = (temp + average).reshape((height.item(), width.item(), SR.item())) + + # data = np.asnumpy(data) + + return data + +@TRANSFORMS.register_module() +@MMENGINE_TRANSFORMS.register_module() +class LoadHyperspectralImage(BaseTransform): + """Load hyperspectral image from various formats. + + This transform handles loading of hyperspectral images from different + file formats (.mat, .npy, .tif, .png) and normalizes them according + to dataset-specific parameters. + + Required Keys: + - img_path + + Modified Keys: + - img + - img_shape + - ori_shape + - img_path + + Args: + dataset_type (str): Type of dataset ('harvard', 'umld2015', etc.) + to_float32 (bool): Whether to convert to float32. Defaults to True. + append_rgb (bool): Whether to append RGB channels. Defaults to False. + """ + + def __init__( + self, + dataset_type='harvard', + to_float32=True, + append_rgb=True, + enable_rank_logging=False, + rank_logger_cache: Optional[Dict[str, logging.Logger]] = None, + ): + self.dataset_type = dataset_type + self.to_float32 = to_float32 + self.append_rgb = append_rgb + self.enable_rank_logging = enable_rank_logging + self.rank_logger_cache = rank_logger_cache + + # Dataset-specific parameters + self._init_dataset_params() + + # Initialize wavelength information + self._init_wavelength_params() + + def _init_dataset_params(self): + """Initialize dataset-specific normalization parameters.""" + if self.dataset_type == 'harvard': + self.mean = [0.00050713, 0.00070553, 0.0011365, 0.00149156, 0.00197441, 0.00223908, + 0.00271003, 0.00345612, 0.00369303, 0.00385219, 0.00435618, 0.00506823, + 0.0070418, 0.00800666, 0.0064554, 0.00628767, 0.00703461, 0.00775983, + 0.00832022, 0.00929337, 0.00898094, 0.00748522, 0.00755848, 0.00718764, + 0.00699057, 0.00689327, 0.00674753, 0.00671624, 0.00751943, 0.00741207, + 0.00676514] + [0.485, 0.456, 0.406] + self.std = [0.00035424, 0.00053509, 0.0009189, 0.00122868, 0.00164547, 0.00186258, + 0.00224559, 0.00286002, 0.0030474, 0.00315195, 0.00353866, 0.00406267, + 0.0055249, 0.00622435, 0.00500298, 0.00480104, 0.0052598, 0.00571489, + 0.00601454, 0.00659049, 0.00634349, 0.00530685, 0.00537778, 0.00513787, + 0.00498475, 0.00488729, 0.00471964, 0.00454973, 0.00490581, 0.0046964, + 0.00421346] + [0.229, 0.224, 0.225] + self.max_val = 1.0 + self.min_val = 0.0 + self.bands = 31 + + elif self.dataset_type == 'umld2015': + self.mean = [0.00049507, 0.00077369, 0.00086868, 0.00092949, 0.00106588, 0.00134611, + 0.00148952, 0.00138134, 0.00147178, 0.00140757, 0.00146943, 0.0014896, + 0.00158795, 0.0017375, 0.00171897, 0.00186404, 0.00182205, 0.00166717, + 0.00176569, 0.00172996, 0.00177187, 0.00178079, 0.00172655, 0.00166295, + 0.00167107, 0.0016319, 0.00167044, 0.00166259, 0.00153768, 0.0013869, + 0.00148293, 0.0015571, 0.00129303] + [0.485, 0.456, 0.406] + self.std = [0.0004163, 0.00053372, 0.00057629, 0.00060292, 0.00068114, 0.00085653, + 0.00095103, 0.0008941, 0.00095387, 0.00092446, 0.00096502, 0.00096958, + 0.00102551, 0.00111695, 0.00109679, 0.00118504, 0.00117788, 0.00107841, + 0.00114765, 0.00113261, 0.00116322, 0.00116857, 0.0011256, 0.0010963, + 0.00110381, 0.00108571, 0.00111103, 0.00111677, 0.00103602, 0.00092566, + 0.0009724, 0.00101692, 0.00085337] + [0.229, 0.224, 0.225] + self.max_val = 795.4633697273729 + self.min_val = -1.2406029247200091e-05 + self.bands = 33 + + elif self.dataset_type == 'umns2002': + # UMNS2002 dataset parameters (31 bands) + self.mean = [0.00050713, 0.00070553, 0.0011365, 0.00149156, 0.00197441, 0.00223908, + 0.00271003, 0.00345612, 0.00369303, 0.00385219, 0.00435618, 0.00506823, + 0.0070418, 0.00800666, 0.0064554, 0.00628767, 0.00703461, 0.00775983, + 0.00832022, 0.00929337, 0.00898094, 0.00748522, 0.00755848, 0.00718764, + 0.00699057, 0.00689327, 0.00674753, 0.00671624, 0.00751943, 0.00741207, + 0.00676514] + [0.485, 0.456, 0.406] + self.std = [0.00035424, 0.00053509, 0.0009189, 0.00122868, 0.00164547, 0.00186258, + 0.00224559, 0.00286002, 0.0030474, 0.00315195, 0.00353866, 0.00406267, + 0.0055249, 0.00622435, 0.00500298, 0.00480104, 0.0052598, 0.00571489, + 0.00601454, 0.00659049, 0.00634349, 0.00530685, 0.00537778, 0.00513787, + 0.00498475, 0.00488729, 0.00471964, 0.00454973, 0.00490581, 0.0046964, + 0.00421346] + [0.229, 0.224, 0.225] + self.max_val = 1.0 + self.min_val = 0.0 + self.bands = 31 + + elif self.dataset_type == 'umns2004': + # UMNS2004 dataset parameters (33 bands) + self.mean = [0.00049507, 0.00077369, 0.00086868, 0.00092949, 0.00106588, 0.00134611, + 0.00148952, 0.00138134, 0.00147178, 0.00140757, 0.00146943, 0.0014896, + 0.00158795, 0.0017375, 0.00171897, 0.00186404, 0.00182205, 0.00166717, + 0.00176569, 0.00172996, 0.00177187, 0.00178079, 0.00172655, 0.00166295, + 0.00167107, 0.0016319, 0.00167044, 0.00166259, 0.00153768, 0.0013869, + 0.00148293, 0.0015571, 0.00129303] + [0.485, 0.456, 0.406] + self.std = [0.0004163, 0.00053372, 0.00057629, 0.00060292, 0.00068114, 0.00085653, + 0.00095103, 0.0008941, 0.00095387, 0.00092446, 0.00096502, 0.00096958, + 0.00102551, 0.00111695, 0.00109679, 0.00118504, 0.00117788, 0.00107841, + 0.00114765, 0.00113261, 0.00116322, 0.00116857, 0.0011256, 0.0010963, + 0.00110381, 0.00108571, 0.00111103, 0.00111677, 0.00103602, 0.00092566, + 0.0009724, 0.00101692, 0.00085337] + [0.229, 0.224, 0.225] + self.max_val = 795.4633697273729 + self.min_val = -1.2406029247200091e-05 + self.bands = 33 + + elif self.dataset_type == 'umos': + # UMOS dataset parameters (31 bands) + self.mean = [0.00050713, 0.00070553, 0.0011365, 0.00149156, 0.00197441, 0.00223908, + 0.00271003, 0.00345612, 0.00369303, 0.00385219, 0.00435618, 0.00506823, + 0.0070418, 0.00800666, 0.0064554, 0.00628767, 0.00703461, 0.00775983, + 0.00832022, 0.00929337, 0.00898094, 0.00748522, 0.00755848, 0.00718764, + 0.00699057, 0.00689327, 0.00674753, 0.00671624, 0.00751943, 0.00741207, + 0.00676514] + [0.485, 0.456, 0.406] + self.std = [0.00035424, 0.00053509, 0.0009189, 0.00122868, 0.00164547, 0.00186258, + 0.00224559, 0.00286002, 0.0030474, 0.00315195, 0.00353866, 0.00406267, + 0.0055249, 0.00622435, 0.00500298, 0.00480104, 0.0052598, 0.00571489, + 0.00601454, 0.00659049, 0.00634349, 0.00530685, 0.00537778, 0.00513787, + 0.00498475, 0.00488729, 0.00471964, 0.00454973, 0.00490581, 0.0046964, + 0.00421346] + [0.229, 0.224, 0.225] + self.max_val = 1.0 + self.min_val = 0.0 + self.bands = 31 + + elif self.dataset_type == 'umri2015': + # UMRI2015 dataset parameters (33 bands) + self.mean = [0.00049507, 0.00077369, 0.00086868, 0.00092949, 0.00106588, 0.00134611, + 0.00148952, 0.00138134, 0.00147178, 0.00140757, 0.00146943, 0.0014896, + 0.00158795, 0.0017375, 0.00171897, 0.00186404, 0.00182205, 0.00166717, + 0.00176569, 0.00172996, 0.00177187, 0.00178079, 0.00172655, 0.00166295, + 0.00167107, 0.0016319, 0.00167044, 0.00166259, 0.00153768, 0.0013869, + 0.00148293, 0.0015571, 0.00129303] + [0.485, 0.456, 0.406] + self.std = [0.0004163, 0.00053372, 0.00057629, 0.00060292, 0.00068114, 0.00085653, + 0.00095103, 0.0008941, 0.00095387, 0.00092446, 0.00096502, 0.00096958, + 0.00102551, 0.00111695, 0.00109679, 0.00118504, 0.00117788, 0.00107841, + 0.00114765, 0.00113261, 0.00116322, 0.00116857, 0.0011256, 0.0010963, + 0.00110381, 0.00108571, 0.00111103, 0.00111677, 0.00103602, 0.00092566, + 0.0009724, 0.00101692, 0.00085337] + [0.229, 0.224, 0.225] + self.max_val = 795.4633697273729 + self.min_val = -1.2406029247200091e-05 + self.bands = 33 + + elif self.dataset_type == 'umemm': + self.mean = [0.01173168, 0.01234073, 0.01300494, 0.01367329, 0.01436883, 0.0151207, + 0.0155524, 0.01612679, 0.01647242, 0.0169334, 0.01737261, 0.01776505, + 0.01821689, 0.01851488, 0.01895346, 0.01905013, 0.01976628, 0.02014966, + 0.02034537, 0.02077717, 0.02100478, 0.02121398, 0.0215768, 0.02184028, + 0.02216735, 0.02231407, 0.02260189, 0.02286339, 0.02325497, 0.0233728, + 0.02365622, 0.02380282, 0.02444496] + [0.485, 0.456, 0.406] + self.std = [0.00483212, 0.00528087, 0.00574404, 0.00611767, 0.00647407, 0.00695638, + 0.0072416, 0.00756005, 0.00780453, 0.00815911, 0.00851377, 0.00878704, + 0.00913599, 0.0093712, 0.0096884, 0.00983615, 0.01027443, 0.01053299, + 0.01056043, 0.01087872, 0.01099751, 0.01115679, 0.01137956, 0.01154608, + 0.01175272, 0.01184787, 0.01195576, 0.01215307, 0.0123245, 0.01232338, + 0.01237378, 0.01234926, 0.01252923] + [0.229, 0.224, 0.225] + self.max_val = 4.380079501083187 + self.min_val = -0.08767047645618645 + self.bands = 33 + + elif self.dataset_type == 'hyperblood': + # HyperBlood dataset parameters (113 bands) + self.mean = [0.11792768, 0.12286566, 0.13354243, 0.12907951, 0.09845191, 0.13444436, + 0.14597324, 0.14484807, 0.12660842, 0.08799646, 0.11882777, 0.13161479, + 0.10589161, 0.09883164, 0.08022733, 0.09555449, 0.10218862, 0.09988686, + 0.09676628, 0.08561739, 0.1227139, 0.13198491, 0.13013612, 0.12793193, + 0.09031978] + [0.485, 0.456, 0.406] + self.std = [0.06492269, 0.06635557, 0.07162475, 0.07012394, 0.05701815, 0.07323762, + 0.0766644, 0.07810237, 0.07141274, 0.05436147, 0.06862938, 0.07280301, + 0.0626632, 0.05946415, 0.05017714, 0.05620537, 0.0591019, 0.05838145, + 0.05704834, 0.05148091, 0.06747658, 0.07073647, 0.07083215, 0.07006211, + 0.05280771] + [0.229, 0.224, 0.225] + self.max_val = 4.0 + self.min_val = 0.0 + self.bands = 113 + + elif self.dataset_type == 'hsidrive20': + self.mean = [0.11792768, 0.12286566, 0.13354243, 0.12907951, 0.09845191, 0.13444436, + 0.14597324, 0.14484807, 0.12660842, 0.08799646, 0.11882777, 0.13161479, + 0.10589161, 0.09883164, 0.08022733, 0.09555449, 0.10218862, 0.09988686, + 0.09676628, 0.08561739, 0.1227139, 0.13198491, 0.13013612, 0.12793193, + 0.09031978] + [0.485, 0.456, 0.406] + self.std = [0.06492269, 0.06635557, 0.07162475, 0.07012394, 0.05701815, 0.07323762, + 0.0766644, 0.07810237, 0.07141274, 0.05436147, 0.06862938, 0.07280301, + 0.0626632, 0.05946415, 0.05017714, 0.05620537, 0.0591019, 0.05838145, + 0.05704834, 0.05148091, 0.06747658, 0.07073647, 0.07083215, 0.07006211, + 0.05280771] + [0.229, 0.224, 0.225] + self.max_val = 4.0 + self.min_val = 0.0 + self.bands = 25 + + elif self.dataset_type == 'hotrednir': + self.mean = [0.28415901, 0.21461861, 0.18719398, 0.19470588, 0.20235114, 0.20367749, + 0.2163216, 0.21995637, 0.2168878, 0.20578036, 0.20192309, 0.217628, + 0.17708894, 0.17544539, 0.16722978] + [0.485, 0.456, 0.406] + self.std = [0.2247296, 0.17951354, 0.15692467, 0.15598073, 0.16016452, 0.15911849, + 0.16180973, 0.15985215, 0.15849979, 0.15031793, 0.146697, 0.14847991, + 0.13463819, 0.13324966, 0.12782383] + [0.229, 0.224, 0.225] + self.max_val = 254.0 + self.min_val = 0.0 + self.bands = 15 + + elif self.dataset_type == 'arad_1k_31': + # ARAD_1K_31 dataset parameters (31 bands) + self.mean = [0.00050713, 0.00070553, 0.0011365, 0.00149156, 0.00197441, 0.00223908, + 0.00271003, 0.00345612, 0.00369303, 0.00385219, 0.00435618, 0.00506823, + 0.0070418, 0.00800666, 0.0064554, 0.00628767, 0.00703461, 0.00775983, + 0.00832022, 0.00929337, 0.00898094, 0.00748522, 0.00755848, 0.00718764, + 0.00699057, 0.00689327, 0.00674753, 0.00671624, 0.00751943, 0.00741207, + 0.00676514] + [0.485, 0.456, 0.406] + self.std = [0.00035424, 0.00053509, 0.0009189, 0.00122868, 0.00164547, 0.00186258, + 0.00224559, 0.00286002, 0.0030474, 0.00315195, 0.00353866, 0.00406267, + 0.0055249, 0.00622435, 0.00500298, 0.00480104, 0.0052598, 0.00571489, + 0.00601454, 0.00659049, 0.00634349, 0.00530685, 0.00537778, 0.00513787, + 0.00498475, 0.00488729, 0.00471964, 0.00454973, 0.00490581, 0.0046964, + 0.00421346] + [0.229, 0.224, 0.225] + self.max_val = 1.0 + self.min_val = 0.0 + self.bands = 31 + + elif self.dataset_type == 'arad_1k_16': + # ARAD_1K_16 dataset parameters (16 bands) + self.mean = [0.00050713, 0.00070553, 0.0011365, 0.00149156, 0.00197441, 0.00223908, + 0.00271003, 0.00345612, 0.00369303, 0.00385219, 0.00435618, 0.00506823, + 0.0070418, 0.00800666, 0.0064554, 0.00628767] + [0.485, 0.456, 0.406] + self.std = [0.00035424, 0.00053509, 0.0009189, 0.00122868, 0.00164547, 0.00186258, + 0.00224559, 0.00286002, 0.0030474, 0.00315195, 0.00353866, 0.00406267, + 0.0055249, 0.00622435, 0.00500298, 0.00480104] + [0.229, 0.224, 0.225] + self.max_val = 1.0 + self.min_val = 0.0 + self.bands = 16 + + elif self.dataset_type == 'cave': + # CAVE dataset parameters (31 bands) + self.mean = [0.00050713, 0.00070553, 0.0011365, 0.00149156, 0.00197441, 0.00223908, + 0.00271003, 0.00345612, 0.00369303, 0.00385219, 0.00435618, 0.00506823, + 0.0070418, 0.00800666, 0.0064554, 0.00628767, 0.00703461, 0.00775983, + 0.00832022, 0.00929337, 0.00898094, 0.00748522, 0.00755848, 0.00718764, + 0.00699057, 0.00689327, 0.00674753, 0.00671624, 0.00751943, 0.00741207, + 0.00676514] + [0.485, 0.456, 0.406] + self.std = [0.00035424, 0.00053509, 0.0009189, 0.00122868, 0.00164547, 0.00186258, + 0.00224559, 0.00286002, 0.0030474, 0.00315195, 0.00353866, 0.00406267, + 0.0055249, 0.00622435, 0.00500298, 0.00480104, 0.0052598, 0.00571489, + 0.00601454, 0.00659049, 0.00634349, 0.00530685, 0.00537778, 0.00513787, + 0.00498475, 0.00488729, 0.00471964, 0.00454973, 0.00490581, 0.0046964, + 0.00421346] + [0.229, 0.224, 0.225] + self.max_val = 1.0 + self.min_val = 0.0 + self.bands = 31 + + elif self.dataset_type == 'icvl': + # ICVL dataset parameters (31 bands) + self.mean = [0.00050713, 0.00070553, 0.0011365, 0.00149156, 0.00197441, 0.00223908, + 0.00271003, 0.00345612, 0.00369303, 0.00385219, 0.00435618, 0.00506823, + 0.0070418, 0.00800666, 0.0064554, 0.00628767, 0.00703461, 0.00775983, + 0.00832022, 0.00929337, 0.00898094, 0.00748522, 0.00755848, 0.00718764, + 0.00699057, 0.00689327, 0.00674753, 0.00671624, 0.00751943, 0.00741207, + 0.00676514] + [0.485, 0.456, 0.406] + self.std = [0.00035424, 0.00053509, 0.0009189, 0.00122868, 0.00164547, 0.00186258, + 0.00224559, 0.00286002, 0.0030474, 0.00315195, 0.00353866, 0.00406267, + 0.0055249, 0.00622435, 0.00500298, 0.00480104, 0.0052598, 0.00571489, + 0.00601454, 0.00659049, 0.00634349, 0.00530685, 0.00537778, 0.00513787, + 0.00498475, 0.00488729, 0.00471964, 0.00454973, 0.00490581, 0.0046964, + 0.00421346] + [0.229, 0.224, 0.225] + self.max_val = 1.0 + self.min_val = 0.0 + self.bands = 31 + + elif self.dataset_type == 'hs_sod': + # HSSOD dataset parameters (81 bands) + self.mean = [0.00505788, 0.00601034, 0.00747643, 0.00959971, 0.0147855, 0.01898453, + 0.0239441, 0.03211231, 0.03791218, 0.04520133, 0.04938109, 0.05594452, + 0.06514561, 0.07837064, 0.08795061, 0.10231026, 0.1106684, 0.12345689, + 0.13252559, 0.14111, 0.15414085, 0.16602382, 0.16550444, 0.1745532, + 0.18869128, 0.19148134, 0.19939337, 0.20783469, 0.20828562, 0.21840917, + 0.23144286, 0.24558449, 0.25482584, 0.25775317, 0.26426578, 0.27155495, + 0.27239095, 0.2683785, 0.26598797, 0.26503738, 0.26443645, 0.26481411, + 0.25628452, 0.2493137, 0.25782899, 0.26621533, 0.26577412, 0.26109554, + 0.26062482, 0.26170838, 0.25086012, 0.24544579, 0.2453043, 0.24627007, + 0.23747638, 0.22964289, 0.22108862, 0.22013535, 0.2160363, 0.21200803, + 0.21234002, 0.20738988, 0.18760026, 0.17716606, 0.18474978, 0.20061198, + 0.2190922, 0.23057194, 0.20136807, 0.18552641, 0.18074632, 0.20211651, + 0.22420212, 0.25190136, 0.26552015, 0.26589699, 0.23496681, 0.15726452, + 0.18386361, 0.22457717, 0.23622217] + [0.485, 0.456, 0.406] + self.std = [0.00335335, 0.00379358, 0.00453958, 0.0057187, 0.00848124, 0.01070781, + 0.01339494, 0.01787782, 0.02111595, 0.02536344, 0.02784967, 0.03205192, + 0.03756858, 0.04570729, 0.05158716, 0.06053343, 0.06596695, 0.07434336, + 0.08030715, 0.0860997, 0.09462209, 0.10215146, 0.10232753, 0.10816608, + 0.11646034, 0.11808529, 0.12236777, 0.12631026, 0.12541599, 0.12993119, + 0.13554931, 0.14209915, 0.14627095, 0.14776726, 0.1509073, 0.15434794, + 0.15478504, 0.15323047, 0.15261152, 0.15322816, 0.15360044, 0.15428015, + 0.1509565, 0.14847103, 0.15334979, 0.15741342, 0.1573434, 0.15556864, + 0.15630692, 0.15746275, 0.15289239, 0.1505807, 0.15081839, 0.15202881, + 0.14851399, 0.1455947, 0.14142634, 0.14174904, 0.14012646, 0.13851422, + 0.13887505, 0.13566844, 0.12321144, 0.11449433, 0.11628917, 0.12220737, + 0.1309691, 0.13637021, 0.12087113, 0.112728, 0.11086555, 0.12307407, + 0.13483802, 0.14899566, 0.15559294, 0.15502698, 0.13857946, 0.09519617, + 0.10987266, 0.13104544, 0.13648109] + [0.229, 0.224, 0.225] + self.max_val = 4095.0 + self.min_val = 0.0 + self.bands = 81 + + elif self.dataset_type == 'hsodbit_v2': + # HSODBIT-V2 dataset parameters (31 bands) + self.mean = [0.00050713, 0.00070553, 0.0011365, 0.00149156, 0.00197441, 0.00223908, + 0.00271003, 0.00345612, 0.00369303, 0.00385219, 0.00435618, 0.00506823, + 0.0070418, 0.00800666, 0.0064554, 0.00628767, 0.00703461, 0.00775983, + 0.00832022, 0.00929337, 0.00898094, 0.00748522, 0.00755848, 0.00718764, + 0.00699057, 0.00689327, 0.00674753, 0.00671624, 0.00751943, 0.00741207, + 0.00676514] + [0.485, 0.456, 0.406] + self.std = [0.00035424, 0.00053509, 0.0009189, 0.00122868, 0.00164547, 0.00186258, + 0.00224559, 0.00286002, 0.0030474, 0.00315195, 0.00353866, 0.00406267, + 0.0055249, 0.00622435, 0.00500298, 0.00480104, 0.0052598, 0.00571489, + 0.00601454, 0.00659049, 0.00634349, 0.00530685, 0.00537778, 0.00513787, + 0.00498475, 0.00488729, 0.00471964, 0.00454973, 0.00490581, 0.0046964, + 0.00421346] + [0.229, 0.224, 0.225] + self.max_val = 1.0 + self.min_val = 0.0 + self.bands = 31 + + elif self.dataset_type == 'vnihdhiatlimafb': + # VNIHDHIATLIMAFB dataset parameters (204 bands) + self.mean = [0.11792768, 0.12286566, 0.13354243, 0.12907951, 0.09845191, 0.13444436, + 0.14597324, 0.14484807, 0.12660842, 0.08799646, 0.11882777, 0.13161479, + 0.10589161, 0.09883164, 0.08022733, 0.09555449, 0.10218862, 0.09988686, + 0.09676628, 0.08561739, 0.1227139, 0.13198491, 0.13013612, 0.12793193, + 0.09031978] + [0.485, 0.456, 0.406] # Placeholder for 204 bands + self.std = [0.06492269, 0.06635557, 0.07162475, 0.07012394, 0.05701815, 0.07323762, + 0.0766644, 0.07810237, 0.07141274, 0.05436147, 0.06862938, 0.07280301, + 0.0626632, 0.05946415, 0.05017714, 0.05620537, 0.0591019, 0.05838145, + 0.05704834, 0.05148091, 0.06747658, 0.07073647, 0.07083215, 0.07006211, + 0.05280771] + [0.229, 0.224, 0.225] # Placeholder for 204 bands + self.max_val = 6.7395835 + self.min_val = 0.0 + self.bands = 204 + + elif self.dataset_type == 'deephsnir': + # DeepHSNIR dataset parameters (252 bands) + self.mean = [0.31596533, 0.31582026, 0.31591017, 0.31598633, 0.31596835, 0.31598215, + 0.31601244, 0.31609212, 0.31615184, 0.31636028, 0.31626798, 0.31632993, + 0.31630893, 0.31629821, 0.31628198, 0.31629123, 0.31628992, 0.31628988, + 0.31629121, 0.31629341, 0.31629719, 0.31630189, 0.31630792, 0.31631442, + 0.31632174, 0.31632916, 0.31633725, 0.31634579, 0.31635505, 0.31636362, + 0.31637288, 0.31638203, 0.31639112, 0.31640022, 0.31640956, 0.31641804, + 0.3164259, 0.31643368, 0.31644078, 0.31644723, 0.31645304, 0.31645748, + 0.31646186, 0.31646554, 0.31646728, 0.3164684, 0.31646862, 0.31646795, + 0.31646639, 0.31646393, 0.31646071, 0.31645649, 0.3164517, 0.31644626, + 0.31643993, 0.3164326, 0.31642488, 0.31641591, 0.316406, 0.31639471, + 0.31638239, 0.3163689, 0.31635382, 0.31633678, 0.3163173, 0.31629476, + 0.31626924, 0.31624086, 0.31621267, 0.31618586, 0.31616282, 0.31614348, + 0.31612933, 0.31611873, 0.31611115, 0.31610538, 0.31610125, 0.3160978, + 0.31609544, 0.31609292, 0.31609089, 0.31608857, 0.31608667, 0.31608452, + 0.31608326, 0.31608272, 0.31608313, 0.31608345, 0.31608475, 0.31608608, + 0.31608797, 0.31609013, 0.31609267, 0.31609534, 0.31609833, 0.31610108, + 0.31610388, 0.3161063, 0.31610849, 0.31611045, 0.3161125, 0.31611421, + 0.31611564, 0.31611635, 0.31611742, 0.31611747, 0.31611709, 0.31611633, + 0.31611496, 0.31611284, 0.3161104, 0.31610654, 0.31610262, 0.31609754, + 0.31609167, 0.31608465, 0.31607718, 0.31606815, 0.3160589, 0.31604863, + 0.3160373, 0.3160252, 0.3160125, 0.31599887, 0.31598522, 0.31597137, + 0.31595758, 0.31594364, 0.31593029, 0.31591749, 0.31590532, 0.31589336, + 0.31588242, 0.31587171, 0.31586104, 0.31584994, 0.31583816, 0.31582486, + 0.3158098, 0.31579286, 0.31577426, 0.31575404, 0.31573181, 0.31570692, + 0.31568126, 0.31565632, 0.31563368, 0.31561237, 0.31559422, 0.31557927, + 0.31556712, 0.31555746, 0.31554977, 0.31554326, 0.31553813, 0.31553397, + 0.31553063, 0.31552774, 0.31552526, 0.31552339, 0.31552228, 0.315521, + 0.31552015, 0.31551944, 0.31551878, 0.31551817, 0.31551761, 0.31551709, + 0.31551661, 0.31551617, 0.31551576, 0.31551538, 0.31551503, 0.31551471, + 0.31551441, 0.31551414, 0.31551389, 0.31551366, 0.31551345, 0.31551326, + 0.31551309, 0.31551294, 0.3155128, 0.31551268, 0.31551257, 0.31551248, + 0.3155124, 0.31551233, 0.31551227, 0.31551222, 0.31551218, 0.31551215, + 0.31551213, 0.31551211, 0.3155121, 0.31551209, 0.31551209, 0.31551209, + 0.3155121, 0.31551211, 0.31551213, 0.31551215, 0.31551218, 0.31551222, + 0.31551227, 0.31551233, 0.3155124, 0.31551248, 0.31551257, 0.31551268, + 0.3155128, 0.31551294, 0.31551309, 0.31551326, 0.31551345, 0.31551366, + 0.31551389, 0.31551414, 0.31551441, 0.31551471, 0.31551503, 0.31551538, + 0.31551576, 0.31551617, 0.31551661, 0.31551709, 0.31551761, 0.31551817, + 0.31551878, 0.31551944, 0.31552015, 0.315521, 0.31552228, 0.31552339, + 0.31552526, 0.31552774, 0.31553063, 0.31553397, 0.31553813, 0.31554326, + 0.31554977, 0.31555746, 0.31556712, 0.31557927, 0.31559422, 0.31561237, + 0.31563368, 0.31565632, 0.31568126, 0.31570692, 0.31573181, 0.31575404, + 0.31577426, 0.31579286, 0.3158098, 0.31582486, 0.31583816, 0.31584994, + 0.31586104, 0.31587171, 0.31588242, 0.31589336, 0.31590532, 0.31591749, + 0.31593029, 0.31594364, 0.31595758, 0.31597137, 0.31598522, 0.31599887, + 0.3160125, 0.3160252, 0.3160373, 0.31604863, 0.3160589, 0.31606815, + 0.31607718, 0.31608465, 0.31609167, 0.31609754, 0.31610262, 0.31610654, + 0.3161104, 0.31611284, 0.31611496, 0.31611633, 0.31611709, 0.31611747, + 0.31611742, 0.31611635, 0.31611564, 0.31611421, 0.3161125, 0.31611045, + 0.31610849, 0.3161063, 0.31610388, 0.31610108, 0.31609833, 0.31609534, + 0.31609267, 0.31609013, 0.31608797, 0.31608608, 0.31608475, 0.31608345, + 0.31608313, 0.31608272, 0.31608326, 0.31608452, 0.31608667, 0.31608857, + 0.31609089, 0.31609292, 0.31609544, 0.3160978, 0.31610125, 0.31610538, + 0.31611115, 0.31611873, 0.31612933, 0.31614348, 0.31616282, 0.31618586, + 0.31621267, 0.31624086, 0.31626924, 0.31629476, 0.3163173, 0.31633678, + 0.31635382, 0.3163689, 0.31638239, 0.31639471, 0.316406, 0.31641591, + 0.31642488, 0.3164326, 0.31643993, 0.31644626, 0.3164517, 0.31645649, + 0.31646071, 0.31646393, 0.31646639, 0.31646795, 0.31646862, 0.3164684, + 0.31646728, 0.31646554, 0.31646186, 0.31645748, 0.31645304, 0.31644723, + 0.31644078, 0.31643368, 0.3164259, 0.31641804, 0.31640956, 0.31640022, + 0.31639112, 0.31638203, 0.31637288, 0.31636362, 0.31635505, 0.31634579, + 0.31633725, 0.31632916, 0.31632174, 0.31631442, 0.31630792, 0.31630189, + 0.31629719, 0.31629341, 0.31629121, 0.31628988, 0.31628992, 0.31629123, + 0.31628198, 0.31629821, 0.31630893, 0.31632993, 0.31626798, 0.31636028, + 0.31615184, 0.31609212, 0.31601244, 0.31598215, 0.31596835, 0.31598633, + 0.31591017, 0.31582026, 0.31596533] + [0.485, 0.456, 0.406] + self.std = [0.00079037, 0.0007425, 0.00065591, 0.00051521, 0.00042861, 0.00035781, + 0.00030852, 0.00027553, 0.00024972, 0.00023215, 0.00021762, 0.00020285, + 0.00019168, 0.00018386, 0.0001759, 0.00017044, 0.00016426, 0.00016082, + 0.00015763, 0.00015393, 0.00015311, 0.00015134, 0.00014883, 0.00014749, + 0.00014741, 0.00014516, 0.00014332, 0.00014341, 0.00014184, 0.00014089, + 0.00014032, 0.00014022, 0.00013943, 0.00014008, 0.00014015, 0.00014017, + 0.00014134, 0.0001425, 0.00014354, 0.00014468, 0.00014716, 0.00015027, + 0.00015342, 0.00015756, 0.00016252, 0.00016839, 0.00017464, 0.00018131, + 0.00018895, 0.00019656, 0.00020385, 0.00021131, 0.00021835, 0.00022541, + 0.00023273, 0.00023976, 0.00024745, 0.00025497, 0.00026362, 0.00027079, + 0.00027759, 0.00028338, 0.00028929, 0.00029449, 0.00029914, 0.00030325, + 0.00030718, 0.00031107, 0.00031513, 0.00031871, 0.00032228, 0.00032645, + 0.00033152, 0.00033614, 0.00034014, 0.00034409, 0.00034907, 0.00035414, + 0.00035885, 0.00036213, 0.00036416, 0.00036582, 0.00036737, 0.00036871, + 0.00037023, 0.00037181, 0.00037464, 0.00037864, 0.00038216, 0.00038387, + 0.00038331, 0.0003815, 0.00037921, 0.00037672, 0.00037407, 0.00037124, + 0.00036876, 0.0003665, 0.00036421, 0.00036161, 0.00035823, 0.00035554, + 0.00035111, 0.00034814, 0.00034807, 0.00035138, 0.00035852, 0.00036978, + 0.00038696, 0.00040979, 0.00043873, 0.00047688, 0.00052208, 0.00057209, + 0.00062645, 0.00067932, 0.00072609, 0.00076801, 0.00080663, 0.0008454, + 0.0008833, 0.0009198, 0.0009528, 0.00098305, 0.00101078, 0.00103879, + 0.0010646, 0.00108751, 0.00110426, 0.00111807, 0.00113049, 0.00114154, + 0.00115239, 0.0011625, 0.00117243, 0.00118141, 0.00118918, 0.00119544, + 0.00120023, 0.00120341, 0.00120584, 0.0012085, 0.00121261, 0.00121765, + 0.0012236, 0.00122975, 0.00123565, 0.00124077, 0.0012446, 0.0012474, + 0.00124991, 0.00125278, 0.00125682, 0.0012612, 0.00126572, 0.00127012, + 0.00127315, 0.00127535, 0.00127643, 0.0012759, 0.0012735, 0.00127003, + 0.00126723, 0.00126586, 0.00126587, 0.0012669, 0.00126801, 0.00126928, + 0.00127057, 0.00127182, 0.0012726, 0.00127326, 0.00127344, 0.00127358, + 0.00127316, 0.00127243, 0.00127118, 0.00127005, 0.00126892, 0.00126813, + 0.00126719, 0.00126615, 0.00126527, 0.00126412, 0.00126246, 0.00126066, + 0.00125855, 0.00125606, 0.00125331, 0.00124968, 0.00124578, 0.00124186, + 0.00123847, 0.00123427, 0.00122877, 0.00122099, 0.00121079, 0.00120015, + 0.00118775, 0.00117478, 0.00116004, 0.00114472, 0.00112692, 0.00110748, + 0.00108788, 0.00106712, 0.00104644, 0.00102789, 0.00101468, 0.00100716, + 0.00100281, 0.00099826, 0.00099611, 0.00099268, 0.00099213, 0.00099252, + 0.00099448, 0.00099648, 0.00099991, 0.00100328, 0.00100812, 0.00101217, + 0.00101756, 0.00102464] + [0.229, 0.224, 0.225] + self.max_val = 1.0 + self.min_val = -0.091662824 + self.bands = 249 + + elif self.dataset_type == 'deephsvis': + # DeepHSVIS dataset parameters (249 bands) + self.mean = [0.31596533] * 249 + [0.485, 0.456, 0.406] # Placeholder values + self.std = [0.00079012] * 249 + [0.229, 0.224, 0.225] # Placeholder values + self.max_val = 1.0 + self.min_val = -0.091662824 + self.bands = 249 + + elif self.dataset_type == 'deephsviscor': + # DeepHSVISCOR dataset parameters (249 bands) + self.mean = [0.31596533] * 249 + [0.485, 0.456, 0.406] # Placeholder values + self.std = [0.00079012] * 249 + [0.229, 0.224, 0.225] # Placeholder values + self.max_val = 1.0 + self.min_val = -0.091662824 + self.bands = 249 + + elif self.dataset_type == 'hsodbitv2': + # HSODBITV2 dataset parameters (200 bands) + self.mean = [0.00858756] * 200 + [0.485, 0.456, 0.406] # Placeholder values + self.std = [0.00751322] * 200 + [0.229, 0.224, 0.225] # Placeholder values + self.max_val = 2.0 + self.min_val = 0.0 + self.bands = 200 + + elif self.dataset_type == 'hotvis': + # HOTVIS dataset parameters (16 bands) + self.mean = [0.17354311, 0.16689073, 0.14970031, 0.14982351, 0.17244257, 0.16725978, + 0.17544793, 0.18323516, 0.16343771, 0.18044153, 0.18598581, 0.1752639, + 0.17251257, 0.20304256, 0.19737918, 0.20113443] + [0.485, 0.456, 0.406] + self.std = [0.14717741, 0.14833903, 0.14008888, 0.14012565, 0.14750255, 0.14482089, + 0.1488135, 0.14891803, 0.14469542, 0.14839285, 0.14959444, 0.136904, + 0.14140587, 0.14981111, 0.14334199, 0.15056744] + [0.229, 0.224, 0.225] + self.max_val = 254 + self.min_val = 0 + self.bands = 16 + + elif self.dataset_type == 'hotnir': + # HOTNIR dataset parameters (128 bands) + self.mean = [0.17354311] * 128 + [0.485, 0.456, 0.406] # Placeholder values + self.std = [0.00202992] * 128 + [0.229, 0.224, 0.225] # Placeholder values + self.max_val = 2.742662 + self.min_val = -1.432596 + self.bands = 128 + + elif self.dataset_type == 'hsiroad': + # HSIROAD dataset parameters (128 bands) + self.mean = [0.17354311] * 128 + [0.485, 0.456, 0.406] # Placeholder values + self.std = [0.00202992] * 128 + [0.229, 0.224, 0.225] # Placeholder values + self.max_val = 2.742662 + self.min_val = -1.432596 + self.bands = 128 + + elif self.dataset_type == 'hyperspectralcityv2': + # hyperspectralcityv2 dataset parameters (128 bands) + self.mean = [0.17354311] * 128 + [0.485, 0.456, 0.406] # Placeholder values + self.std = [0.00202992] * 128 + [0.229, 0.224, 0.225] # Placeholder values + self.max_val = 2.742662 + self.min_val = -1.432596 + self.bands = 128 + + elif self.dataset_type == 'hykov2nir': + # hykov2nir dataset parameters (25 bands) + self.mean = [0.1] * 25 + [0.485, 0.456, 0.406] # Placeholder values + self.std = [0.05] * 25 + [0.229, 0.224, 0.225] # Placeholder values + self.max_val = 1.0 + self.min_val = 0.0 + self.bands = 25 + + elif self.dataset_type == 'hykov2vis': + # hykov2vis dataset parameters (15 bands) + self.mean = [0.1] * 15 + [0.485, 0.456, 0.406] # Placeholder values + self.std = [0.05] * 15 + [0.229, 0.224, 0.225] # Placeholder values + self.max_val = 1.0 + self.min_val = 0.0 + self.bands = 15 + + elif self.dataset_type == 'hyperdrive': + # Hyperdrive dataset parameters (128 bands) + self.mean = [0.17354311] * 128 + [0.485, 0.456, 0.406] # Placeholder values + self.std = [0.00202992] * 128 + [0.229, 0.224, 0.225] # Placeholder values + self.max_val = 2.742662 + self.min_val = -1.432596 + self.bands = 128 + + elif self.dataset_type == 'hyperdrivevnir': + # HyperdriveVNIR dataset parameters (128 bands) + self.mean = [0.17354311] * 128 + [0.485, 0.456, 0.406] # Placeholder values + self.std = [0.00202992] * 128 + [0.229, 0.224, 0.225] # Placeholder values + self.max_val = 2.742662 + self.min_val = -1.432596 + self.bands = 128 + + elif self.dataset_type == 'hyperdriveswir': + # HyperdriveSWIR dataset parameters (128 bands) + self.mean = [0.17354311] * 128 + [0.485, 0.456, 0.406] # Placeholder values + self.std = [0.00202992] * 128 + [0.229, 0.224, 0.225] # Placeholder values + self.max_val = 2.742662 + self.min_val = -1.432596 + self.bands = 128 + + elif self.dataset_type == 'libhsi': + # LIBHSI dataset parameters (204 bands) + self.mean = [0.1] * 204 + [0.485, 0.456, 0.406] # Placeholder values + self.std = [0.05] * 204 + [0.229, 0.224, 0.225] # Placeholder values + self.max_val = 1.0 + self.min_val = 0.0 + self.bands = 204 + + elif self.dataset_type == 'virginia_tech_tree': + # VirginiaTechTrees dataset parameters (420 bands) + self.mean = [0.1] * 420 + [0.485, 0.456, 0.406] # Placeholder values + self.std = [0.05] * 420 + [0.229, 0.224, 0.225] # Placeholder values + self.max_val = 65535.0 + self.min_val = 0.0 + self.bands = 420 + + elif self.dataset_type == 'fiftyoutdoor': + # FiftyOutdoor dataset parameters (33 bands) + self.mean = [0.5] * 33 + [0.485, 0.456, 0.406] # 33 HSI bands + 3 RGB bands + self.std = [0.5] * 33 + [0.229, 0.224, 0.225] # 33 HSI bands + 3 RGB bands + self.max_val = 1.0 + self.min_val = 0.0 + self.bands = 33 + + elif self.dataset_type == 'aphid': + # APHID (Agricultural plant hyperspectral imaging dataset) parameters (237 bands) + self.mean = [0.01749677, 0.01863154, 0.01968502, 0.02096651, 0.0222703, 0.02343416, + 0.02486456, 0.02623226, 0.02711628, 0.02806029, 0.029251, 0.03039208, + 0.03149611, 0.0324034, 0.03310641, 0.03367099, 0.03440539, 0.03559069, + 0.03706571, 0.03864252, 0.04023792, 0.04108739, 0.04091695, 0.04059534, + 0.04176284, 0.04384956, 0.04603461, 0.04808683, 0.04970166, 0.05056294, + 0.05120134, 0.05231753, 0.05404492, 0.05613217, 0.05841183, 0.06040159, + 0.06176928, 0.06352201, 0.06672157, 0.07070624, 0.07452483, 0.07856132, + 0.08336198, 0.08813702, 0.09218899, 0.0957341, 0.09813736, 0.09948482, + 0.10089726, 0.10222418, 0.10359852, 0.10576257, 0.10874553, 0.1115804, + 0.11350075, 0.11437227, 0.11461496, 0.11388246, 0.11216935, 0.11024847, + 0.1088342, 0.1087843, 0.1095063, 0.11013955, 0.11095031, 0.11238496, + 0.11351851, 0.11270449, 0.10897382, 0.10531164, 0.10361046, 0.10310593, + 0.10363231, 0.10527451, 0.107754, 0.11062107, 0.11306273, 0.11433087, + 0.11441181, 0.11306909, 0.110761, 0.10861859, 0.10717231, 0.10603203, + 0.10528735, 0.10519255, 0.10547309, 0.10642145, 0.10789556, 0.10951177, + 0.11057608, 0.11080275, 0.11043563, 0.10899756, 0.10621833, 0.10343582, + 0.10152958, 0.09933766, 0.09696239, 0.09659571, 0.09835973, 0.09998306, + 0.10117153, 0.10197631, 0.10239724, 0.10213523, 0.10149442, 0.10068651, + 0.09948141, 0.09803665, 0.09656651, 0.09445546, 0.09231605, 0.09290426, + 0.09721154, 0.10396054, 0.11291141, 0.12304567, 0.13413498, 0.14725136, + 0.16233688, 0.17846247, 0.19488951, 0.20931178, 0.21713638, 0.21432398, + 0.21035695, 0.21707963, 0.22783414, 0.23649397, 0.24813107, 0.26640504, + 0.29275966, 0.32234601, 0.34856743, 0.37127585, 0.39328289, 0.41307188, + 0.4276742, 0.4356971, 0.43781677, 0.43502193, 0.42373551, 0.39014824, + 0.32058243, 0.25648081, 0.24593042, 0.27940771, 0.32313044, 0.35244421, + 0.3646437, 0.36728434, 0.36622976, 0.36283905, 0.35801778, 0.35183559, + 0.34352493, 0.33310404, 0.32312864, 0.31559416, 0.30912014, 0.30196878, + 0.29375823, 0.28506906, 0.27649879, 0.26673254, 0.25346453, 0.23533093, + 0.21329628, 0.19368162, 0.1830368, 0.17975254, 0.17868787, 0.17938373, + 0.18064577, 0.18095194, 0.18175849, 0.18480291, 0.18925455, 0.19289429, + 0.19460079, 0.19428892, 0.19203493, 0.18722012, 0.17995, 0.1717305, + 0.16454595, 0.15969452, 0.15656967, 0.15329931, 0.14871182, 0.14348243, + 0.13973992, 0.13788484, 0.13644798, 0.13451014, 0.13252546, 0.13048483, + 0.1283227, 0.12643253, 0.124531, 0.12215579, 0.1183463, 0.11226351, + 0.10376037, 0.0947622, 0.08802142, 0.08586727, 0.08575157, 0.0836123, + 0.07931947, 0.07523115, 0.07192349, 0.06935133, 0.06830636, 0.06826021, + 0.06710699, 0.06376308, 0.05800961, 0.05036524, 0.04200856, 0.03558817, + 0.03223782, 0.03177794, 0.03210223, 0.03172927, 0.03087431, 0.03024037, + 0.02975344, 0.02941706, 0.0293257, 0.02927379, 0.0292441, 0.02950881, + 0.03002286, 0.03068394, 0.03161591] + [0.485, 0.456, 0.406] + self.std = [0.01152971, 0.01246639, 0.0133121, 0.01436954, 0.01541135, 0.01638534, + 0.01757471, 0.01858997, 0.01925267, 0.02002466, 0.02094319, 0.02179194, + 0.02270399, 0.02341295, 0.02388981, 0.02430273, 0.02488912, 0.0258316, + 0.02695783, 0.02815591, 0.02925099, 0.02986218, 0.02970572, 0.02945916, + 0.03035832, 0.0318107, 0.03328634, 0.0347459, 0.03576967, 0.03619796, + 0.03647458, 0.03704743, 0.03800565, 0.03917259, 0.04039074, 0.0413286, + 0.04171075, 0.04219915, 0.04369529, 0.04580031, 0.0479429, 0.05019833, + 0.05293343, 0.05563171, 0.05788512, 0.05989067, 0.06113891, 0.06171445, + 0.06234663, 0.06307677, 0.06400757, 0.06546068, 0.06730459, 0.06902729, + 0.07008141, 0.07033944, 0.07022615, 0.06977442, 0.06894731, 0.06814718, + 0.06774428, 0.06810594, 0.06882164, 0.06934666, 0.06990361, 0.07078452, + 0.07139315, 0.07079498, 0.06857792, 0.06630415, 0.06526684, 0.06512386, + 0.06568101, 0.06689893, 0.06856078, 0.07039654, 0.07184651, 0.07240477, + 0.07209843, 0.07100998, 0.06943199, 0.06802907, 0.0671699, 0.06662852, + 0.06625083, 0.0661338, 0.06617793, 0.06658512, 0.06730466, 0.06812465, + 0.06866366, 0.06868333, 0.06821723, 0.06712205, 0.06523205, 0.06327473, + 0.06186961, 0.06043651, 0.05888788, 0.05861247, 0.05975403, 0.06084589, + 0.06163529, 0.0619789, 0.06194087, 0.061432, 0.06063354, 0.05966061, + 0.05842775, 0.05710185, 0.05577594, 0.05394797, 0.05187146, 0.05152278, + 0.0534283, 0.05664466, 0.06106503, 0.06604659, 0.07145322, 0.07784917, + 0.08533052, 0.09329414, 0.1011765, 0.10791616, 0.11120184, 0.10852307, + 0.1045392, 0.10643732, 0.11066276, 0.11409803, 0.11902983, 0.12698301, + 0.13902298, 0.15237588, 0.1633798, 0.17212956, 0.179671, 0.18561263, + 0.18925252, 0.19040748, 0.18937401, 0.18703309, 0.18260644, 0.17033362, + 0.14077065, 0.11084724, 0.1030968, 0.11741595, 0.13745567, 0.15110533, + 0.15682253, 0.15812345, 0.15755359, 0.15585662, 0.15368759, 0.15086846, + 0.14702306, 0.14210789, 0.1372956, 0.13339315, 0.12988061, 0.1262256, + 0.12216039, 0.1178111, 0.11358331, 0.10918471, 0.1034911, 0.09589767, + 0.08665663, 0.07825239, 0.07361674, 0.07224158, 0.07199165, 0.07257136, + 0.07346027, 0.07374678, 0.07415465, 0.07543777, 0.07721565, 0.07861143, + 0.07911456, 0.07863731, 0.07730382, 0.0749192, 0.07162238, 0.06797465, + 0.06475224, 0.06266206, 0.06146712, 0.06030559, 0.05864737, 0.05667419, + 0.05525446, 0.05461379, 0.05417626, 0.05354191, 0.05284226, 0.05207279, + 0.05124803, 0.05051118, 0.04972649, 0.04876982, 0.04732547, 0.04493024, + 0.04143843, 0.03756908, 0.03454615, 0.03337561, 0.03325491, 0.03246053, + 0.03074391, 0.02899512, 0.02752891, 0.02636907, 0.02590251, 0.02585678, + 0.02543508, 0.02426568, 0.02216031, 0.01917821, 0.01588485, 0.01322024, + 0.0117436, 0.01146387, 0.0116006, 0.01157587, 0.01135505, 0.01116603, + 0.01104617, 0.01098228, 0.01100889, 0.01104027, 0.01109781, 0.01125572, + 0.01149373, 0.01179753, 0.01218904] + [0.229, 0.224, 0.225] + self.max_val = 255.0 + self.min_val = 0.0 + self.bands = 237 + + else: + raise ValueError(f"Unsupported dataset type: {self.dataset_type}") + + def _init_wavelength_params(self): + """Initialize wavelength information based on dataset type.""" + if self.dataset_type == 'harvard': + # Harvard wavelengths (31 bands from 420.0 to 720.0) + self.wavelengths = [420.0, 430.0, 440.0, 450.0, 460.0, 470.0, 480.0, 490.0, 500.0, 510.0, + 520.0, 530.0, 540.0, 550.0, 560.0, 570.0, 580.0, 590.0, 600.0, 610.0, + 620.0, 630.0, 640.0, 650.0, 660.0, 670.0, 680.0, 690.0, 700.0, 710.0, 720.0] + elif self.dataset_type == 'umld2015': + self.wavelengths = [400.0, 410.0, 420.0, 430.0, 440.0, 450.0, 460.0, 470.0, 480.0, 490.0, 500.0, 510.0, 520.0, 530.0, 540.0, 550.0, 560.0, 570.0, 580.0, 590.0, 600.0, 610.0, 620.0, 630.0, 640.0, 650.0, 660.0, 670.0, 680.0, 690.0, 700.0, 710.0, 720.0] + elif self.dataset_type == 'umns2002': + # UMNS2002 wavelengths (31 bands from 410.0 to 710.0) + self.wavelengths = [410.0, 420.0, 430.0, 440.0, 450.0, 460.0, 470.0, 480.0, 490.0, 500.0, + 510.0, 520.0, 530.0, 540.0, 550.0, 560.0, 570.0, 580.0, 590.0, 600.0, + 610.0, 620.0, 630.0, 640.0, 650.0, 660.0, 670.0, 680.0, 690.0, 700.0, 710.0] + elif self.dataset_type == 'umns2004': + # UMNS2004 wavelengths (33 bands from 400.0 to 720.0) + self.wavelengths = [400.0, 410.0, 420.0, 430.0, 440.0, 450.0, 460.0, 470.0, 480.0, 490.0, + 500.0, 510.0, 520.0, 530.0, 540.0, 550.0, 560.0, 570.0, 580.0, 590.0, + 600.0, 610.0, 620.0, 630.0, 640.0, 650.0, 660.0, 670.0, 680.0, 690.0, 700.0, 710.0, 720.0] + elif self.dataset_type == 'umos': + # UMOS wavelengths (31 bands from 400.0 to 700.0) + self.wavelengths = [400.0, 410.0, 420.0, 430.0, 440.0, 450.0, 460.0, 470.0, 480.0, 490.0, + 500.0, 510.0, 520.0, 530.0, 540.0, 550.0, 560.0, 570.0, 580.0, 590.0, + 600.0, 610.0, 620.0, 630.0, 640.0, 650.0, 660.0, 670.0, 680.0, 690.0, 700.0] + elif self.dataset_type == 'umri2015': + # UMRI2015 wavelengths (33 bands from 400.0 to 720.0) + self.wavelengths = [400.0, 410.0, 420.0, 430.0, 440.0, 450.0, 460.0, 470.0, 480.0, 490.0, + 500.0, 510.0, 520.0, 530.0, 540.0, 550.0, 560.0, 570.0, 580.0, 590.0, + 600.0, 610.0, 620.0, 630.0, 640.0, 650.0, 660.0, 670.0, 680.0, 690.0, 700.0, 710.0, 720.0] + elif self.dataset_type == 'umemm': + self.wavelengths = [400.0, 410.0, 420.0, 430.0, 440.0, 450.0, 460.0, 470.0, 480.0, 490.0, 500.0, 510.0, 520.0, 530.0, 540.0, 550.0, 560.0, 570.0, 580.0, 590.0, 600.0, 610.0, 620.0, 630.0, 640.0, 650.0, 660.0, 670.0, 680.0, 690.0, 700.0, 710.0, 720.0] + elif self.dataset_type == 'hyperblood': + self.wavelengths = [ 401.5636, 406.528 , 411.4977, 416.4725, 421.4525, 426.4379, + 431.4284, 436.4241, 441.4251, 446.4313, 451.4427, 456.4594, + 461.4813, 466.5084, 471.5408, 476.5783, 481.6211, 486.6691, + 491.7224, 496.7808, 501.8445, 506.9134, 511.9876, 517.067 , + 522.1515, 527.2413, 532.3364, 537.4367, 542.5422, 547.6529, + 552.7689, 557.8901, 563.0164, 568.1481, 573.2849, 578.427 , + 583.5743, 588.7269, 593.8846, 599.0476, 604.2158, 609.3892, + 614.5679, 635.3348, 640.5396, 645.7496, 650.9649, 656.1853, + 661.4111, 666.642 , 671.8782, 677.1195, 682.3661, 687.6179, + 692.875 , 698.1372, 703.4047, 708.6775, 713.9554, 719.2386, + 724.5271, 729.8207, 735.1196, 740.4236, 745.7329, 751.0475, + 756.3672, 761.6923, 767.0225, 772.358 , 777.6987, 783.0445, + 788.3956, 793.752 , 799.1135, 804.4803, 809.8524, 815.2296, + 820.6121, 825.9998, 831.3927, 836.7909, 842.1942, 847.6028, + 853.0167, 858.4358, 863.86 , 869.2896, 874.7243, 880.1642, + 885.6095, 891.0598, 896.5155, 901.9764, 907.4425, 912.9138, + 918.3903, 923.8721, 929.3591, 934.8514, 940.3488, 945.8514, + 951.3594, 956.8725, 962.3909, 967.9144, 973.4432, 978.9773, + 984.5165, 990.061 , 995.6107, 1001.1656, 1006.7258] + elif self.dataset_type == 'hsidrive20': + self.wavelengths = [600.0, 615.625, 631.25, 646.875, 662.5, 678.125, 693.75, 709.375, 725.0, 740.625, 756.25, 771.875, 787.5, 803.125, 818.75, 834.375, 850.0, 865.625, 881.25, 896.875, 912.5, 928.125, 943.75, 959.375, 975.0] + elif self.dataset_type == 'hotrednir': + self.wavelengths = [600.0, 617.857143, 635.714286, 653.571429, 671.428571, 689.285714, 707.142857, 725.0, 742.857143, 760.714286, 778.571429, 796.428571, 814.285714, 832.142857, 850.0] + elif self.dataset_type == 'arad_1k_31': + self.wavelengths = [400.0, 410.0, 420.0, 430.0, 440.0, 450.0, 460.0, 470.0, 480.0, 490.0, 500.0, 510.0, 520.0, 530.0, 540.0, 550.0, 560.0, 570.0, 580.0, 590.0, 600.0, 610.0, 620.0, 630.0, 640.0, 650.0, 660.0, 670.0, 680.0, 690.0, 700.0] + elif self.dataset_type == 'arad_1k_16': + self.wavelengths = [400.0, 440.0, 480.0, 520.0, 560.0, 600.0, 640.0, 680.0, 720.0, 760.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0] + elif self.dataset_type == 'cave': + self.wavelengths = [400.0, 410.0, 420.0, 430.0, 440.0, 450.0, 460.0, 470.0, 480.0, 490.0, 500.0, 510.0, 520.0, 530.0, 540.0, 550.0, 560.0, 570.0, 580.0, 590.0, 600.0, 610.0, 620.0, 630.0, 640.0, 650.0, 660.0, 670.0, 680.0, 690.0, 700.0] + elif self.dataset_type == 'icvl': + self.wavelengths = [400.0, 410.0, 420.0, 430.0, 440.0, 450.0, 460.0, 470.0, 480.0, 490.0, 500.0, 510.0, 520.0, 530.0, 540.0, 550.0, 560.0, 570.0, 580.0, 590.0, 600.0, 610.0, 620.0, 630.0, 640.0, 650.0, 660.0, 670.0, 680.0, 690.0, 700.0] + + elif self.dataset_type == 'hs_sod': + # HSSOD wavelengths (81 bands from 380.0 to 720.0) + self.wavelengths = [380.0, 384.25, 388.5, 392.75, 397.0, 401.25, 405.5, 409.75, 414.0, 418.25, 422.5, 426.75, 431.0, 435.25, 439.5, 443.75, 448.0, 452.25, 456.5, 460.75, 465.0, 469.25, 473.5, 477.75, 482.0, 486.25, 490.5, 494.75, 499.0, 503.25, 507.5, 511.75, 516.0, 520.25, 524.5, 528.75, 533.0, 537.25, 541.5, 545.75, 550.0, 554.25, 558.5, 562.75, 567.0, 571.25, 575.5, 579.75, 584.0, 588.25, 592.5, 596.75, 601.0, 605.25, 609.5, 613.75, 618.0, 622.25, 626.5, 630.75, 635.0, 639.25, 643.5, 647.75, 652.0, 656.25, 660.5, 664.75, 669.0, 673.25, 677.5, 681.75, 686.0, 690.25, 694.5, 698.75, 703.0, 707.25, 711.5, 715.75, 720.0] + elif self.dataset_type == 'hsodbit_v2': + self.wavelengths = [401.5, 404.5, 407.5, 410.5, 413.5, 416.5, 419.5, 422.5, 425.5, 428.5, 431.5, 434.5, 437.5, 440.5, 443.5, 446.5, 449.5, 452.5, 455.5, 458.5, 461.5, 464.5, 467.5, 470.5, 473.5, 476.5, 479.5, 482.5, 485.5, 488.5, 491.5, 494.5, 497.5, 500.5, 503.5, 506.5, 509.5, 512.5, 515.5, 518.5, 521.5, 524.5, 527.5, 530.5, 533.5, 536.5, 539.5, 542.5, 545.5, 548.5, 551.5, 554.5, 557.5, 560.5, 563.5, 566.5, 569.5, 572.5, 575.5, 578.5, 581.5, 584.5, 587.5, 590.5, 593.5, 596.5, 599.5, 602.5, 605.5, 608.5, 611.5, 614.5, 617.5, 620.5, 623.5, 626.5, 629.5, 632.5, 635.5, 638.5, 641.5, 644.5, 647.5, 650.5, 653.5, 656.5, 659.5, 662.5, 665.5, 668.5, 671.5, 674.5, 677.5, 680.5, 683.5, 686.5, 689.5, 692.5, 695.5, 698.5, 701.5, 704.5, 707.5, 710.5, 713.5, 716.5, 719.5, 722.5, 725.5, 728.5, 731.5, 734.5, 737.5, 740.5, 743.5, 746.5, 749.5, 752.5, 755.5, 758.5, 761.5, 764.5, 767.5, 770.5, 773.5, 776.5, 779.5, 782.5, 785.5, 788.5, 791.5, 794.5, 797.5, 800.5, 803.5, 806.5, 809.5, 812.5, 815.5, 818.5, 821.5, 824.5, 827.5, 830.5, 833.5, 836.5, 839.5, 842.5, 845.5, 848.5, 851.5, 854.5, 857.5, 860.5, 863.5, 866.5, 869.5, 872.5, 875.5, 878.5, 881.5, 884.5, 887.5, 890.5, 893.5, 896.5, 899.5, 902.5, 905.5, 908.5, 911.5, 914.5, 917.5, 920.5, 923.5, 926.5, 929.5, 932.5, 935.5, 938.5, 941.5, 944.5, 947.5, 950.5, 953.5, 956.5, 959.5, 962.5, 965.5, 968.5, 971.5, 974.5, 977.5, 980.5, 983.5, 986.5, 989.5, 992.5, 995.5, 998.5] + elif self.dataset_type == 'vnihdhiatlimafb': + # VNIHDHIATLIMAFB wavelengths (204 bands from 397.32 to 1000.0) + self.wavelengths = [397.32, 400.20, 403.09, 405.97, 408.85, 411.74, 414.63, 417.52, 420.40, 423.29, 426.19, 429.08, 431.97, 434.87, 437.76, 440.66, 443.56, 446.45, 449.35, 452.25, 455.16, 458.06, 460.96, 463.87, 466.77, 469.68, 472.59, 475.50, 478.41, 481.32, 484.23, 487.14, 490.06, 492.97, 495.89, 498.80, 501.72, 504.64, 507.56, 510.48, 513.40, 516.33, 519.25, 522.18, 525.10, 528.03, 530.96, 533.89, 536.82, 539.75, 542.68, 545.62, 548.55, 551.49, 554.43, 557.36, 560.30, 563.24, 566.18, 569.12, 572.07, 575.01, 577.96, 580.90, 583.85, 586.80, 589.75, 592.70, 595.65, 598.60, 601.55, 604.51, 607.46, 610.42, 613.38, 616.34, 619.30, 622.26, 625.22, 628.18, 631.15, 634.11, 637.08, 640.04, 643.01, 645.98, 648.95, 651.92, 654.89, 657.87, 660.84, 663.81, 666.79, 669.77, 672.75, 675.73, 678.71, 681.69, 684.67, 687.65, 690.64, 693.62, 696.61, 699.60, 702.58, 705.57, 708.57, 711.56, 714.55, 717.54, 720.54, 723.53, 726.53, 729.53, 732.53, 735.53, 738.53, 741.53, 744.53, 747.54, 750.54, 753.55, 756.56, 759.56, 762.57, 765.58, 768.60, 771.61, 774.62, 777.64, 780.65, 783.67, 786.68, 789.70, 792.72, 795.74, 798.77, 801.79, 804.81, 807.84, 810.86, 813.89, 816.92, 819.95, 822.98, 826.01, 829.04, 832.07, 835.11, 838.14, 841.18, 844.22, 847.25, 850.29, 853.33, 856.37, 859.42, 862.46, 865.50, 868.55, 871.60, 874.64, 877.69, 880.74, 883.79, 886.84, 889.90, 892.95, 896.01, 899.06, 902.12, 905.18, 908.24, 911.30, 914.36, 917.42, 920.48, 923.55, 926.61, 929.68, 932.74, 935.81, 938.88, 941.95, 945.02, 948.10, 951.17, 954.24, 957.32, 960.40, 963.47, 966.55, 969.63, 972.71, 975.79, 978.88, 981.96, 985.05, 988.13, 991.22, 994.31, 997.40, 1000.49, 1003.58] + elif self.dataset_type == 'deephsnir': + self.wavelengths = [950.0, 952.988048, 955.976096, 958.964143, 961.952191, 964.940239, 967.928287, 970.916335, 973.904382, 976.89243, 979.880478, 982.868526, 985.856574, 988.844622, 991.832669, 994.820717, 997.808765, 1000.796813, 1003.784861, 1006.772908, 1009.760956, 1012.749004, 1015.737052, 1018.7251, 1021.713147, 1024.701195, 1027.689243, 1030.677291, 1033.665339, 1036.653386, 1039.641434, 1042.629482, 1045.61753, 1048.605578, 1051.593625, 1054.581673, 1057.569721, 1060.557769, 1063.545817, 1066.533865, 1069.521912, 1072.50996, 1075.498008, 1078.486056, 1081.474104, 1084.462151, 1087.450199, 1090.438247, 1093.426295, 1096.414343, 1099.40239, 1102.390438, 1105.378486, 1108.366534, 1111.354582, 1114.342629, 1117.330677, 1120.318725, 1123.306773, 1126.294821, 1129.282869, 1132.270916, 1135.258964, 1138.247012, 1141.23506, 1144.223108, 1147.211155, 1150.199203, 1153.187251, 1156.175299, 1159.163347, 1162.151394, 1165.139442, 1168.12749, 1171.115538, 1174.103586, 1177.091633, 1180.079681, 1183.067729, 1186.055777, 1189.043825, 1192.031873, 1195.01992, 1198.007968, 1200.996016, 1203.984064, 1206.972112, 1209.960159, 1212.948207, 1215.936255, 1218.924303, 1221.912351, 1224.900398, 1227.888446, 1230.876494, 1233.864542, 1236.85259, 1239.840637, 1242.828685, 1245.816733, 1248.804781, 1251.792829, 1254.780876, 1257.768924, 1260.756972, 1263.74502, 1266.733068, 1269.721116, 1272.709163, 1275.697211, 1278.685259, 1281.673307, 1284.661355, 1287.649402, 1290.63745, 1293.625498, 1296.613546, 1299.601594, 1302.589641, 1305.577689, 1308.565737, 1311.553785, 1314.541833, 1317.52988, 1320.517928, 1323.505976, 1326.494024, 1329.482072, 1332.47012, 1335.458167, 1338.446215, 1341.434263, 1344.422311, 1347.410359, 1350.398406, 1353.386454, 1356.374502, 1359.36255, 1362.350598, 1365.338645, 1368.326693, 1371.314741, 1374.302789, 1377.290837, 1380.278884, 1383.266932, 1386.25498, 1389.243028, 1392.231076, 1395.219124, 1398.207171, 1401.195219, 1404.183267, 1407.171315, 1410.159363, 1413.14741, 1416.135458, 1419.123506, 1422.111554, 1425.099602, 1428.087649, 1431.075697, 1434.063745, 1437.051793, 1440.039841, 1443.027888, 1446.015936, 1449.003984, 1451.992032, 1454.98008, 1457.968127, 1460.956175, 1463.944223, 1466.932271, 1469.920319, 1472.908367, 1475.896414, 1478.884462, 1481.87251, 1484.860558, 1487.848606, 1490.836653, 1493.824701, 1496.812749, 1499.800797, 1502.788845, 1505.776892, 1508.76494, 1511.752988, 1514.741036, 1517.729084, 1520.717131, 1523.705179, 1526.693227, 1529.681275, 1532.669323, 1535.657371, 1538.645418, 1541.633466, 1544.621514, 1547.609562, 1550.59761, 1553.585657, 1556.573705, 1559.561753, 1562.549801, 1565.537849, 1568.525896, 1571.513944, 1574.501992, 1577.49004, 1580.478088, 1583.466135, 1586.454183, 1589.442231, 1592.430279, 1595.418327, 1598.406375, 1601.394422, 1604.38247, 1607.370518, 1610.358566, 1613.346614, 1616.334661, 1619.322709, 1622.310757, 1625.298805, 1628.286853, 1631.2749, 1634.262948, 1637.250996, 1640.239044, 1643.227092, 1646.215139, 1649.203187, 1652.191235, 1655.179283, 1658.167331, 1661.155378, 1664.143426, 1667.131474, 1670.119522, 1673.10757, 1676.095618, 1679.083665, 1682.071713, 1685.059761, 1688.047809, 1691.035857, 1694.023904, 1697.011952, 1700.0] + elif self.dataset_type == 'deephsvis': + self.wavelengths = [400.0, 402.690583, 405.381166, 408.071749, 410.762332, 413.452915, 416.143498, 418.834081, 421.524664, 424.215247, 426.90583, 429.596413, 432.286996, 434.977578, 437.668161, 440.358744, 443.049327, 445.73991, 448.430493, 451.121076, 453.811659, 456.502242, 459.192825, 461.883408, 464.573991, 467.264574, 469.955157, 472.64574, 475.336323, 478.026906, 480.717489, 483.408072, 486.098655, 488.789238, 491.479821, 494.170404, 496.860987, 499.55157, 502.242152, 504.932735, 507.623318, 510.313901, 513.004484, 515.695067, 518.38565, 521.076233, 523.766816, 526.457399, 529.147982, 531.838565, 534.529148, 537.219731, 539.910314, 542.600897, 545.29148, 547.982063, 550.672646, 553.363229, 556.053812, 558.744395, 561.434978, 564.125561, 566.816143, 569.506726, 572.197309, 574.887892, 577.578475, 580.269058, 582.959641, 585.650224, 588.340807, 591.03139, 593.721973, 596.412556, 599.103139, 601.793722, 604.484305, 607.174888, 609.865471, 612.556054, 615.246637, 617.93722, 620.627803, 623.318386, 626.008969, 628.699552, 631.390135, 634.080717, 636.7713, 639.461883, 642.152466, 644.843049, 647.533632, 650.224215, 652.914798, 655.605381, 658.295964, 660.986547, 663.67713, 666.367713, 669.058296, 671.748879, 674.439462, 677.130045, 679.820628, 682.511211, 685.201794, 687.892377, 690.58296, 693.273543, 695.964126, 698.654709, 701.345291, 704.035874, 706.726457, 709.41704, 712.107623, 714.798206, 717.488789, 720.179372, 722.869955, 725.560538, 728.251121, 730.941704, 733.632287, 736.32287, 739.013453, 741.704036, 744.394619, 747.085202, 749.775785, 752.466368, 755.156951, 757.847534, 760.538117, 763.2287, 765.919283, 768.609865, 771.300448, 773.991031, 776.681614, 779.372197, 782.06278, 784.753363, 787.443946, 790.134529, 792.825112, 795.515695, 798.206278, 800.896861, 803.587444, 806.278027, 808.96861, 811.659193, 814.349776, 817.040359, 819.730942, 822.421525, 825.112108, 827.802691, 830.493274, 833.183857, 835.874439, 838.565022, 841.255605, 843.946188, 846.636771, 849.327354, 852.017937, 854.70852, 857.399103, 860.089686, 862.780269, 865.470852, 868.161435, 870.852018, 873.542601, 876.233184, 878.923767, 881.61435, 884.304933, 886.995516, 889.686099, 892.376682, 895.067265, 897.757848, 900.44843, 903.139013, 905.829596, 908.520179, 911.210762, 913.901345, 916.591928, 919.282511, 921.973094, 924.663677, 927.35426, 930.044843, 932.735426, 935.426009, 938.116592, 940.807175, 943.497758, 946.188341, 948.878924, 951.569507, 954.26009, 956.950673, 959.641256, 962.331839, 965.022422, 967.713004, 970.403587, 973.09417, 975.784753, 978.475336, 981.165919, 983.856502, 986.547085, 989.237668, 991.928251, 994.618834, 997.309417, 1000.0] + elif self.dataset_type == 'deephsviscor': + # DeepHS wavelengths (249 bands from 400.0 to 1000.0) + self.wavelengths = [400.0, 402.690583, 405.381166, 408.071749, 410.762332, 413.452915, 416.143498, 418.834081, 421.524664, 424.215247, 426.90583, 429.596413, 432.286996, 434.977578, 437.668161, 440.358744, 443.049327, 445.73991, 448.430493, 451.121076, 453.811659, 456.502242, 459.192825, 461.883408, 464.573991, 467.264574, 469.955157, 472.64574, 475.336323, 478.026906, 480.717489, 483.408072, 486.098655, 488.789238, 491.479821, 494.170404, 496.860987, 499.55157, 502.242152, 504.932735, 507.623318, 510.313901, 513.004484, 515.695067, 518.38565, 521.076233, 523.766816, 526.457399, 529.147982, 531.838565, 534.529148, 537.219731, 539.910314, 542.600897, 545.29148, 547.982063, 550.672646, 553.363229, 556.053812, 558.744395, 561.434978, 564.125561, 566.816143, 569.506726, 572.197309, 574.887892, 577.578475, 580.269058, 582.959641, 585.650224, 588.340807, 591.03139, 593.721973, 596.412556, 599.103139, 601.793722, 604.484305, 607.174888, 609.865471, 612.556054, 615.246637, 617.93722, 620.627803, 623.318386, 626.008969, 628.699552, 631.390135, 634.080717, 636.7713, 639.461883, 642.152466, 644.843049, 647.533632, 650.224215, 652.914798, 655.605381, 658.295964, 660.986547, 663.67713, 666.367713, 669.058296, 671.748879, 674.439462, 677.130045, 679.820628, 682.511211, 685.201794, 687.892377, 690.58296, 693.273543, 695.964126, 698.654709, 701.345291, 704.035874, 706.726457, 709.41704, 712.107623, 714.798206, 717.488789, 720.179372, 722.869955, 725.560538, 728.251121, 730.941704, 733.632287, 736.32287, 739.013453, 741.704036, 744.394619, 747.085202, 749.775785, 752.466368, 755.156951, 757.847534, 760.538117, 763.2287, 765.919283, 768.609865, 771.300448, 773.991031, 776.681614, 779.372197, 782.06278, 784.753363, 787.443946, 790.134529, 792.825112, 795.515695, 798.206278, 800.896861, 803.587444, 806.278027, 808.96861, 811.659193, 814.349776, 817.040359, 819.730942, 822.421525, 825.112108, 827.802691, 830.493274, 833.183857, 835.874439, 838.565022, 841.255605, 843.946188, 846.636771, 849.327354, 852.017937, 854.70852, 857.399103, 860.089686, 862.780269, 865.470852, 868.161435, 870.852018, 873.542601, 876.233184, 878.923767, 881.61435, 884.304933, 886.995516, 889.686099, 892.376682, 895.067265, 897.757848, 900.44843, 903.139013, 905.829596, 908.520179, 911.210762, 913.901345, 916.591928, 919.282511, 921.973094, 924.663677, 927.35426, 930.044843, 932.735426, 935.426009, 938.116592, 940.807175, 943.497758, 946.188341, 948.878924, 951.569507, 954.26009, 956.950673, 959.641256, 962.331839, 965.022422, 967.713004, 970.403587, 973.09417, 975.784753, 978.475336, 981.165919, 983.856502, 986.547085, 989.237668, 991.928251, 994.618834, 997.309417, 1000.0] + elif self.dataset_type == 'hsodbitv2': + # HSODBITV2 wavelengths (200 bands from 401.5 to 998.5) + self.wavelengths = [401.5, 404.5, 407.5, 410.5, 413.5, 416.5, 419.5, 422.5, 425.5, 428.5, 431.5, 434.5, 437.5, 440.5, 443.5, 446.5, 449.5, 452.5, 455.5, 458.5, 461.5, 464.5, 467.5, 470.5, 473.5, 476.5, 479.5, 482.5, 485.5, 488.5, 491.5, 494.5, 497.5, 500.5, 503.5, 506.5, 509.5, 512.5, 515.5, 518.5, 521.5, 524.5, 527.5, 530.5, 533.5, 536.5, 539.5, 542.5, 545.5, 548.5, 551.5, 554.5, 557.5, 560.5, 563.5, 566.5, 569.5, 572.5, 575.5, 578.5, 581.5, 584.5, 587.5, 590.5, 593.5, 596.5, 599.5, 602.5, 605.5, 608.5, 611.5, 614.5, 617.5, 620.5, 623.5, 626.5, 629.5, 632.5, 635.5, 638.5, 641.5, 644.5, 647.5, 650.5, 653.5, 656.5, 659.5, 662.5, 665.5, 668.5, 671.5, 674.5, 677.5, 680.5, 683.5, 686.5, 689.5, 692.5, 695.5, 698.5, 701.5, 704.5, 707.5, 710.5, 713.5, 716.5, 719.5, 722.5, 725.5, 728.5, 731.5, 734.5, 737.5, 740.5, 743.5, 746.5, 749.5, 752.5, 755.5, 758.5, 761.5, 764.5, 767.5, 770.5, 773.5, 776.5, 779.5, 782.5, 785.5, 788.5, 791.5, 794.5, 797.5, 800.5, 803.5, 806.5, 809.5, 812.5, 815.5, 818.5, 821.5, 824.5, 827.5, 830.5, 833.5, 836.5, 839.5, 842.5, 845.5, 848.5, 851.5, 854.5, 857.5, 860.5, 863.5, 866.5, 869.5, 872.5, 875.5, 878.5, 881.5, 884.5, 887.5, 890.5, 893.5, 896.5, 899.5, 902.5, 905.5, 908.5, 911.5, 914.5, 917.5, 920.5, 923.5, 926.5, 929.5, 932.5, 935.5, 938.5, 941.5, 944.5, 947.5, 950.5, 953.5, 956.5, 959.5, 962.5, 965.5, 968.5, 971.5, 974.5, 977.5, 980.5, 983.5, 986.5, 989.5, 992.5, 995.5, 998.5] + elif self.dataset_type == 'hotvis': + # HOT VIS wavelengths (16 bands) + self.wavelengths = [463.0, 472.0, 481.0, 490.0, 499.0, 508.0, 517.0, 526.0, 535.0, 544.0, 553.0, 562.0, 571.0, 580.0, 589.0, 598.0] + elif self.dataset_type == 'hotnir': + # HOT NIR wavelengths (25 bands) + self.wavelengths = [668.0, 680.0, 692.0, 704.0, 716.0, 728.0, 740.0, 752.0, 764.0, 776.0, 788.0, 800.0, 812.0, 824.0, 836.0, 848.0, 860.0, 872.0, 884.0, 896.0, 908.0, 920.0, 932.0, 944.0, 956.0] + elif self.dataset_type == 'hsiroad': + # HSI Road wavelengths (25 bands) + self.wavelengths = [600.0, 615.0, 630.0, 645.0, 660.0, 675.0, 690.0, 705.0, 720.0, 735.0, 750.0, 765.0, 780.0, 795.0, 810.0, 825.0, 840.0, 855.0, 870.0, 885.0, 900.0, 915.0, 930.0, 945.0, 960.0] + elif self.dataset_type == 'hyperspectralcityv2': + # hyperspectralcityv2 wavelengths (128 bands) + self.wavelengths = [450.0, 453.937008, 457.874016, 461.811024, 465.748031, 469.685039, 473.622047, 477.559055, 481.496063, 485.433071, 489.370079, 493.307087, 497.244094, 501.181102, 505.11811, 509.055118, 512.992126, 516.929134, 520.866142, 524.80315, 528.740157, 532.677165, 536.614173, 540.551181, 544.488189, 548.425197, 552.362205, 556.299213, 560.23622, 564.173228, 568.110236, 572.047244, 575.984252, 579.92126, 583.858268, 587.795276, 591.732283, 595.669291, 599.606299, 603.543307, 607.480315, 611.417323, 615.354331, 619.291339, 623.228346, 627.165354, 631.102362, 635.03937, 638.976378, 642.913386, 646.850394, 650.787402, 654.724409, 658.661417, 662.598425, 666.535433, 670.472441, 674.409449, 678.346457, 682.283465, 686.220472, 690.15748, 694.094488, 698.031496, 701.968504, 705.905512, 709.84252, 713.779528, 717.716535, 721.653543, 725.590551, 729.527559, 733.464567, 737.401575, 741.338583, 745.275591, 749.212598, 753.149606, 757.086614, 761.023622, 764.96063, 768.897638, 772.834646, 776.771654, 780.708661, 784.645669, 788.582677, 792.519685, 796.456693, 800.393701, 804.330709, 808.267717, 812.204724, 816.141732, 820.07874, 824.015748, 827.952756, 831.889764, 835.826772, 839.76378, 843.700787, 847.637795, 851.574803, 855.511811, 859.448819, 863.385827, 867.322835, 871.259843, 875.19685, 879.133858, 883.070866, 887.007874, 890.944882, 894.88189, 898.818898, 902.755906, 906.692913, 910.629921, 914.566929, 918.503937, 922.440945, 926.377953, 930.314961, 934.251969, 938.188976, 942.125984, 946.062992, 950.0] + elif self.dataset_type == 'hyperdrive': + # Hyperdrive full dataset wavelengths (33 bands: 24 VNIR + 9 SWIR) + self.wavelengths = [660.0, 670.434783, 680.869565, 691.304348, 701.73913, 712.173913, 722.608696, 733.043478, 743.478261, 753.913043, 764.347826, 774.782609, 785.217391, 795.652174, 806.086957, 816.521739, 826.956522, 837.391304, 847.826087, 858.26087, 868.695652, 879.130435, 889.565217, 900.0] + [1100.0, 1175.0, 1250.0, 1325.0, 1400.0, 1475.0, 1550.0, 1625.0, 1700.0] + elif self.dataset_type == 'hyperdrivevnir': + # HyperdriveVNIR wavelengths (24 VNIR bands only) + self.wavelengths = [660.0, 670.434783, 680.869565, 691.304348, 701.73913, 712.173913, 722.608696, 733.043478, 743.478261, 753.913043, 764.347826, 774.782609, 785.217391, 795.652174, 806.086957, 816.521739, 826.956522, 837.391304, 847.826087, 858.26087, 868.695652, 879.130435, 889.565217, 900.0] + elif self.dataset_type == 'hyperdriveswir': + # HyperdriveSWIR wavelengths (9 SWIR bands only) + self.wavelengths = [1100.0, 1175.0, 1250.0, 1325.0, 1400.0, 1475.0, 1550.0, 1625.0, 1700.0] + elif self.dataset_type == 'hykov2nir': + # hykov2nir wavelengths (25 bands) + self.wavelengths = [ 673.37, 674.88, 689.24, 714.08, 728.15, 740.42, 754.96, 767.18, 780.18, 791.21, 803.8, 822.46, 834.33, 844.29, 855.44, 865.25, 875.2, 884.62, 893.66, 909.95, 917.28, 924.59, 930.97, 939.62, 944.82] + elif self.dataset_type == 'hykov2vis': + # hykov2vis wavelengths (15 bands) + self.wavelengths = [ 468.2, 478.34, 490.83, 503.56, 514.11, 526.92, 541.8, 555.12, 569.3, 578.54, 592.71, 600.25, 611.57, 622.49, 642.55] + elif self.dataset_type == 'libhsi': + # LIBHSI wavelengths (204 bands from 397.32 to 1003.58) + self.wavelengths = [397.32,400.20,403.09,405.97,408.85,411.74,414.63,417.52,420.40,423.29,426.19,429.08,431.97,434.87,437.76,440.66,443.56,446.45,449.35,452.25,455.16,458.06,460.96,463.87,466.77,469.68,472.59,475.50,478.41,481.32,484.23,487.14,490.06,492.97,495.89,498.80,501.72,504.64,507.56,510.48,513.40,516.33,519.25,522.18,525.10,528.03,530.96,533.89,536.82,539.75,542.68,545.62,548.55,551.49,554.43,557.36,560.30,563.24,566.18,569.12,572.07,575.01,577.96,580.90,583.85,586.80,589.75,592.70,595.65,598.60,601.55,604.51,607.46,610.42,613.38,616.34,619.30,622.26,625.22,628.18,631.15,634.11,637.08,640.04,643.01,645.98,648.95,651.92,654.89,657.87,660.84,663.81,666.79,669.77,672.75,675.73,678.71,681.69,684.67,687.65,690.64,693.62,696.61,699.60,702.58,705.57,708.57,711.56,714.55,717.54,720.54,723.53,726.53,729.53,732.53,735.53,738.53,741.53,744.53,747.54,750.54,753.55,756.56,759.56,762.57,765.58,768.60,771.61,774.62,777.64,780.65,783.67,786.68,789.70,792.72,795.74,798.77,801.79,804.81,807.84,810.86,813.89,816.92,819.95,822.98,826.01,829.04,832.07,835.11,838.14,841.18,844.22,847.25,850.29,853.33,856.37,859.42,862.46,865.50,868.55,871.60,874.64,877.69,880.74,883.79,886.84,889.90,892.95,896.01,899.06,902.12,905.18,908.24,911.30,914.36,917.42,920.48,923.55,926.61,929.68,932.74,935.81,938.88,941.95,945.02,948.10,951.17,954.24,957.32,960.40,963.47,966.55,969.63,972.71,975.79,978.88,981.96,985.05,988.13,991.22,994.31,997.40,1000.49,1003.58] + elif self.dataset_type == 'virginiatree': + # VirginiaTechTrees wavelengths (420 bands from 394.7 to 1005.86) + self.wavelengths = [394.7, 396.09, 397.48, 398.87, 400.26, 401.66, 403.05, 404.44, 405.83, 407.22, 408.62, 410.01, 411.4, 412.8, 414.19, 415.58, 416.98, 418.37, 419.77, 421.17, 422.56, 423.96, 425.35, 426.75, 428.15, 429.55, 430.94, 432.34, 433.74, 435.14, 436.54, 437.94, 439.34, 440.74, 442.14, 443.54, 444.94, 446.34, 447.75, 449.15, 450.55, 451.95, 453.36, 454.76, 456.17, 457.57, 458.97, 460.38, 461.78, 463.19, 464.6, 466, 467.41, 468.82, 470.22, 471.63, 473.04, 474.45, 475.86, 477.26, 478.67, 480.08, 481.49, 482.9, 484.31, 485.72, 487.14, 488.55, 489.96, 491.37, 492.78, 494.2, 495.61, 497.02, 498.44, 499.85, 501.27, 502.68, 504.1, 505.51, 506.93, 508.34, 509.76, 511.18, 512.59, 514.01, 515.43, 516.85, 518.27, 519.68, 521.1, 522.52, 523.94, 525.36, 526.78, 528.2, 529.62, 531.05, 532.47, 533.89, 535.31, 536.74, 538.16, 539.58, 541.01, 542.43, 543.85, 545.28, 546.7, 548.13, 549.55, 550.98, 552.41, 553.83, 555.26, 556.69, 558.12, 559.54, 560.97, 562.4, 563.83, 565.26, 566.69, 568.12, 569.55, 570.98, 572.41, 573.84, 575.27, 576.71, 578.14, 579.57, 581, 582.44, 583.87, 585.3, 586.74, 588.17, 589.61, 591.04, 592.48, 593.91, 595.35, 596.79, 598.22, 599.66, 601.1, 602.54, 603.97, 605.41, 606.85, 608.29, 609.73, 611.17, 612.61, 614.05, 615.49, 616.93, 618.37, 619.82, 621.26, 622.7, 624.14, 625.59, 627.03, 628.47, 629.92, 631.36, 632.81, 634.25, 635.7, 637.14, 638.59, 640.04, 641.48, 642.93, 644.38, 645.83, 647.27, 648.72, 650.17, 651.62, 653.07, 654.52, 655.97, 657.42, 658.87, 660.32, 661.77, 663.22, 664.68, 666.13, 667.58, 669.03, 670.49, 671.94, 673.4, 674.85, 676.3, 677.76, 679.21, 680.67, 682.13, 683.58, 685.04, 686.5, 687.95, 689.41, 690.87, 692.33, 693.79, 695.24, 696.7, 698.16, 699.62, 701.08, 702.54, 704.01, 705.47, 706.93, 708.39, 709.85, 711.32, 712.78, 714.24, 715.7, 717.17, 718.63, 720.1, 721.56, 723.03, 724.49, 725.96, 727.42, 728.89, 730.36, 731.83, 733.29, 734.76, 736.23, 737.7, 739.17, 740.64, 742.1, 743.57, 745.04, 746.52, 747.99, 749.46, 750.93, 752.4, 753.87, 755.35, 756.82, 758.29, 759.76, 761.24, 762.71, 764.19, 765.66, 767.14, 768.61, 770.09, 771.56, 773.04, 774.52, 775.99, 777.47, 778.95, 780.43, 781.91, 783.38, 784.86, 786.34, 787.82, 789.3, 790.78, 792.26, 793.74, 795.23, 796.71, 798.19, 799.67, 801.15, 802.64, 804.12, 805.6, 807.09, 808.57, 810.06, 811.54, 813.03, 814.51, 816, 817.48, 818.97, 820.46, 821.95, 823.43, 824.92, 826.41, 827.9, 829.39, 830.88, 832.37, 833.86, 835.35, 836.84, 838.33, 839.82, 841.31, 842.8, 844.29, 845.79, 847.28, 848.77, 850.27, 851.76, 853.25, 854.75, 856.24, 857.74, 859.23, 860.73, 862.23, 863.72, 865.22, 866.72, 868.21, 869.71, 871.21, 872.71, 874.21, 875.71, 877.21, 878.71, 880.21, 881.71, 883.21, 884.71, 886.21, 887.71, 889.21, 890.72, 892.22, 893.72, 895.22, 896.73, 898.23, 899.74, 901.24, 902.75, 904.25, 905.76, 907.26, 908.77, 910.28, 911.78, 913.29, 914.8, 916.31, 917.82, 919.32, 920.83, 922.34, 923.85, 925.36, 926.87, 928.38, 929.89, 931.4, 932.92, 934.43, 935.94, 937.45, 938.97, 940.48, 941.99, 943.51, 945.02, 946.54, 948.05, 949.57, 951.08, 952.6, 954.11, 955.63, 957.15, 958.66, 960.18, 961.7, 963.22, 964.74, 966.26, 967.77, 969.29, 970.81, 972.33, 973.85, 975.38, 976.9, 978.42, 979.94, 981.46, 982.98, 984.51, 986.03, 987.55, 989.08, 990.6, 992.13, 993.65, 995.18, 996.7, 998.23, 999.75, 1001.28, 1002.81, 1004.33, 1005.86 ] + elif self.dataset_type == 'fiftyoutdoor': + # FiftyOutdoor wavelengths (33 bands from 400.0 to 720.0) + self.wavelengths = [400.0, 410.0, 420.0, 430.0, 440.0, 450.0, 460.0, 470.0, 480.0, 490.0, 500.0, 510.0, 520.0, 530.0, 540.0, 550.0, 560.0, 570.0, 580.0, 590.0, 600.0, 610.0, 620.0, 630.0, 640.0, 650.0, 660.0, 670.0, 680.0, 690.0, 700.0, 710.0, 720.0] + elif self.dataset_type == 'aphid': + # APHID wavelengths (237 bands from 436.0 to 965.0) + self.wavelengths = [436.0, 438.0, 440.0, 442.0, 445.0, 447.0, 449.0, 451.0, 454.0, 456.0, 458.0, 460.0, 463.0, 465.0, 467.0, 469.0, 472.0, 474.0, 476.0, 478.0, 481.0, 483.0, 485.0, 487.0, 490.0, 492.0, 494.0, 496.0, 499.0, 501.0, 503.0, 505.0, 508.0, 510.0, 512.0, 514.0, 516.0, 519.0, 521.0, 523.0, 525.0, 528.0, 530.0, 532.0, 534.0, 537.0, 539.0, 541.0, 543.0, 546.0, 548.0, 550.0, 552.0, 555.0, 557.0, 559.0, 561.0, 564.0, 566.0, 568.0, 570.0, 573.0, 575.0, 577.0, 579.0, 582.0, 584.0, 586.0, 588.0, 591.0, 593.0, 595.0, 597.0, 600.0, 602.0, 604.0, 606.0, 609.0, 611.0, 613.0, 615.0, 617.0, 620.0, 622.0, 624.0, 626.0, 629.0, 631.0, 633.0, 635.0, 638.0, 640.0, 642.0, 644.0, 647.0, 649.0, 651.0, 653.0, 656.0, 658.0, 660.0, 662.0, 665.0, 667.0, 669.0, 671.0, 674.0, 676.0, 678.0, 680.0, 683.0, 685.0, 687.0, 689.0, 692.0, 694.0, 696.0, 698.0, 701.0, 703.0, 705.0, 707.0, 709.0, 712.0, 714.0, 716.0, 718.0, 721.0, 723.0, 725.0, 727.0, 730.0, 732.0, 734.0, 736.0, 739.0, 741.0, 743.0, 745.0, 748.0, 750.0, 752.0, 754.0, 757.0, 759.0, 761.0, 763.0, 766.0, 768.0, 770.0, 772.0, 775.0, 777.0, 779.0, 781.0, 784.0, 786.0, 788.0, 790.0, 793.0, 795.0, 797.0, 799.0, 801.0, 804.0, 806.0, 808.0, 810.0, 813.0, 815.0, 817.0, 819.0, 822.0, 824.0, 826.0, 828.0, 831.0, 833.0, 835.0, 837.0, 840.0, 842.0, 844.0, 846.0, 849.0, 851.0, 853.0, 855.0, 858.0, 860.0, 862.0, 864.0, 867.0, 869.0, 871.0, 873.0, 876.0, 878.0, 880.0, 882.0, 885.0, 887.0, 889.0, 891.0, 894.0, 896.0, 898.0, 900.0, 902.0, 905.0, 907.0, 909.0, 911.0, 914.0, 916.0, 918.0, 920.0, 923.0, 925.0, 927.0, 929.0, 932.0, 934.0, 936.0, 938.0, 941.0, 943.0, 945.0, 947.0, 950.0, 952.0, 954.0, 956.0, 959.0, 961.0, 963.0, 965.0] + else: + # Default wavelength range for unknown datasets + self.wavelengths = [400.0, 410.0, 420.0, 430.0, 440.0, 450.0, 460.0, 470.0, 480.0, 490.0, + 500.0, 510.0, 520.0, 530.0, 540.0, 550.0, 560.0, 570.0, 580.0, 590.0, + 600.0, 610.0, 620.0, 630.0, 640.0, 650.0, 660.0, 670.0, 680.0, 690.0, 700.0] + + def transform(self, results: dict) -> dict: + """Transform function to load hyperspectral image. + + Args: + results (dict): Result dict containing img_path. + + Returns: + dict: The dict contains loaded image and meta information. + """ + _, logger = _get_rank_logger( + 'pipeline', + logger_cache=self.rank_logger_cache, + enable=self.enable_rank_logging, + ) + dataset_name = results.get('dataset_name', results.get('dataset', 'unknown')) + img_path = results['img_path'] + if logger is not None: + logger.info(f"Loading : {img_path}") + # Load image based on dataset type + if self.dataset_type == 'harvard': + img = self._load_harvard_image(img_path) + elif self.dataset_type == 'umld2015': + img = self._load_umld2015_image(img_path) + elif self.dataset_type == 'umns2002': + img = self._load_umns2002_image(img_path) + elif self.dataset_type == 'umns2004': + img = self._load_umns2004_image(img_path) + elif self.dataset_type == 'umos': + img = self._load_umos_image(img_path) + elif self.dataset_type == 'umri2015': + img = self._load_umri2015_image(img_path) + elif self.dataset_type == 'umemm': + img = self._load_umemm_image(img_path) + elif self.dataset_type == 'hyperblood': + img = self._load_hyperblood_image(img_path) + elif self.dataset_type == 'hsidrive20': + img = self._load_hsidrive20_image(img_path) + elif self.dataset_type == 'hotrednir': + img = self._load_hotrednir_image(img_path) + elif self.dataset_type == 'arad_1k_31': + img = self._load_arad_1k_31_image(img_path) + elif self.dataset_type == 'arad_1k_16': + img = self._load_arad_1k_16_image(img_path) + elif self.dataset_type == 'cave': + img = self._load_cave_image(img_path) + elif self.dataset_type == 'icvl': + img = self._load_icvl_image(img_path) + elif self.dataset_type == 'hs_sod': + img = self._load_hs_sod_image(img_path) + elif self.dataset_type == 'vnihdhiatlimafb': + img = self._load_vnihdhiatlimafb_image(img_path) + elif self.dataset_type == 'deephsnir': + img = self._load_deephsnir_image(img_path) + elif self.dataset_type == 'deephsvis': + img = self._load_deephsvis_image(img_path) + elif self.dataset_type == 'deephsviscor': + img = self._load_deephsviscor_image(img_path) + elif self.dataset_type == 'hsodbitv2': + img = self._load_hsodbit_v2_image(img_path) + elif self.dataset_type == 'hotvis': + img = self._load_hotvis_image(img_path) + elif self.dataset_type == 'hotnir': + img = self._load_hotnir_image(img_path) + elif self.dataset_type == 'hsiroad': + img = self._load_hsiroad_image(img_path) + elif self.dataset_type == 'hyperspectralcityv2': + img = self._load_hyperspectralcityv2_image(img_path) + elif self.dataset_type == 'hykov2nir': + img = self._load_hykov2nir_image(img_path) + elif self.dataset_type == 'hykov2vis': + img = self._load_hykov2vis_image(img_path) + elif self.dataset_type == 'hyperdrive': + img = self._load_hyperdrive_image(img_path) + elif self.dataset_type == 'hyperdrivevnir': + img = self._load_hyperdrivevnir_image(img_path) + elif self.dataset_type == 'hyperdriveswir': + img = self._load_hyperdriveswir_image(img_path) + elif self.dataset_type == 'libhsi': + img = self._load_libhsi_image(img_path) + elif self.dataset_type == 'virginia_tech_tree': + img = self._load_virginiatree_image(img_path) + elif self.dataset_type == 'fiftyoutdoor': + img = self._load_fiftyoutdoor_image(img_path) + elif self.dataset_type == 'aphid': + img = self._load_aphid_image(img_path) + else: + raise ValueError(f"Unsupported dataset type: {self.dataset_type}") + + # Convert to float32 if needed + if self.to_float32: + img = img.astype(np.float32) + + results['img'] = img + results['img_shape'] = img.shape[:2] + results['ori_shape'] = img.shape[:2] + results['wavelengths'] = self.wavelengths + + if logger is not None: + logger.info(f"Finished: {img_path}") + + return results + + def _load_harvard_image(self, img_path): + """Load Harvard dataset image (.mat file).""" + img_cube = loadmat(img_path) + img_hsi = img_cube['ref'][:].astype(np.float32) + + if self.append_rgb: + # Harvard RGB bands: [22, 13, 5] corresponding to red, green, blue + img_rgb = img_hsi[:, :, [22, 13, 5]] + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + + return img + + def _load_umld2015_image(self, img_path): + """Load UMDL2015 dataset image (.mat file).""" + img_cube = loadmat(img_path) + img_hsi = img_cube[list(img_cube.keys())[-1]][:].astype(np.float32) + + if self.append_rgb: + # UMDL2015 RGB bands: [24, 15, 7] corresponding to red, green, blue + img_rgb = img_hsi[:, :, [24, 15, 7]] + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + + return img + + def _load_umns2002_image(self, img_path): + """Load UMNS2002 dataset image (.mat file).""" + img_cube = loadmat(img_path) + img_hsi = img_cube[list(img_cube.keys())[-1]][:].astype(np.float32) + + if self.append_rgb: + # UMNS2002 RGB bands: [22, 13, 5] corresponding to red, green, blue + img_rgb = img_hsi[:,:,[23,14,6]] + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + + return img + + def _load_umns2004_image(self, img_path): + """Load UMNS2004 dataset image (.mat file).""" + img_cube = loadmat(img_path) + img_hsi = img_cube[list(img_cube.keys())[-1]][:].astype(np.float32) + + if self.append_rgb: + # UMNS2004 RGB bands: [24, 15, 7] corresponding to red, green, blue + img_rgb = img_hsi[:, :, [24, 15, 7]] + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + + return img + + def _load_umos_image(self, img_path): + """Load UMOS dataset image (.mat file).""" + img_cube = loadmat(img_path) + img_hsi = img_cube[list(img_cube.keys())[-1]][:].astype(np.float32) + + if self.append_rgb: + # UMOS RGB bands: [22, 13, 5] corresponding to red, green, blue + img_rgb = img_hsi[:,:,[24,15,7]] + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + + return img + + def _load_umri2015_image(self, img_path): + """Load UMRI2015 dataset image (.mat file).""" + img_cube = loadmat(img_path) + img_hsi = img_cube[list(img_cube.keys())[-1]][:].astype(np.float32) + + if self.append_rgb: + # UMRI2015 RGB bands: [24, 15, 7] corresponding to red, green, blue + img_rgb = img_hsi[:, :, [24, 15, 7]] + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + + return img + + def _load_umemm_image(self, img_path): + """Load UMEMM dataset image (.mat file).""" + img_cube = loadmat(img_path) + img_hsi = img_cube[list(img_cube.keys())[-1]][:].astype(np.float32) + + if self.append_rgb: + # UMEMM RGB bands: [24, 15, 7] corresponding to red, green, blue + img_rgb = img_hsi[:,:,[23,14,6]] + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + + return img + + def _load_hyperblood_image(self, img_path): + #print(img_path) + # with rasterio.open('/home/ps/Documents/data/'+img_path) as data: + # img = data.read() # (c, h, w) + # img_cube = np.load(img_path).transpose(1,2,0) + img_cube,wav = ds_load.get_data(img_path) # hsi.shape = (519, 696, 113) + # anno = ds_load.get_anno(filename) + img_rgb = ds_load.get_rgb(img_cube, wav) + img_hsi = img_cube + # img_hsi = (img_hsi - self.min) / (self.max - self.min) + if self.append_rgb: + img_rgb = ds_load.get_rgb(img_cube, wav) + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + # kid = (img - img.min(axis=(0, 1), keepdims=True)) + # mom = (img.max(axis=(0, 1), keepdims=True) - img.min(axis=(0, 1), keepdims=True)) + # img = kid / (mom+1e-10) + # # return img.transpose(1, 2, 0).astype(np.float32) # (h, w, c) + return img + + def _load_hsidrive20_image(self, img_path): + """Load HSI-Drive20 dataset image (.npy file).""" + img_cube = np.load(img_path) + img_hsi = img_cube.astype(np.float32) + + if self.append_rgb: + # HSI-Drive20 special handling for RGB images + rgb_path = img_path.replace('_TC.npy', '_pseudocolor.png') + rgb_path = rgb_path.replace('_MF', '') + rgb_path = rgb_path.replace('/images/', '/RGB/') + rgb_path = rgb_path.replace('/test/', '/') + rgb_path = rgb_path.replace('/training/', '/') + rgb_path = rgb_path.replace('/validation/', '/') + + if os.path.exists(rgb_path): + img_rgb = Image.open(rgb_path) + img_rgb = np.asanyarray(img_rgb).astype(np.float32) / 255 + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + # Fallback: use bands around 650nm, 550nm, 450nm for RGB + if img_hsi.shape[2] >= 25: + img_rgb = img_hsi[:, :, [20, 15, 10]] # Approximate RGB bands + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + else: + img = img_hsi + + return img + + def _load_hotrednir_image(self, img_path): + """Load HOTRedNIR dataset image (.png file).""" + # Try to use the original hsi3d module + img_cube = get_image_loader(img_file=img_path, cellSize=4)[:, :, :-1] + img_hsi = img_cube.astype(np.float32) + + if self.append_rgb: + rgb_path = img_path.replace('/HSI-RedNIR/', '/HSI-RedNIR-FalseColor/').replace(".png", ".jpg") + rgb_cube = get_image_loader(rgb_path, cellSize=-1) + img_rgb = np.array(rgb_cube).astype(np.float32) / 255 + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + + return img + + def _load_arad_1k_31_image(self, img_path): + """Load ARAD_1K_31 dataset image (.mat file).""" + #print(img_path) + # with rasterio.open('/home/ps/Documents/data/'+img_path) as data: + # img = data.read() # (c, h, w) + img_cube = h5py.File(img_path, 'r') + img_hsi = img_cube['cube'][:].transpose(2, 1, 0).astype(np.float32) + # img_hsi = (img_hsi - self.min) / (self.max - self.min) + if self.append_rgb: + rgb_cube_path = img_path.replace('mats', 'rgb') + rgb_cube_path = rgb_cube_path.replace('.mat', '.jpg') + rgb_cube = Image.open(rgb_cube_path) + img_rgb = np.array(rgb_cube).astype(np.float32)/255 + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + # kid = (img - img.min(axis=(0, 1), keepdims=True)) + # mom = (img.max(axis=(0, 1), keepdims=True) - img.min(axis=(0, 1), keepdims=True)) + # img = kid / (mom+1e-10) + # # return img.transpose(1, 2, 0).astype(np.float32) # (h, w, c) + return img + + def _load_arad_1k_16_image(self, img_path): + """Load ARAD_1K_16 dataset image (.mat file).""" + #print(img_path) + # with rasterio.open('/home/ps/Documents/data/'+img_path) as data: + # img = data.read() # (c, h, w) + img_cube = h5py.File(img_path, 'r') + img_hsi = img_cube['cube'][:].transpose(2, 1, 0).astype(np.float32) + # img_hsi = (img_hsi - self.min) / (self.max - self.min) + if self.append_rgb: + img = np.concatenate((img_hsi, img_hsi[:,:,[7,4,1]]), axis=2) + # kid = (img - img.min(axis=(0, 1), keepdims=True)) + # mom = (img.max(axis=(0, 1), keepdims=True) - img.min(axis=(0, 1), keepdims=True)) + # img = kid / (mom+1e-10) + # # return img.transpose(1, 2, 0).astype(np.float32) # (h, w, c) + return img + + def _load_cave_image(self, img_path): + """Load CAVE dataset image (.mat file).""" + img_cube = loadmat(img_path) + img_hsi = img_cube['DataCube'][:].astype(np.float32) + + if self.append_rgb: + img_rgb = img_hsi[:, :, [24, 15, 7]] + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + + return img + + def _load_icvl_image(self, img_path): + """Load ICVL dataset image (.h5 file).""" + img_cube = h5py.File(img_path, 'r') + img_hsi = img_cube['rad'][:].astype(np.float32) + img_rgb = img_cube['rgb'][:].astype(np.float32) + + if self.append_rgb: + img_hsi = np.transpose(img_hsi, (2, 1, 0)) + img_hsi = np.rot90(img_hsi) + img_rgb = np.transpose(img_rgb, (2, 1, 0)) + rgb_height, rgb_width = img_rgb.shape[:2] + img_hsi = cv2.resize(img_hsi, (rgb_width, rgb_height)) + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + def _load_hs_sod_image(self, img_path): + """Load HSSOD dataset image (.h5 file).""" + try: + img_cube = h5py.File(img_path, 'r') + img_hsi = img_cube['hypercube'][:].astype(np.float32) + img_hsi = np.transpose(img_hsi, (2, 1, 0)) + except Exception: + img_cube = loadmat(img_path) + img_hsi = img_cube['hypercube'].astype(np.float32) + + if self.append_rgb: + rgb_cube_path = img_path.replace('hyperspectral', 'color') + rgb_cube_path = rgb_cube_path.replace('.mat', '.jpg') + rgb_cube = Image.open(rgb_cube_path) + img_rgb = np.array(rgb_cube).astype(np.float32) / 255 + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + + return img + + def _load_hsodbit_v2_image(self, img_path): + """Load HSODBIT-V2 dataset image (.mat file).""" + #print(img_path) + try: + img_cube = h5py.File(img_path) + img_hsi = img_cube['dataset'][:].transpose(2,1,0) + except Exception: + img_cube = loadmat(img_path) + img_hsi = img_cube['dataset'].astype(np.float32) + # img_hsi = (img_hsi - self.min) / (self.max - self.min) + if self.append_rgb: + rgb_path = img_path.replace("/hyperspectral/","/color/") + rgb_path = rgb_path.replace(".h5",".jpg") + rgb_cube = Image.open(rgb_path) + img_rgb = np.array(rgb_cube).astype(np.float32)/255 + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + # kid = (img - img.min(axis=(0, 1), keepdims=True)) + # mom = (img.max(axis=(0, 1), keepdims=True) - img.min(axis=(0, 1), keepdims=True)) + # img = kid / (mom+1e-10) + # # return img.transpose(1, 2, 0).astype(np.float32) # (h, w, c) + img = img.transpose(1, 0, 2) + return img + + def _load_vnihdhiatlimafb_image(self, img_path): + """Load VNIHDHIATLIMAFB dataset image (.hdr file).""" + #print(img_path) + img_cube = envi.open(img_path).asarray() + img_hsi = img_cube + # img_hsi = (img_hsi - self.min) / (self.max - self.min) + if self.append_rgb: + img_rgb = img_hsi[:,:,[90, 40, 28]] + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + # kid = (img - img.min(axis=(0, 1), keepdims=True)) + # mom = (img.max(axis=(0, 1), keepdims=True) - img.min(axis=(0, 1), keepdims=True)) + # img = kid / (mom+1e-10) + # # return img.transpose(1, 2, 0).astype(np.float32) # (h, w, c) + img = img.transpose(1, 0, 2) + return img + + def _load_deephsnir_image(self, img_path): + """Load DeepHSNIR dataset image (.bin file).""" + #print(img_path) + img_cube = envi.open(img_path.replace('.bin','.hdr'), img_path).asarray() + img_hsi = img_cube + # img_hsi = (img_hsi - self.min) / (self.max - self.min) + if self.append_rgb: + img = np.concatenate((img_hsi, img_hsi[:,:,[206,124,42]]), axis=2) + # kid = (img - img.min(axis=(0, 1), keepdims=True)) + # mom = (img.max(axis=(0, 1), keepdims=True) - img.min(axis=(0, 1), keepdims=True)) + # img = kid / (mom+1e-10) + # # return img.transpose(1, 2, 0).astype(np.float32) # (h, w, c) + return img + + def _load_deephsvis_image(self, img_path): + """Load DeepHSVIS dataset image (.bin file).""" + #print(img_path) + img_cube = envi.open(img_path.replace('.bin','.hdr'), img_path).asarray() + img_hsi = img_cube + # img_hsi = (img_hsi - self.min) / (self.max - self.min) + if self.append_rgb: + img = np.concatenate((img_hsi, img_hsi[:,:,[74,56,19]]), axis=2) + # kid = (img - img.min(axis=(0, 1), keepdims=True)) + # mom = (img.max(axis=(0, 1), keepdims=True) - img.min(axis=(0, 1), keepdims=True)) + # img = kid / (mom+1e-10) + # # return img.transpose(1, 2, 0).astype(np.float32) # (h, w, c) + return img + + def _load_deephsviscor_image(self, img_path): + """Load DeepHSVISCOR dataset image (.bin file).""" + #print(img_path) + img_cube = envi.open(img_path.replace('.bin','.hdr'), img_path).asarray() + img_hsi = img_cube + # img_hsi = (img_hsi - self.min) / (self.max - self.min) + if self.append_rgb: + img = np.concatenate((img_hsi, img_hsi[:,:,[100,75,24]]), axis=2) + # kid = (img - img.min(axis=(0, 1), keepdims=True)) + # mom = (img.max(axis=(0, 1), keepdims=True) - img.min(axis=(0, 1), keepdims=True)) + # img = kid / (mom+1e-10) + # # return img.transpose(1, 2, 0).astype(np.float32) # (h, w, c) + return img + + def _load_hotvis_image(self, img_path): + """Load HOTVIS dataset image (.png file).""" + # print(img_path) + img_cube = get_image_loader(img_file = img_path, cellSize=4) + img_hsi = img_cube + # img_hsi = (img_hsi - self.min) / (self.max - self.min) + if self.append_rgb: + rgb_path = img_path.replace('/HSI-VIS/', '/HSI-VIS-FalseColor/').replace(".png",".jpg") + rgb_cube = get_image_loader(rgb_path, cellSize=-1) + img_rgb = np.array(rgb_cube).astype(np.float32)/255 + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + # kid = (img - img.min(axis=(0, 1), keepdims=True)) + # mom = (img.max(axis=(0, 1), keepdims=True) - img.min(axis=(0, 1), keepdims=True)) + # img = kid / (mom+1e-10) + # # return img.transpose(1, 2, 0).astype(np.float32) # (h, w, c) + return img + + def _load_hotnir_image(self, img_path): + """Load HOTNIR dataset image (.png file).""" + # print(img_path) + img_cube = get_image_loader(img_file = img_path, cellSize=5) + img_hsi = img_cube + # img_hsi = (img_hsi - self.min) / (self.max - self.min) + if self.append_rgb: + rgb_path = img_path.replace('/HSI-NIR/', '/HSI-NIR-FalseColor/').replace(".png",".jpg") + rgb_cube = get_image_loader(rgb_path, cellSize=-1) + img_rgb = np.array(rgb_cube).astype(np.float32)/255 + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + # kid = (img - img.min(axis=(0, 1), keepdims=True)) + # mom = (img.max(axis=(0, 1), keepdims=True) - img.min(axis=(0, 1), keepdims=True)) + # img = kid / (mom+1e-10) + # # return img.transpose(1, 2, 0).astype(np.float32) # (h, w, c) + return img + + def _load_hsiroad_image(self, img_path): + """Load HSIROAD dataset image (.tif file).""" + # print(img_path) + img_hsi = tifffile.imread(img_path).astype(np.float32) / 255 + if self.append_rgb: + # rgb_path = img_path.replace('_nir.tif', '_rgb.tif') + # img_rgb = tiffile.imread(rgb_path).astype(np.float32) / 255 + img_rgb = img_hsi[[21,13,5],...] + img = np.concatenate((img_hsi, img_rgb), axis=0) + else: + img = img_hsi + img = img.transpose(1,2,0) + # kid = (img - img.min(axis=(0, 1), keepdims=True)) + # mom = (img.max(axis=(0, 1), keepdims=True) - img.min(axis=(0, 1), keepdims=True)) + # img = kid / (mom+1e-10) + # # return img.transpose(1, 2, 0).astype(np.float32) # (h, w, c) + return img + + def _load_hyperspectralcityv2_image(self, img_path): + """Load hyperspectralcityv2 dataset image (.hsd file).""" + # Read HSD file + data= read_HSD(img_path) + + # Normalize data + # data = (data - self.min) / (self.max - self.min) + # data = (data - data.min()) / (data.max() - data.min()) + + if self.append_rgb: + # Create pseudo-RGB from spectral bands (using first 3 bands as placeholder) + # Update with appropriate band indices for RGB representation + if data.shape[2] >= 3: + img_rgb = data[:, :,[51, 15, 6]] # Using first 3 bands for RGB + else: + # If fewer than 3 bands, duplicate available bands + img_rgb = np.repeat(data[:, :, :3], 3, axis=2) + img = np.concatenate((data, img_rgb), axis=2) + else: + img = data + + return img + + def _load_hykov2nir_image(self, img_path): + # Read .mat file + img_cube = loadmat(img_path) + + # Extract the data cube - assuming the last key is the data + img_hsi = img_cube['data'] + + # Normalize data + # img_hsi = (img_hsi - self.min) / (self.max - self.min) + + if self.append_rgb: + # Create pseudo-RGB from spectral bands (using appropriate bands for RGB) + # For now, using first 3 bands as placeholder + if img_hsi.shape[2] >= 3: + img_rgb = img_hsi[:, :, [20, 12, 4]] + else: + img_rgb = np.repeat(img_hsi[:, :, :3], 3, axis=2) + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + + return img + + + def _load_hykov2vis_image(self, img_path): + """Load hykov2vis dataset image (.mat file).""" + # Read .mat file + img_cube = loadmat(img_path) + + # Extract the data cube - assuming the last key is the data + img_hsi = img_cube['data'] + # Normalize data + # img_hsi = (img_hsi - self.min) / (self.max - self.min) + + if self.append_rgb: + # Create pseudo-RGB from spectral bands (using appropriate bands for RGB) + # For now, using first 3 bands as placeholder + if img_hsi.shape[2] >= 3: + img_rgb = img_hsi[:, :, [14, 5, 0]] + else: + img_rgb = np.repeat(img_hsi[:, :, :3], 3, axis=2) + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + + return img + + def _load_hyperdrive_image(self, img_path): + """Load Hyperdrive dataset image (.npz file).""" + img_hsi = np.load(img_path)['cube.npy'] + + if self.append_rgb: + # Create pseudo-RGB from VNIR bands + if img_hsi.shape[2] >= 3: + rgb_path = img_path.replace('.npz', '.png').replace('/HSI_REGISTERED/', '/RGB_REGISTERED/') + img_rgb = np.asarray(Image.open(rgb_path)).astype(np.float32)/255 + # img_rgb = np.asanyarray(img_rgb).astype(np.float32)/255 + # Use appropriate VNIR bands for RGB representation + # img_rgb = img_hsi[:, :, [20, 12, 4]] # Adjust indices based on actual data + else: + img_rgb = np.repeat(img_hsi[:, :, :3], 3, axis=2) + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + + return img + + def _load_hyperdrivevnir_image(self, img_path): + """ + Load VNIR hyperspectral image from file (first 24 bands only). + """ + img_hsi = np.load(img_path)['cube.npy'] + + # Select only the first 24 bands (VNIR) + img_hsi = img_hsi[:, :, :24] + + if self.append_rgb: + # Create pseudo-RGB from VNIR bands + if img_hsi.shape[2] >= 3: + img_rgb = img_hsi[:, :, [20, 12, 4]] + else: + img_rgb = np.repeat(img_hsi[:, :, :3], 3, axis=2) + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + + return img + + def _load_hyperdriveswir_image(self, img_path): + """ + Load SWIR hyperspectral image from file (last 9 bands only). + """ + img_hsi = np.load(img_path)['cube.npy'] + + # Select only the last 9 bands (SWIR) + img_hsi = img_hsi[:, :, 24:33] + + if self.append_rgb: + # Create pseudo-RGB from SWIR bands + if img_hsi.shape[2] >= 3: + img_rgb = img_hsi[:, :, [7,4,1]] + else: + img_rgb = np.repeat(img_hsi[:, :, :3], 3, axis=2) + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + + return img + + + def _load_libhsi_image(self, img_path): + """Load LIBHSI dataset image (.hdr file).""" + img_hsi = np.rot90(envi.open(img_path).asarray().astype(np.float32), -1,axes=(0,1)) + + + if self.append_rgb: + # Get corresponding RGB image + rgb_path = img_path.replace('.hdr', '.png').replace('reflectance_cubes', 'rgb') + + # Load RGB image using Pillow + img_rgb_pil = Image.open(rgb_path) + if img_rgb_pil.mode != 'RGB': + img_rgb_pil = img_rgb_pil.convert('RGB') + + # Convert to numpy array and normalize to [0, 1] + img_rgb = np.array(img_rgb_pil).astype(np.float32) / 255.0 + + # Ensure both images have the same spatial dimensions + hsi_h, hsi_w = img_hsi.shape[:2] + rgb_h, rgb_w = img_rgb.shape[:2] + + if hsi_h != rgb_h or hsi_w != rgb_w: + # Resize RGB to match HSI dimensions using Pillow + img_rgb_pil_resized = img_rgb_pil.resize((hsi_w, hsi_h), Image.LANCZOS) + img_rgb = np.array(img_rgb_pil_resized).astype(np.float32) / 255.0 + # Concatenate HSI and RGB channels + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + + return img + + def _load_virginiatree_image(self, img_path): + """Load VirginiaTechTrees dataset image (.hdr file).""" + # Load hyperspectral image using spectral library + img_hsi = envi.open(img_path).asarray().astype(np.float32) + + # Normalize to [0, 1] range + img_hsi = img_hsi / 4096 # Normalize 16-bit data + + if self.append_rgb: + # Extract RGB channels from hyperspectral data + # Using bands that correspond to red, green, blue wavelengths + # These indices may need adjustment based on actual wavelength mapping + red_band = 163 # Approximate red band index + green_band = 93 # Approximate green band index + blue_band = 50 # Approximate blue band index + + img_rgb = img_hsi[:, :, [red_band, green_band, blue_band]] + + # Concatenate HSI and RGB channels + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + + img = img.transpose(1, 0, 2) + return img + + def _load_fiftyoutdoor_image(self, img_path): + """Load FiftyOutdoor dataset image (.mat file).""" + # Load hyperspectral image from .mat file + data = loadmat(img_path) + img_hsi = data['hsi'].astype(np.float32) + + # Normalize to [0, 1] range if needed + if img_hsi.max() > 1.0: + img_hsi = img_hsi / img_hsi.max() + + if self.append_rgb: + # Extract RGB channels from hyperspectral data + # Using bands that correspond to red, green, blue wavelengths + # For 33 bands with wavelengths 400-720nm, select appropriate bands: + # Red: ~650nm (band 25), Green: ~550nm (band 15), Blue: ~450nm (band 5) + + img_rgb = img_hsi[:, :, [22, 12, 6]] + + # Concatenate HSI and RGB channels + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + + return img + + def _load_aphid_image(self, img_path): + """Load APHID dataset image (.npy file).""" + #print(img_path) + # with rasterio.open('/home/ps/Documents/data/'+img_path) as data: + # img = data.read() # (c, h, w) + img_cube = np.load(img_path).transpose(1,2,0) + img_hsi = img_cube + # img_hsi = (img_hsi - self.min) / (self.max - self.min) + if self.append_rgb: + img_rgb = img_hsi[:,:,[84, 40, 13]] + img = np.concatenate((img_hsi, img_rgb), axis=2) + else: + img = img_hsi + # kid = (img - img.min(axis=(0, 1), keepdims=True)) + # mom = (img.max(axis=(0, 1), keepdims=True) - img.min(axis=(0, 1), keepdims=True)) + # img = kid / (mom+1e-10) + # # return img.transpose(1, 2, 0).astype(np.float32) # (h, w, c) + return img + + def _normalize_image(self, img): + """Normalize image using dataset-specific parameters.""" + # Normalize to [0, 1] range + img = (img - self.min_val) / (self.max_val - self.min_val) + return img + + +# Pipeline configurations for different datasets +harvard_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='harvard', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +umld2015_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='umld2015', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +umemm_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='umemm', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +umns2002_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='umns2002', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +umns2004_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='umns2004', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +umos_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='umos', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +umri2015_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='umri2015', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hyperblood_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hyperblood', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hsidrive20_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hsidrive20', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hotrednir_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hotrednir', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +arad_1k_31_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='arad_1k_31', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +arad_1k_16_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='arad_1k_16', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +cave_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='cave', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +icvl_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='icvl', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hs_sod_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hs_sod', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hsodbit_v2_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hsodbit_v2', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + + +# Test pipelines (without augmentation) +harvard_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='harvard', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +umld2015_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='umld2015', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +umemm_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='umemm', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +umns2002_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='umns2002', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +umns2004_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='umns2004', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +umos_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='umos', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +umri2015_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='umri2015', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hyperblood_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hyperblood', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hsidrive20_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hsidrive20', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hotrednir_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hotrednir', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +arad_1k_31_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='arad_1k_31', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +arad_1k_16_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='arad_1k_16', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +cave_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='cave', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +icvl_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='icvl', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hs_sod_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hs_sod', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hsodbit_v2_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hsodbit_v2', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + + +# New dataset pipelines +vnihdhiatlimafb_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='vnihdhiatlimafb', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +vnihdhiatlimafb_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='vnihdhiatlimafb', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +deephsnir_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='deephsnir', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +deephsnir_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='deephsnir', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +deephsvis_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='deephsvis', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +deephsvis_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='deephsvis', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +deephsviscor_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='deephsviscor', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +deephsviscor_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='deephsviscor', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hotvis_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hotvis', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hotvis_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hotvis', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hotnir_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hotnir', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hotnir_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hotnir', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hsiroad_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hsiroad', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hsiroad_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hsiroad', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hyperspectralcityv2_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hyperspectralcityv2', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hyperspectralcityv2_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hyperspectralcityv2', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hykov2nir_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hykov2nir', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hykov2nir_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hykov2nir', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hykov2vis_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hykov2vis', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hykov2vis_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hykov2vis', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hyperdrive_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hyperdrive', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hyperdrive_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hyperdrive', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hyperdrivevnir_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hyperdrivevnir', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hyperdrivevnir_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hyperdrivevnir', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hyperdriveswir_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hyperdriveswir', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +hyperdriveswir_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='hyperdriveswir', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +libhsi_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='libhsi', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +libhsi_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='libhsi', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +virginiatree_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='virginiatree', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +virginiatree_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='virginiatree', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +fiftyoutdoor_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='fiftyoutdoor', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +fiftyoutdoor_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='fiftyoutdoor', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +# APHID (Agricultural plant hyperspectral imaging dataset) pipeline configurations +aphid_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='aphid', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +aphid_test_pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type='aphid', to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) +] + +# Universal training pipeline for all datasets +def create_universal_train_pipeline(dataset_type, crop_size=(512, 512)): + """Create a universal training pipeline for all hyperspectral datasets. + + Args: + dataset_type (str): Type of dataset + crop_size (tuple): Crop size for RandomCrop + + Returns: + list: Training pipeline configuration + """ + pipeline = [ + dict(type='LoadHyperspectralImage', dataset_type=dataset_type, to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + # dict(type='RandomResize', scale=(512, 512), ratio_range=(0.5, 2.0), keep_ratio=True), + # dict(type='RandomCrop', crop_size=crop_size), + dict(type='RandomFlip', prob=.5), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'flip', 'flip_direction', 'wavelengths')), + ] + return pipeline + + +# Universal test pipeline for all datasets +def create_universal_test_pipeline(dataset_type): + """Create a universal test pipeline for all hyperspectral datasets. + + Args: + dataset_type (str): Type of dataset + + Returns: + list: Test pipeline configuration + """ + return [ + dict(type='LoadHyperspectralImage', dataset_type=dataset_type, to_float32=True, append_rgb=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'flip', 'flip_direction', 'wavelengths')) + ] + + +# Pre-defined universal pipelines for common datasets +harvard_universal_train_pipeline = create_universal_train_pipeline('harvard') +harvard_universal_test_pipeline = create_universal_test_pipeline('harvard') + +umld2015_universal_train_pipeline = create_universal_train_pipeline('umld2015') +umld2015_universal_test_pipeline = create_universal_test_pipeline('umld2015') + +hsodbitv2_universal_train_pipeline = create_universal_train_pipeline('hsodbitv2') +hsodbitv2_universal_test_pipeline = create_universal_test_pipeline('hsodbitv2') + +vnihdhiatlimafb_universal_train_pipeline = create_universal_train_pipeline('vnihdhiatlimafb') +vnihdhiatlimafb_universal_test_pipeline = create_universal_test_pipeline('vnihdhiatlimafb') + +virginia_tech_tree_universal_train_pipeline = create_universal_train_pipeline('virginia_tech_tree') +virginia_tech_tree_universal_test_pipeline = create_universal_test_pipeline('virginia_tech_tree') + +# Additional datasets +arad_1k_31_universal_train_pipeline = create_universal_train_pipeline('arad_1k_31') +arad_1k_31_universal_test_pipeline = create_universal_test_pipeline('arad_1k_31') + +hs_sod_universal_train_pipeline = create_universal_train_pipeline('hs_sod') +hs_sod_universal_test_pipeline = create_universal_test_pipeline('hs_sod') + +cave_universal_train_pipeline = create_universal_train_pipeline('cave') +cave_universal_test_pipeline = create_universal_test_pipeline('cave') + +icvl_universal_train_pipeline = create_universal_train_pipeline('icvl') +icvl_universal_test_pipeline = create_universal_test_pipeline('icvl') + +# Additional universal pipelines for all datasets +umld2015_universal_train_pipeline = create_universal_train_pipeline('umld2015') +umld2015_universal_test_pipeline = create_universal_test_pipeline('umld2015') + +umns2002_universal_train_pipeline = create_universal_train_pipeline('umns2002') +umns2002_universal_test_pipeline = create_universal_test_pipeline('umns2002') + +umns2004_universal_train_pipeline = create_universal_train_pipeline('umns2004') +umns2004_universal_test_pipeline = create_universal_test_pipeline('umns2004') + +umos_universal_train_pipeline = create_universal_train_pipeline('umos') +umos_universal_test_pipeline = create_universal_test_pipeline('umos') + +umri2015_universal_train_pipeline = create_universal_train_pipeline('umri2015') +umri2015_universal_test_pipeline = create_universal_test_pipeline('umri2015') + +umemm_universal_train_pipeline = create_universal_train_pipeline('umemm') +umemm_universal_test_pipeline = create_universal_test_pipeline('umemm') + +hyperblood_universal_train_pipeline = create_universal_train_pipeline('hyperblood') +hyperblood_universal_test_pipeline = create_universal_test_pipeline('hyperblood') + +hsidrive20_universal_train_pipeline = create_universal_train_pipeline('hsidrive20') +hsidrive20_universal_test_pipeline = create_universal_test_pipeline('hsidrive20') + +hotrednir_universal_train_pipeline = create_universal_train_pipeline('hotrednir') +hotrednir_universal_test_pipeline = create_universal_test_pipeline('hotrednir') + +arad_1k_16_universal_train_pipeline = create_universal_train_pipeline('arad_1k_16') +arad_1k_16_universal_test_pipeline = create_universal_test_pipeline('arad_1k_16') + +hotvis_universal_train_pipeline = create_universal_train_pipeline('hotvis') +hotvis_universal_test_pipeline = create_universal_test_pipeline('hotvis') + +hotnir_universal_train_pipeline = create_universal_train_pipeline('hotnir') +hotnir_universal_test_pipeline = create_universal_test_pipeline('hotnir') + +libhsi_universal_train_pipeline = create_universal_train_pipeline('libhsi') +libhsi_universal_test_pipeline = create_universal_test_pipeline('libhsi') + +fiftyoutdoor_universal_train_pipeline = create_universal_train_pipeline('fiftyoutdoor') +fiftyoutdoor_universal_test_pipeline = create_universal_test_pipeline('fiftyoutdoor') + +aphid_universal_train_pipeline = create_universal_train_pipeline('aphid') +aphid_universal_test_pipeline = create_universal_test_pipeline('aphid') + +hyperspectralcityv2_universal_train_pipeline = create_universal_train_pipeline('hyperspectralcityv2') +hyperspectralcityv2_universal_test_pipeline = create_universal_test_pipeline('hyperspectralcityv2') + +hykov2nir_universal_train_pipeline = create_universal_train_pipeline('hykov2nir') +hykov2nir_universal_test_pipeline = create_universal_test_pipeline('hykov2nir') + +hykov2vis_universal_train_pipeline = create_universal_train_pipeline('hykov2vis') +hykov2vis_universal_test_pipeline = create_universal_test_pipeline('hykov2vis') + +deephsnir_universal_train_pipeline = create_universal_train_pipeline('deephsnir') +deephsnir_universal_test_pipeline = create_universal_test_pipeline('deephsnir') + +deephsvis_universal_train_pipeline = create_universal_train_pipeline('deephsvis') +deephsvis_universal_test_pipeline = create_universal_test_pipeline('deephsvis') + +deephsviscor_universal_train_pipeline = create_universal_train_pipeline('deephsviscor') +deephsviscor_universal_test_pipeline = create_universal_test_pipeline('deephsviscor') + +hsiroad_universal_train_pipeline = create_universal_train_pipeline('hsiroad') +hsiroad_universal_test_pipeline = create_universal_test_pipeline('hsiroad') + +hyperdrivevnir_universal_train_pipeline = create_universal_train_pipeline('hyperdrivevnir') +hyperdrivevnir_universal_test_pipeline = create_universal_test_pipeline('hyperdrivevnir') + +hyperdriveswir_universal_train_pipeline = create_universal_train_pipeline('hyperdriveswir') +hyperdriveswir_universal_test_pipeline = create_universal_test_pipeline('hyperdriveswir') + +hyperdrive_universal_train_pipeline = create_universal_train_pipeline('hyperdrive') +hyperdrive_universal_test_pipeline = create_universal_test_pipeline('hyperdrive') diff --git a/hyperspectral_image_reader/read_dataset_image.py b/hyperspectral_image_reader/read_dataset_image.py new file mode 100644 index 0000000000000000000000000000000000000000..54bb7f4a812fd74cdea3f84129723735103527c4 --- /dev/null +++ b/hyperspectral_image_reader/read_dataset_image.py @@ -0,0 +1,119 @@ +import os +import sys +import argparse +import numpy as np + +# Ensure workspace is in python path to allow importing configs +current_dir = os.path.abspath(os.path.dirname(__file__)) +parent_dir = os.path.abspath(os.path.join(current_dir, '..')) +if current_dir not in sys.path: + sys.path.append(current_dir) +if parent_dir not in sys.path: + sys.path.append(parent_dir) + +try: + from hyperspectral_pipelines import LoadHyperspectralImage +except ImportError as e: + print(f"Error: Could not import LoadHyperspectralImage. Detail: {e}") + sys.exit(1) + +DATASET_EXTENSIONS = { + # .mat / .h5 formats + 'harvard': '.mat', 'umld2015': '.mat', 'umns2002': '.mat', 'umns2004': '.mat', + 'umos': '.mat', 'umri2015': '.mat', 'umemm': '.mat', 'hyperblood': '.mat', + 'arad_1k_31': '.mat', 'arad_1k_16': '.mat', 'cave': '.mat', 'fiftyoutdoor': '.mat', + 'icvl': '.h5', 'hs_sod': '.h5', 'hsodbitv2': '.mat', + # .npy / .npz formats + 'hsidrive20': '.npy', 'aphid': '.npy', + 'hyperdrive': '.npz', 'hyperdrivevnir': '.npz', 'hyperdriveswir': '.npz', + # ENVI formats (requires .hdr + raw file, pass the .hdr file path) + 'libhsi': '.hdr', 'virginia_tech_tree': '.hdr', 'vnihdhiatlimafb': '.hdr', + # ENVI formats (with .bin, requires .hdr + .bin, pass the .bin file path) + 'deephsnir': '.bin', 'deephsvis': '.bin', 'deephsviscor': '.bin', + # Image formats + 'hotvis': '.png', 'hotnir': '.png', 'hotrednir': '.png', + 'hsiroad': '.tif', + # Custom format + 'hyperspectralcityv2': '.hsd', +} + +def load_hypervision_matrix(file_path, dataset_name): + """ + Loads a hyperspectral image and processes it into the exact matrix shape and scale + expected by the HyperVision / HyperFree models. + + Args: + file_path (str): Path to the image file. + dataset_name (str): Name of the dataset (e.g., 'harvard', 'arad_1k_31', etc.). + + Returns: + np.ndarray: Processed matrix of shape (H_ori, W_ori, C_hsi) scaled to [0, 255]. + """ + if not os.path.exists(file_path): + raise FileNotFoundError(f"Image path not found: {file_path}") + + # Validate file extension + _, ext = os.path.splitext(file_path) + expected_ext = DATASET_EXTENSIONS.get(dataset_name) + if expected_ext and ext.lower() != expected_ext.lower(): + print(f"Warning: Expected file extension '{expected_ext}' for dataset '{dataset_name}', but got '{ext}'.") + if expected_ext == '.hdr': + print("Note: ENVI datasets require both the header (.hdr) and the raw binary data file. Please pass the path to the .hdr file.") + elif expected_ext == '.bin': + print("Note: DeepHS datasets require both the binary data (.bin) and the header (.hdr) file. Please pass the path to the .bin file.") + elif expected_ext in ['.mat', '.h5']: + print("Note: This dataset requires a MATLAB (.mat) or HDF5 (.h5) formatted cube.") + elif expected_ext == '.npz': + print("Note: This dataset requires a NumPy compressed archive (.npz) containing 'cube.npy'.") + print() + + # Initialize the dataset loader pipeline + loader = LoadHyperspectralImage(dataset_type=dataset_name, to_float32=True, append_rgb=True) + + # Run the transform + results = {'img_path': file_path} + results = loader(results) + + img = results['img'] # Loaded image of shape (H, W, C) + + # Check if the loaded image contains appended RGB channels. + # The cache image might contain RGB (C = bands + 3), while the raw HSI might not (C = bands). + num_hsi_channels = loader.bands + actual_channels = img.shape[2] + + if actual_channels > num_hsi_channels: + # Strip the last 3 channels (the appended RGB bands) + img = img[:, :, :num_hsi_channels] + + # Min-Max normalization per image sample to [0, 255] + hsi_min = img.min() + hsi_max = img.max() + if hsi_max > hsi_min: + processed_matrix = 255.0 * (img - hsi_min) / (hsi_max - hsi_min) + else: + processed_matrix = np.zeros_like(img) + + return processed_matrix + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description="Read HSI dataset image and output the matrix processed for HyperVision.") + parser.add_argument('--path', type=str, required=True, help="Path to the HSI image file.") + parser.add_argument('--dataset', type=str, required=True, help="Dataset name (e.g. harvard, arad_1k_31, icvl, etc.).") + parser.add_argument('--output', type=str, default=None, help="Optional path to save the output matrix as a .npy file.") + + args = parser.parse_args() + + try: + matrix = load_hypervision_matrix(args.path, args.dataset) + print("\nSuccessfully loaded and processed HSI image.") + print(f"Matrix shape (H, W, C): {matrix.shape}") + print(f"Value range: [{matrix.min():.2f}, {matrix.max():.2f}]") + print(f"Data type: {matrix.dtype}") + + if args.output: + np.save(args.output, matrix) + print(f"Saved processed matrix to: {args.output}") + + except Exception as e: + print(f"Error during execution: {e}") + sys.exit(1) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..55acc20557dfd74071c18f7d3b28d946ddc62697 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,84 @@ +addict==2.4.0 +affine==2.4.0 +attrs==26.1.0 +certifi==2026.6.17 +click==8.4.2 +click-plugins==1.1.1.2 +cligj==0.7.2 +contourpy==1.3.2 +cuda-bindings==12.9.4 +cuda-pathfinder==1.5.6 +cupy-cuda12x==14.1.1 +cycler==0.12.1 +filelock==3.29.0 +fonttools==4.63.0 +fsspec==2026.4.0 +GDAL @ file:///home/task_178125945642559/croot/libgdal-core_1781261927835/work/build/swig/python +h5py==3.16.0 +hdf5plugin==7.0.0 +ImageIO @ file:///home/task_177400278551675/croot/imageio_1774003043916/work +Jinja2==3.1.6 +kiwisolver==1.5.0 +lazy-loader @ file:///home/task_177375491044565/croot/lazy_loader_1773754937338/work +markdown-it-py==4.2.0 +MarkupSafe==3.0.3 +matplotlib==3.10.9 +mdurl==0.1.2 +mkl-service==2.7.2 +mkl_fft @ file:///home/task_177730042096369/croot/mkl_fft_1777300464161/work +mkl_random @ file:///home/task_178236946501460/croot/mkl_random_1782369492709/work +mmcv==2.1.0 +mmcv-lite==2.1.0 +mmdet==3.3.0 +mmengine==0.10.7 +mpmath==1.3.0 +networkx @ file:///croot/networkx_1737039604450/work +numpy @ file:///home/task_177619032023410/croot/numpy_and_numpy_base_1776190368994/work/dist/numpy-2.2.5-cp310-cp310-linux_x86_64.whl#sha256=0148211ba260b4bb27c3ceaa36d0a564fda110f5e80228fa1a30b81ba4e6f53b +nvidia-cublas-cu12==12.8.4.1 +nvidia-cuda-cupti-cu12==12.8.90 +nvidia-cuda-nvrtc-cu12==12.8.93 +nvidia-cuda-runtime-cu12==12.8.90 +nvidia-cudnn-cu12==9.10.2.21 +nvidia-cufft-cu12==11.3.3.83 +nvidia-cufile-cu12==1.13.1.3 +nvidia-curand-cu12==10.3.9.90 +nvidia-cusolver-cu12==11.7.3.90 +nvidia-cusparse-cu12==12.5.8.93 +nvidia-cusparselt-cu12==0.7.1 +nvidia-nccl-cu12==2.27.5 +nvidia-nvjitlink-cu12==12.8.93 +nvidia-nvshmem-cu12==3.4.5 +nvidia-nvtx-cu12==12.8.90 +opencv-python==4.13.0.92 +packaging==26.0 +pandas==2.3.3 +pillow @ file:///home/task_178098864793104/croot/pillow_1780988673921/work +platformdirs==4.10.0 +pycocotools==2.0.11 +Pygments==2.20.0 +pyparsing==3.3.2 +python-dateutil==2.9.0.post0 +pytz==2026.2 +PyYAML==6.0.3 +rasterio==1.4.4 +rich==15.0.0 +scikit-image @ file:///home/task_176477234103261/conda-bld/scikit-image_1764772822609/work +scipy @ file:///home/task_177627750685798/croot/scipy_1776277546737/work/dist/scipy-1.15.3-cp310-cp310-linux_x86_64.whl#sha256=7b2aac7107989ccfc45554ee68822a9bf970562f95275bc51d8febc0a341a335 +setuptools-scm==10.2.0 +shapely==2.1.2 +six==1.17.0 +spectral==0.24 +sympy==1.14.0 +termcolor==3.3.0 +terminaltables==3.1.10 +tifffile @ file:///croot/tifffile_1741164537642/work +tomli==2.4.1 +torch==2.10.0+cu128 +torchaudio==2.10.0+cu128 +torchvision==0.25.0+cu128 +tqdm==4.68.3 +triton==3.6.0 +typing_extensions==4.15.0 +tzdata==2026.2 +vcs-versioning==2.2.0 +yapf==0.43.0