IronKitty commited on
Commit
d9375f3
·
verified ·
1 Parent(s): a37133d

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. HyperVision/__init__.py +11 -0
  2. HyperVision/__pycache__/__init__.cpython-310.pyc +0 -0
  3. HyperVision/__pycache__/__init__.cpython-311.pyc +0 -0
  4. HyperVision/__pycache__/__init__.cpython-313.pyc +0 -0
  5. HyperVision/__pycache__/automatic_mask_generator.cpython-310.pyc +0 -0
  6. HyperVision/__pycache__/automatic_mask_generator.cpython-311.pyc +0 -0
  7. HyperVision/__pycache__/build_HyperFree.cpython-311.pyc +0 -0
  8. HyperVision/__pycache__/build_HyperVision.cpython-310.pyc +0 -0
  9. HyperVision/__pycache__/build_HyperVision.cpython-313.pyc +0 -0
  10. HyperVision/__pycache__/predictor.cpython-310.pyc +0 -0
  11. HyperVision/__pycache__/predictor.cpython-311.pyc +0 -0
  12. HyperVision/automatic_mask_generator.py +395 -0
  13. HyperVision/build_HyperVision.py +136 -0
  14. HyperVision/modeling/__init__.py +11 -0
  15. HyperVision/modeling/__pycache__/__init__.cpython-310.pyc +0 -0
  16. HyperVision/modeling/__pycache__/__init__.cpython-311.pyc +0 -0
  17. HyperVision/modeling/__pycache__/common.cpython-310.pyc +0 -0
  18. HyperVision/modeling/__pycache__/common.cpython-311.pyc +0 -0
  19. HyperVision/modeling/__pycache__/image_encoder.cpython-310.pyc +0 -0
  20. HyperVision/modeling/__pycache__/image_encoder.cpython-311.pyc +0 -0
  21. HyperVision/modeling/__pycache__/mask_decoder.cpython-310.pyc +0 -0
  22. HyperVision/modeling/__pycache__/mask_decoder.cpython-311.pyc +0 -0
  23. HyperVision/modeling/__pycache__/prompt_encoder.cpython-310.pyc +0 -0
  24. HyperVision/modeling/__pycache__/prompt_encoder.cpython-311.pyc +0 -0
  25. HyperVision/modeling/__pycache__/sam.cpython-310.pyc +0 -0
  26. HyperVision/modeling/__pycache__/sam.cpython-311.pyc +0 -0
  27. HyperVision/modeling/__pycache__/scale_aware_PE.cpython-310.pyc +0 -0
  28. HyperVision/modeling/__pycache__/scale_aware_PE.cpython-311.pyc +0 -0
  29. HyperVision/modeling/__pycache__/transformer.cpython-310.pyc +0 -0
  30. HyperVision/modeling/__pycache__/transformer.cpython-311.pyc +0 -0
  31. HyperVision/modeling/common.py +37 -0
  32. HyperVision/modeling/image_encoder.py +672 -0
  33. HyperVision/modeling/mask_decoder.py +180 -0
  34. HyperVision/modeling/prompt_encoder.py +214 -0
  35. HyperVision/modeling/sam.py +163 -0
  36. HyperVision/modeling/scale_aware_PE.py +65 -0
  37. HyperVision/modeling/transformer.py +234 -0
  38. HyperVision/predictor.py +310 -0
  39. HyperVision/utils/__init__.py +5 -0
  40. HyperVision/utils/__pycache__/__init__.cpython-310.pyc +0 -0
  41. HyperVision/utils/__pycache__/__init__.cpython-311.pyc +0 -0
  42. HyperVision/utils/__pycache__/amg.cpython-310.pyc +0 -0
  43. HyperVision/utils/__pycache__/amg.cpython-311.pyc +0 -0
  44. HyperVision/utils/__pycache__/spectral_process_utils.cpython-310.pyc +0 -0
  45. HyperVision/utils/__pycache__/spectral_process_utils.cpython-311.pyc +0 -0
  46. HyperVision/utils/__pycache__/transforms.cpython-310.pyc +0 -0
  47. HyperVision/utils/__pycache__/transforms.cpython-311.pyc +0 -0
  48. HyperVision/utils/amg.py +346 -0
  49. HyperVision/utils/spectral_process_utils.py +146 -0
  50. HyperVision/utils/transforms.py +102 -0
HyperVision/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .build_HyperVision import (
2
+ _build_HyperVision,
3
+ build_HyperVision,
4
+ build_HyperVision_h,
5
+ build_HyperVision_l,
6
+ build_HyperVision_b,
7
+ HyperVision_model_registry,
8
+ )
9
+
10
+ from .predictor import HyperVision_Predictor
11
+ from .automatic_mask_generator import SamAutomaticMaskGenerator
HyperVision/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (468 Bytes). View file
 
HyperVision/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (611 Bytes). View file
 
HyperVision/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (514 Bytes). View file
 
HyperVision/__pycache__/automatic_mask_generator.cpython-310.pyc ADDED
Binary file (12.6 kB). View file
 
HyperVision/__pycache__/automatic_mask_generator.cpython-311.pyc ADDED
Binary file (20.5 kB). View file
 
HyperVision/__pycache__/build_HyperFree.cpython-311.pyc ADDED
Binary file (5.1 kB). View file
 
HyperVision/__pycache__/build_HyperVision.cpython-310.pyc ADDED
Binary file (3.11 kB). View file
 
HyperVision/__pycache__/build_HyperVision.cpython-313.pyc ADDED
Binary file (4.55 kB). View file
 
HyperVision/__pycache__/predictor.cpython-310.pyc ADDED
Binary file (10.3 kB). View file
 
HyperVision/__pycache__/predictor.cpython-311.pyc ADDED
Binary file (14.7 kB). View file
 
HyperVision/automatic_mask_generator.py ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ from torchvision.ops.boxes import batched_nms, box_area # type: ignore
4
+
5
+ from typing import Any, Dict, List, Optional, Tuple
6
+ import torch.nn.functional as F
7
+ from .modeling import Sam
8
+ from .predictor import HyperVision_Predictor
9
+ from .utils.amg import (
10
+ MaskData,
11
+ area_from_rle,
12
+ batch_iterator,
13
+ batched_mask_to_box,
14
+ box_xyxy_to_xywh,
15
+ build_all_layer_point_grids,
16
+ calculate_stability_score,
17
+ coco_encode_rle,
18
+ generate_crop_boxes,
19
+ is_box_near_crop_edge,
20
+ mask_to_rle_pytorch,
21
+ remove_small_regions,
22
+ rle_to_mask,
23
+ uncrop_boxes_xyxy,
24
+ uncrop_masks,
25
+ uncrop_points,
26
+ )
27
+
28
+
29
+ class SamAutomaticMaskGenerator:
30
+ def __init__(
31
+ self,
32
+ model: Sam,
33
+ points_per_side: Optional[int] = 32,
34
+ points_per_batch: int = 64,
35
+ pred_iou_thresh: float = 0.88,
36
+ stability_score_thresh: float = 0.95,
37
+ stability_score_offset: float = 1.0,
38
+ box_nms_thresh: float = 0.7,
39
+ crop_n_layers: int = 0,
40
+ crop_nms_thresh: float = 0.7,
41
+ crop_overlap_ratio: float = 512 / 1500,
42
+ crop_n_points_downscale_factor: int = 1,
43
+ point_grids: Optional[List[np.ndarray]] = None,
44
+ min_mask_region_area: int = 0,
45
+ output_mode: str = "binary_mask",
46
+ ) -> None:
47
+ """
48
+ Using a SAM model, generates masks for the entire image.
49
+ Generates a grid of point prompts over the image, then filters
50
+ low quality and duplicate mask[s. The default settings are chosen
51
+ for SAM with a ViT-H backbone.
52
+
53
+ Arguments:
54
+ model (Sam): The SAM model to use for mask prediction.
55
+ points_per_side (int or None): The number of points to be sampled
56
+ along one side of the image. The total number of points is
57
+ points_per_side**2. If None, 'point_grids' must provide explicit
58
+ point sampling.
59
+ points_per_batch (int): Sets the number of points run simultaneously
60
+ by the model. Higher numbers may be faster but use more GPU memory.
61
+ pred_iou_thresh (float): A filtering threshold in [0,1], using the
62
+ model's predicted mask quality.
63
+ stability_score_thresh (float): A filtering threshold in [0,1], using
64
+ the stability of the mask under changes to the cutoff used to binarize
65
+ the model's mask predictions.
66
+ stability_score_offset (float): The amount to shift the cutoff when
67
+ calculated the stability score.
68
+ box_nms_thresh (float): The box IoU cutoff used by non-maximal
69
+ suppression to filter duplicate masks.
70
+ crop_n_layers (int): If >0, mask prediction will be run again on
71
+ crops of the image. Sets the number of layers to run, where each
72
+ layer has 2**i_layer number of image crops.
73
+ crop_nms_thresh (float): The box IoU cutoff used by non-maximal
74
+ suppression to filter duplicate masks between different crops.
75
+ crop_overlap_ratio (float): Sets the degree to which crops overlap.
76
+ In the first crop layer, crops will overlap by this fraction of
77
+ the image length. Later layers with more crops scale down this overlap.
78
+ crop_n_points_downscale_factor (int): The number of points-per-side
79
+ sampled in layer n is scaled down by crop_n_points_downscale_factor**n.
80
+ point_grids (list(np.ndarray) or None): A list over explicit grids
81
+ of points used for sampling, normalized to [0,1]. The nth grid in the
82
+ list is used in the nth crop layer. Exclusive with points_per_side.
83
+ min_mask_region_area (int): If >0, postprocessing will be applied
84
+ to remove disconnected regions and holes in masks with area smaller
85
+ than min_mask_region_area. Requires opencv.
86
+ output_mode (str): The form masks are returned in. Can be 'binary_mask',
87
+ 'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools.
88
+ For large resolutions, 'binary_mask' may consume large amounts of
89
+ memory.
90
+ """
91
+
92
+ assert (points_per_side is None) != (
93
+ point_grids is None
94
+ ), "Exactly one of points_per_side or point_grid must be provided."
95
+ if points_per_side is not None:
96
+ self.point_grids = build_all_layer_point_grids(
97
+ points_per_side,
98
+ crop_n_layers,
99
+ crop_n_points_downscale_factor,
100
+ )
101
+ elif point_grids is not None:
102
+ self.point_grids = point_grids
103
+ else:
104
+ raise ValueError("Can't have both points_per_side and point_grid be None.")
105
+
106
+ assert output_mode in [
107
+ "binary_mask",
108
+ "uncompressed_rle",
109
+ "coco_rle",
110
+ ], f"Unknown output_mode {output_mode}."
111
+ if output_mode == "coco_rle":
112
+ from pycocotools import mask as mask_utils # type: ignore # noqa: F401
113
+
114
+ if min_mask_region_area > 0:
115
+ import cv2 # type: ignore # noqa: F401
116
+
117
+ self.predictor = HyperVision_Predictor(model)
118
+ self.points_per_batch = points_per_batch
119
+ self.pred_iou_thresh = pred_iou_thresh
120
+ self.stability_score_thresh = stability_score_thresh
121
+ self.stability_score_offset = stability_score_offset
122
+ self.box_nms_thresh = box_nms_thresh
123
+ self.crop_n_layers = crop_n_layers
124
+ self.crop_nms_thresh = crop_nms_thresh
125
+ self.crop_overlap_ratio = crop_overlap_ratio
126
+ self.crop_n_points_downscale_factor = crop_n_points_downscale_factor
127
+ self.min_mask_region_area = min_mask_region_area
128
+ self.output_mode = output_mode
129
+
130
+ @torch.no_grad()
131
+ def generate(self, image: np.ndarray, spectral_lengths = None, GSD=None) -> List[Dict[str, Any]]:
132
+ """
133
+ Generates masks for the given image.
134
+
135
+ Arguments:
136
+ image (np.ndarray): The image to generate masks for, in HWC uint8 format.
137
+
138
+ Returns:
139
+ list(dict(str, any)): A list over records for masks. Each record is
140
+ a dict containing the following keys:
141
+ segmentation (dict(str, any) or np.ndarray): The mask. If
142
+ output_mode='binary_mask', is an array of shape HW. Otherwise,
143
+ is a dictionary containing the RLE.
144
+ bbox (list(float)): The box around the mask, in XYWH format.
145
+ area (int): The area in pixels of the mask.
146
+ predicted_iou (float): The model's own prediction of the mask's
147
+ quality. This is filtered by the pred_iou_thresh parameter.
148
+ point_coords (list(list(float))): The point coordinates input
149
+ to the model to generate this mask.
150
+ stability_score (float): A measure of the mask's quality. This
151
+ is filtered on using the stability_score_thresh parameter.
152
+ crop_box (list(float)): The crop of the image used to generate
153
+ the mask, given in XYWH format.
154
+ """
155
+
156
+ # Generate masks
157
+ mask_data = self._generate_masks(image, spectral_lengths, GSD)
158
+
159
+ # Filter small disconnected regions and holes in masks
160
+ if self.min_mask_region_area > 0:
161
+ mask_data = self.postprocess_small_regions(
162
+ mask_data,
163
+ self.min_mask_region_area,
164
+ max(self.box_nms_thresh, self.crop_nms_thresh),
165
+ )
166
+
167
+ # Encode masks
168
+ if self.output_mode == "coco_rle":
169
+ mask_data["segmentations"] = [coco_encode_rle(rle) for rle in mask_data["rles"]]
170
+ elif self.output_mode == "binary_mask":
171
+ mask_data["segmentations"] = [rle_to_mask(rle) for rle in mask_data["rles"]]
172
+ else:
173
+ mask_data["segmentations"] = mask_data["rles"]
174
+
175
+ # Write mask records
176
+ curr_anns = []
177
+ for idx in range(len(mask_data["segmentations"])):
178
+ ann = {
179
+ "segmentation": mask_data["segmentations"][idx],
180
+ "area": area_from_rle(mask_data["rles"][idx]),
181
+ "bbox": box_xyxy_to_xywh(mask_data["boxes"][idx]).tolist(),
182
+ "predicted_iou": mask_data["iou_preds"][idx].item(),
183
+ "point_coords": [mask_data["points"][idx].tolist()],
184
+ "stability_score": mask_data["stability_score"][idx].item(),
185
+ "crop_box": box_xyxy_to_xywh(mask_data["crop_boxes"][idx]).tolist(),
186
+ }
187
+ curr_anns.append(ann)
188
+
189
+ return curr_anns
190
+
191
+ def anns2mask(self, anns):
192
+ if len(anns) == 0:
193
+ print("len=0")
194
+ return
195
+ sorted_anns = sorted(anns, key=(lambda x: x['area']), reverse=True)
196
+ res = np.zeros((1, anns[0]['segmentation'].shape[0], anns[0]['segmentation'].shape[1]))
197
+
198
+ for ann in sorted_anns:
199
+ m = ann['segmentation']
200
+ area_ratio = (ann['area']) / (anns[0]['segmentation'].shape[0] * anns[0]['segmentation'].shape[1])
201
+ if area_ratio > 0.9:
202
+ continue
203
+ locs = np.where(m == True)
204
+ res_t = np.zeros((1, anns[0]['segmentation'].shape[0], anns[0]['segmentation'].shape[1]))
205
+ res_t[0, locs[0], locs[1]] = 1
206
+ res = np.concatenate([res_t, res], axis=0)
207
+ return res
208
+
209
+ def cosine_similarity(self, vector1, vector2):
210
+
211
+ dot_product = np.dot(vector1, vector2)
212
+
213
+ norm_v1 = np.linalg.norm(vector1)
214
+ norm_v2 = np.linalg.norm(vector2)
215
+ # 计算余弦相似度
216
+ return dot_product / (norm_v1 * norm_v2)
217
+
218
+ def _generate_masks(self, image: np.ndarray, spectral_lengths=None, GSD=None) -> MaskData:
219
+ orig_size = image.shape[:2]
220
+ crop_boxes, layer_idxs = generate_crop_boxes(
221
+ orig_size, self.crop_n_layers, self.crop_overlap_ratio
222
+ )
223
+
224
+ # Iterate over image crops
225
+ data = MaskData()
226
+ for crop_box, layer_idx in zip(crop_boxes, layer_idxs):
227
+ crop_data = self._process_crop(image, crop_box, layer_idx, orig_size, spectral_lengths, GSD)
228
+ data.cat(crop_data)
229
+
230
+ # Remove duplicate masks between crops
231
+ if len(crop_boxes) > 1:
232
+ # Prefer masks from smaller crops
233
+ scores = 1 / box_area(data["crop_boxes"])
234
+ scores = scores.to(data["boxes"].device)
235
+ keep_by_nms = batched_nms(
236
+ data["boxes"].float(),
237
+ scores,
238
+ torch.zeros_like(data["boxes"][:, 0]), # categories
239
+ iou_threshold=self.crop_nms_thresh,
240
+ )
241
+ data.filter(keep_by_nms)
242
+
243
+ data.to_numpy()
244
+ return data
245
+
246
+ def _process_crop(
247
+ self,
248
+ image: np.ndarray,
249
+ crop_box: List[int],
250
+ crop_layer_idx: int,
251
+ orig_size: Tuple[int, ...],
252
+ spectral_lengths = None,
253
+ GSD=None,
254
+ ) -> MaskData:
255
+ # Crop the image and calculate embeddings
256
+ x0, y0, x1, y1 = crop_box
257
+ cropped_im = image[y0:y1, x0:x1, :]
258
+ cropped_im_size = cropped_im.shape[:2]
259
+ self.predictor.set_image(cropped_im, True, spectral_lengths, GSD)
260
+
261
+ # Get points for this crop
262
+ points_scale = np.array(cropped_im_size)[None, ::-1]
263
+ points_for_image = self.point_grids[crop_layer_idx] * points_scale
264
+
265
+ # Generate masks for this crop in batches
266
+ data = MaskData()
267
+ for (points,) in batch_iterator(self.points_per_batch, points_for_image):
268
+ batch_data = self._process_batch(points, cropped_im_size, crop_box, orig_size)
269
+ data.cat(batch_data)
270
+ del batch_data
271
+ self.predictor.reset_image()
272
+
273
+ # Remove duplicates within this crop.
274
+ keep_by_nms = batched_nms(
275
+ data["boxes"].float(),
276
+ data["iou_preds"],
277
+ torch.zeros_like(data["boxes"][:, 0]), # categories
278
+ iou_threshold=self.box_nms_thresh,
279
+ )
280
+ data.filter(keep_by_nms)
281
+
282
+ # Return to the original image frame
283
+ data["boxes"] = uncrop_boxes_xyxy(data["boxes"], crop_box)
284
+ data["points"] = uncrop_points(data["points"], crop_box)
285
+ data["crop_boxes"] = torch.tensor([crop_box for _ in range(len(data["rles"]))])
286
+
287
+ return data
288
+
289
+ def _process_batch(
290
+ self,
291
+ points: np.ndarray,
292
+ im_size: Tuple[int, ...],
293
+ crop_box: List[int],
294
+ orig_size: Tuple[int, ...],
295
+ ) -> MaskData:
296
+ orig_h, orig_w = orig_size
297
+
298
+ # Run model on this batch
299
+ transformed_points = self.predictor.transform.apply_coords(points, im_size)
300
+ in_points = torch.as_tensor(transformed_points, device=self.predictor.device)
301
+ in_labels = torch.ones(in_points.shape[0], dtype=torch.int, device=in_points.device)
302
+ masks, iou_preds, _ = self.predictor.predict_torch(
303
+ in_points[:, None, :],
304
+ in_labels[:, None],
305
+ multimask_output=True,
306
+ return_logits=True,
307
+ )
308
+
309
+ # Serialize predictions and store in MaskData
310
+ data = MaskData(
311
+ masks=masks.flatten(0, 1),
312
+ iou_preds=iou_preds.flatten(0, 1),
313
+ points=torch.as_tensor(points.repeat(masks.shape[1], axis=0)),
314
+ )
315
+ del masks
316
+
317
+ # Filter by predicted IoU
318
+ if self.pred_iou_thresh > 0.0:
319
+ keep_mask = data["iou_preds"] > self.pred_iou_thresh
320
+ data.filter(keep_mask)
321
+
322
+ # Calculate stability score
323
+ data["stability_score"] = calculate_stability_score(
324
+ data["masks"], self.predictor.model.mask_threshold, self.stability_score_offset
325
+ )
326
+ if self.stability_score_thresh > 0.0:
327
+ keep_mask = data["stability_score"] >= self.stability_score_thresh
328
+ data.filter(keep_mask)
329
+
330
+ # Threshold masks and calculate boxes
331
+ data["masks"] = data["masks"] > self.predictor.model.mask_threshold
332
+ data["boxes"] = batched_mask_to_box(data["masks"])
333
+
334
+ # Filter boxes that touch crop boundaries
335
+ keep_mask = ~is_box_near_crop_edge(data["boxes"], crop_box, [0, 0, orig_w, orig_h])
336
+ if not torch.all(keep_mask):
337
+ data.filter(keep_mask)
338
+
339
+ # Compress to RLE
340
+ data["masks"] = uncrop_masks(data["masks"], crop_box, orig_h, orig_w)
341
+ data["rles"] = mask_to_rle_pytorch(data["masks"])
342
+ del data["masks"]
343
+
344
+ return data
345
+
346
+ @staticmethod
347
+ def postprocess_small_regions(
348
+ mask_data: MaskData, min_area: int, nms_thresh: float
349
+ ) -> MaskData:
350
+ """
351
+ Removes small disconnected regions and holes in masks, then reruns
352
+ box NMS to remove any new duplicates.
353
+
354
+ Edits mask_data in place.
355
+
356
+ Requires open-cv as a dependency.
357
+ """
358
+ if len(mask_data["rles"]) == 0:
359
+ return mask_data
360
+
361
+ # Filter small disconnected regions and holes
362
+ new_masks = []
363
+ scores = []
364
+ for rle in mask_data["rles"]:
365
+ mask = rle_to_mask(rle)
366
+
367
+ mask, changed = remove_small_regions(mask, min_area, mode="holes")
368
+ unchanged = not changed
369
+ mask, changed = remove_small_regions(mask, min_area, mode="islands")
370
+ unchanged = unchanged and not changed
371
+
372
+ new_masks.append(torch.as_tensor(mask).unsqueeze(0))
373
+ # Give score=0 to changed masks and score=1 to unchanged masks
374
+ # so NMS will prefer ones that didn't need postprocessing
375
+ scores.append(float(unchanged))
376
+
377
+ # Recalculate boxes and remove any new duplicates
378
+ masks = torch.cat(new_masks, dim=0)
379
+ boxes = batched_mask_to_box(masks)
380
+ keep_by_nms = batched_nms(
381
+ boxes.float(),
382
+ torch.as_tensor(scores),
383
+ torch.zeros_like(boxes[:, 0]), # categories
384
+ iou_threshold=nms_thresh,
385
+ )
386
+
387
+ # Only recalculate RLEs for masks that have changed
388
+ for i_mask in keep_by_nms:
389
+ if scores[i_mask] == 0.0:
390
+ mask_torch = masks[i_mask].unsqueeze(0)
391
+ mask_data["rles"][i_mask] = mask_to_rle_pytorch(mask_torch)[0]
392
+ mask_data["boxes"][i_mask] = boxes[i_mask] # update res directly
393
+ mask_data.filter(keep_by_nms)
394
+
395
+ return mask_data
HyperVision/build_HyperVision.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ from functools import partial
4
+ from HyperVision.modeling import ImageEncoderViT, MaskDecoder, PromptEncoder, Sam, TwoWayTransformer
5
+
6
+
7
+ def build_HyperVision_h(checkpoint=None, image_size=1024, vit_patch_size = 16,
8
+ encoder_global_attn_indexes=[15, 23, 31], merge_indexs=[8, 32], class_number = -1):
9
+ return _build_HyperVision(
10
+ encoder_embed_dim=1280,
11
+ encoder_depth=32,
12
+ encoder_num_heads=16,
13
+ encoder_global_attn_indexes=[7, 15, 23, 31] if encoder_global_attn_indexes == -1 else encoder_global_attn_indexes,
14
+ merge_indexs=merge_indexs,
15
+ vit_patch_size=vit_patch_size,
16
+ image_size=image_size,
17
+ checkpoint=checkpoint,
18
+ class_number = class_number,
19
+ )
20
+
21
+
22
+ build_HyperVision = build_HyperVision_h
23
+
24
+
25
+ def build_HyperVision_l(checkpoint=None, image_size=1024, vit_patch_size = 16,
26
+ encoder_global_attn_indexes=[11, 17, 23], merge_indexs=[6, 24], class_number = -1):
27
+ return _build_HyperVision(
28
+ encoder_embed_dim=1024,
29
+ encoder_depth=24,
30
+ encoder_num_heads=16,
31
+ encoder_global_attn_indexes=[5, 11, 17, 23] if encoder_global_attn_indexes == -1 else encoder_global_attn_indexes,
32
+ merge_indexs=merge_indexs,
33
+ vit_patch_size=vit_patch_size,
34
+ image_size=image_size,
35
+ checkpoint=checkpoint,
36
+ class_number = class_number,
37
+ )
38
+
39
+
40
+ def build_HyperVision_b(checkpoint=None, image_size=1024, vit_patch_size = 16,
41
+ encoder_global_attn_indexes=[5, 8, 11], merge_indexs=[3, 12], class_number = -1):
42
+ return _build_HyperVision(
43
+ encoder_embed_dim=768,
44
+ encoder_depth=12,
45
+ encoder_num_heads=12,
46
+ encoder_global_attn_indexes=[2, 5, 8, 11] if encoder_global_attn_indexes == -1 else encoder_global_attn_indexes,
47
+ merge_indexs=merge_indexs,
48
+ vit_patch_size=vit_patch_size,
49
+ image_size=image_size,
50
+ checkpoint=checkpoint,
51
+ class_number = class_number,
52
+ )
53
+
54
+
55
+ HyperVision_model_registry = {
56
+ "default": build_HyperVision_h,
57
+ "vit_h": build_HyperVision_h,
58
+ "vit_l": build_HyperVision_l,
59
+ "vit_b": build_HyperVision_b,
60
+ }
61
+
62
+
63
+ def load_and_resize_params(model, checkpoint_path):
64
+ checkpoint = torch.load(checkpoint_path, map_location='cpu')
65
+ model_dict = model.state_dict()
66
+
67
+ for k, v in checkpoint.items():
68
+ if k in model_dict:
69
+ if v.shape != model_dict[k].shape:
70
+ if 'pos_embed' in k:
71
+ 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))
72
+ elif 'rel_pos' in k:
73
+ v = F.interpolate(v.unsqueeze(0).unsqueeze(0), size=(model_dict[k].shape[0], model_dict[k].shape[1]),).squeeze(0).squeeze(0)
74
+ elif 'weight_bank' in k:
75
+ v = F.interpolate(v, size=(model_dict[k].shape[2], model_dict[k].shape[3]), mode='nearest')
76
+
77
+ model_dict[k] = v
78
+
79
+ model.load_state_dict(model_dict, strict=False)
80
+ return model
81
+
82
+
83
+ def _build_HyperVision(
84
+ encoder_embed_dim,
85
+ encoder_depth,
86
+ encoder_num_heads,
87
+ encoder_global_attn_indexes,
88
+ merge_indexs,
89
+ vit_patch_size,
90
+ checkpoint=None,
91
+ image_size=1024,
92
+ class_number = -1,
93
+ ):
94
+ prompt_embed_dim = 256
95
+ image_embedding_size = image_size // vit_patch_size
96
+ hypervision = Sam(
97
+ image_encoder=ImageEncoderViT(
98
+ depth=encoder_depth,
99
+ embed_dim=encoder_embed_dim,
100
+ img_size=image_size,
101
+ mlp_ratio=4,
102
+ norm_layer=partial(torch.nn.LayerNorm, eps=1e-6),
103
+ num_heads=encoder_num_heads,
104
+ patch_size=vit_patch_size,
105
+ qkv_bias=True,
106
+ use_rel_pos=True,
107
+ global_attn_indexes=encoder_global_attn_indexes,
108
+ merge_indexs = merge_indexs,
109
+ window_size=14,
110
+ out_chans=prompt_embed_dim,
111
+ ),
112
+ prompt_encoder=PromptEncoder(
113
+ embed_dim=prompt_embed_dim,
114
+ image_embedding_size=(image_embedding_size, image_embedding_size),
115
+ input_image_size=(image_size, image_size),
116
+ mask_in_chans=16,
117
+ ),
118
+ mask_decoder=MaskDecoder(
119
+ num_multimask_outputs=3,
120
+ transformer=TwoWayTransformer(
121
+ depth=2,
122
+ embedding_dim=prompt_embed_dim,
123
+ mlp_dim=2048,
124
+ num_heads=8,
125
+ ),
126
+ transformer_dim=prompt_embed_dim,
127
+ iou_head_depth=3,
128
+ iou_head_hidden_dim=256,
129
+ class_number = class_number
130
+ ),
131
+ )
132
+
133
+ hypervision.eval()
134
+ if checkpoint is not None:
135
+ load_and_resize_params(hypervision, checkpoint)
136
+ return hypervision
HyperVision/modeling/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from .sam import Sam
8
+ from .image_encoder import ImageEncoderViT
9
+ from .mask_decoder import MaskDecoder
10
+ from .prompt_encoder import PromptEncoder
11
+ from .transformer import TwoWayTransformer
HyperVision/modeling/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (389 Bytes). View file
 
HyperVision/modeling/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (504 Bytes). View file
 
HyperVision/modeling/__pycache__/common.cpython-310.pyc ADDED
Binary file (1.74 kB). View file
 
HyperVision/modeling/__pycache__/common.cpython-311.pyc ADDED
Binary file (3.23 kB). View file
 
HyperVision/modeling/__pycache__/image_encoder.cpython-310.pyc ADDED
Binary file (21.4 kB). View file
 
HyperVision/modeling/__pycache__/image_encoder.cpython-311.pyc ADDED
Binary file (37.1 kB). View file
 
HyperVision/modeling/__pycache__/mask_decoder.cpython-310.pyc ADDED
Binary file (5.73 kB). View file
 
HyperVision/modeling/__pycache__/mask_decoder.cpython-311.pyc ADDED
Binary file (9.71 kB). View file
 
HyperVision/modeling/__pycache__/prompt_encoder.cpython-310.pyc ADDED
Binary file (7.71 kB). View file
 
HyperVision/modeling/__pycache__/prompt_encoder.cpython-311.pyc ADDED
Binary file (12.9 kB). View file
 
HyperVision/modeling/__pycache__/sam.cpython-310.pyc ADDED
Binary file (6.21 kB). View file
 
HyperVision/modeling/__pycache__/sam.cpython-311.pyc ADDED
Binary file (8.39 kB). View file
 
HyperVision/modeling/__pycache__/scale_aware_PE.cpython-310.pyc ADDED
Binary file (1.82 kB). View file
 
HyperVision/modeling/__pycache__/scale_aware_PE.cpython-311.pyc ADDED
Binary file (2.97 kB). View file
 
HyperVision/modeling/__pycache__/transformer.cpython-310.pyc ADDED
Binary file (6.6 kB). View file
 
HyperVision/modeling/__pycache__/transformer.cpython-311.pyc ADDED
Binary file (10.9 kB). View file
 
HyperVision/modeling/common.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ from typing import Type
5
+
6
+
7
+ class MLPBlock(nn.Module):
8
+ def __init__(
9
+ self,
10
+ embedding_dim: int,
11
+ mlp_dim: int,
12
+ act: Type[nn.Module] = nn.GELU,
13
+ ) -> None:
14
+ super().__init__()
15
+ self.lin1 = nn.Linear(embedding_dim, mlp_dim)
16
+ self.lin2 = nn.Linear(mlp_dim, embedding_dim)
17
+ self.act = act()
18
+
19
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
20
+ return self.lin2(self.act(self.lin1(x)))
21
+
22
+
23
+ # From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa
24
+ # Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa
25
+ class LayerNorm2d(nn.Module):
26
+ def __init__(self, num_channels: int, eps: float = 1e-6) -> None:
27
+ super().__init__()
28
+ self.weight = nn.Parameter(torch.ones(num_channels))
29
+ self.bias = nn.Parameter(torch.zeros(num_channels))
30
+ self.eps = eps
31
+
32
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
33
+ u = x.mean(1, keepdim=True)
34
+ s = (x - u).pow(2).mean(1, keepdim=True)
35
+ x = (x - u) / torch.sqrt(s + self.eps)
36
+ x = self.weight[:, None, None] * x + self.bias[:, None, None]
37
+ return x
HyperVision/modeling/image_encoder.py ADDED
@@ -0,0 +1,672 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+ from typing import Optional, Tuple, Type
6
+ from .common import LayerNorm2d, MLPBlock
7
+ import math
8
+ import warnings
9
+ import numpy as np
10
+ import random
11
+ from itertools import repeat
12
+ TORCH_MAJOR = int(torch.__version__.split('.')[0])
13
+ TORCH_MINOR = int(torch.__version__.split('.')[1])
14
+ if TORCH_MAJOR == 1 and TORCH_MINOR < 8:
15
+ from torch._six import container_abcs
16
+ else:
17
+ import collections.abc as container_abcs
18
+ from ..utils.spectral_process_utils import *
19
+ from .scale_aware_PE import get_2d_sincos_pos_embed_with_resolution
20
+
21
+
22
+ class MLP(nn.Module):
23
+ def __init__(
24
+ self,
25
+ input_dim: int,
26
+ hidden_dim: int,
27
+ output_dim: int,
28
+ num_layers: int,
29
+ sigmoid_output: bool = False,
30
+ ) -> None:
31
+ super().__init__()
32
+ self.num_layers = num_layers
33
+ h = [hidden_dim] * (num_layers - 1)
34
+ self.layers = nn.ModuleList(
35
+ nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim])
36
+ )
37
+ self.sigmoid_output = sigmoid_output
38
+
39
+ def forward(self, x):
40
+ for i, layer in enumerate(self.layers):
41
+ x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
42
+ if self.sigmoid_output:
43
+ x = F.sigmoid(x)
44
+ return x
45
+
46
+
47
+ class ImageEncoderViT(nn.Module):
48
+ def __init__(
49
+ self,
50
+ img_size: int = 1024,
51
+ patch_size: int = 16,
52
+ in_chans: int = 3,
53
+ embed_dim: int = 768,
54
+ depth: int = 12,
55
+ num_heads: int = 12,
56
+ mlp_ratio: float = 4.0,
57
+ out_chans: int = 256,
58
+ qkv_bias: bool = True,
59
+ norm_layer: Type[nn.Module] = nn.LayerNorm,
60
+ act_layer: Type[nn.Module] = nn.GELU,
61
+ use_abs_pos: bool = False,
62
+ use_rel_pos: bool = False,
63
+ rel_pos_zero_init: bool = True,
64
+ window_size: int = 0,
65
+ global_attn_indexes: Tuple[int, ...] = (),
66
+ in_chans_spectral = 85,
67
+ merge_indexs = [3, 6, 8, 11], # for Vit-b version
68
+ ) -> None:
69
+ """
70
+ Args:
71
+ img_size (int): Input image size.
72
+ patch_size (int): Patch size.
73
+ in_chans (int): Number of input image channels.
74
+ embed_dim (int): Patch embedding dimension.
75
+ depth (int): Depth of ViT.
76
+ num_heads (int): Number of attention heads in each ViT block.
77
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
78
+ qkv_bias (bool): If True, add a learnable bias to query, key, value.
79
+ norm_layer (nn.Module): Normalization layer.
80
+ act_layer (nn.Module): Activation layer.
81
+ use_abs_pos (bool): If True, use absolute positional embeddings.
82
+ use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
83
+ rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
84
+ window_size (int): Window size for window attention blocks.
85
+ global_attn_indexes (list): Indexes for blocks using global attention.
86
+ """
87
+ super().__init__()
88
+ self.in_chans = in_chans
89
+ self.img_size = img_size
90
+ self.embed_dim = embed_dim
91
+ self.depth = depth
92
+ self.patch_size = patch_size
93
+ self.out_chans = out_chans
94
+
95
+ self.pos_embed_mlp = MLP(self.embed_dim, self.embed_dim//2, self.embed_dim, 3, sigmoid_output=False)
96
+
97
+ self.blocks = nn.ModuleList()
98
+ for i in range(depth):
99
+ block = Block(
100
+ dim=embed_dim,
101
+ num_heads=num_heads,
102
+ mlp_ratio=mlp_ratio,
103
+ qkv_bias=qkv_bias,
104
+ norm_layer=norm_layer,
105
+ act_layer=act_layer,
106
+ use_rel_pos=use_rel_pos,
107
+ rel_pos_zero_init=rel_pos_zero_init,
108
+ window_size=window_size if i not in global_attn_indexes else 0,
109
+ input_size=(img_size // patch_size, img_size // patch_size),
110
+ )
111
+ self.blocks.append(block)
112
+
113
+ self.contras_modules = nn.ModuleList()
114
+ for i in range(2):
115
+ block = Block(
116
+ dim=256,
117
+ num_heads=8,
118
+ mlp_ratio=mlp_ratio,
119
+ qkv_bias=qkv_bias,
120
+ norm_layer=norm_layer,
121
+ act_layer=act_layer,
122
+ use_rel_pos=use_rel_pos,
123
+ rel_pos_zero_init=rel_pos_zero_init,
124
+ window_size=16,
125
+ input_size=(img_size // patch_size, img_size // patch_size),
126
+ )
127
+ self.contras_modules.append(block)
128
+
129
+ self.neck = nn.Sequential(
130
+ nn.Conv2d(
131
+ embed_dim,
132
+ out_chans,
133
+ kernel_size=1,
134
+ bias=False,
135
+ ),
136
+ LayerNorm2d(out_chans),
137
+ nn.Conv2d(
138
+ out_chans,
139
+ out_chans,
140
+ kernel_size=3,
141
+ padding=1,
142
+ bias=False,
143
+ ),
144
+ LayerNorm2d(out_chans),
145
+ )
146
+
147
+ self.nm_dis = 10
148
+ 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)
149
+ 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)
150
+ self.weight_bank_data_indices_hy, _, self.weight_bank_indices_hy = find_corresponding_indices(input_wavelengths_hy, weight_bank_wavelength,self.nm_dis)
151
+
152
+ self.point_spectral_weight_bank_w = nn.Parameter(torch.randn((self.embed_dim, len(spectral_wavelength), patch_size, patch_size)))
153
+ self.point_spectral_weight_bank_b = nn.Parameter(torch.randn(self.embed_dim))
154
+ self.block_spectral_weight_bank_w = nn.Parameter(torch.randn((self.embed_dim, len(weight_bank_wavelength), patch_size, patch_size)))
155
+ self.block_spectral_weight_bank_b = nn.Parameter(torch.randn(self.embed_dim))
156
+
157
+ self.merge_indexs = merge_indexs
158
+ self.global_attn_indexes = global_attn_indexes
159
+ # self.multi_scale_convs = nn.ModuleList([
160
+ # nn.Sequential(
161
+ # nn.Conv2d(embed_dim, embed_dim, kernel_size=3, stride=2, padding=1, bias=True), # 保持特征图尺寸‌:ml-citation{ref="6" data="citationList"}
162
+ # nn.GELU()
163
+ # )
164
+ # for _ in range(len(self.merge_indexs))]) if self.merge_indexs != None else None
165
+ self.multi_scale_convs = nn.ModuleList([
166
+ PatchMerging(dim=embed_dim)
167
+ for i in range(len(self.merge_indexs))]) if self.merge_indexs != None else None
168
+
169
+ def convert_semantic_feature(self, backbone_features):
170
+ backbone_features = backbone_features.permute((0,2,3,1))
171
+
172
+ for i, blk in enumerate(self.contras_modules):
173
+ backbone_features = blk(backbone_features)
174
+
175
+ contras_features = (backbone_features.permute(0, 3, 1, 2))
176
+ return contras_features
177
+
178
+
179
+ def find_indices_not_in_A(self, A, B):
180
+ set_A = set(A)
181
+ result_indices = []
182
+ for index, element in enumerate(B):
183
+ if element not in set_A:
184
+ result_indices.append(index)
185
+ return result_indices
186
+
187
+
188
+ def forward(self, x: torch.Tensor, test_mode=False, input_wavelength=None, GSD=None) -> torch.Tensor:
189
+
190
+ """
191
+ Args:
192
+ x (tensor): input image with [B, C, H, W].
193
+ test_mode (bool): If true, all the input channels would be used.
194
+ If false, we would randomly select 40 channels for each iteration
195
+ input_wavelength: list, storing wavelengths for each hyperspectral channel
196
+ GSD: ground sampling distance (m/pixel). list, such as [1.0] or tensor, such as torch.tensor([1.0])
197
+
198
+ Returns: multi-stage backbone features
199
+ """
200
+
201
+
202
+ is_hy = False
203
+ is_mu = False
204
+
205
+ if x.shape[1] < 20:
206
+ is_mu = True
207
+ else:
208
+ is_hy = True
209
+
210
+ if input_wavelength != None and is_hy:
211
+ input_wavelengths_hy = input_wavelength
212
+ 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)
213
+ self.weight_bank_data_indices_hy, _, self.weight_bank_indices_hy = find_corresponding_indices(input_wavelengths_hy, weight_bank_wavelength,self.nm_dis)
214
+ elif input_wavelength != None and is_mu:
215
+ input_wavelengths_mu = input_wavelength
216
+ 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)
217
+
218
+ if is_hy:
219
+ if not test_mode:
220
+ random_indices = generate_random_indices(len(self.weight_bank_data_indices_hy)-1, 40)
221
+ random_indices.sort()
222
+ 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()]
223
+ else:
224
+ indices = [self.Band_feature_indices_hy, self.point_bank_indices_hy, self.weight_bank_data_indices_hy, self.weight_bank_indices_hy]
225
+ block_indices = self.find_indices_not_in_A(indices[0], indices[2])
226
+ indices[2] = np.array(indices[2])[block_indices].tolist()
227
+ indices[3] = np.array(indices[3])[block_indices].tolist()
228
+ self.last_indices = indices
229
+ elif is_mu:
230
+ indices = [self.Band_feature_indices_mu, self.point_bank_indices_mu, [], []]
231
+ self.last_indices = indices
232
+
233
+ if GSD == None:
234
+ GSD = [1.0]
235
+ if not torch.is_tensor(GSD):
236
+ GSD = torch.tensor(GSD)
237
+
238
+ point_feature = F.conv2d(
239
+ x[:,indices[0],:,:],
240
+ weight=self.point_spectral_weight_bank_w[:,indices[1],:,:],
241
+ bias=self.point_spectral_weight_bank_b,
242
+ stride=(self.patch_size, self.patch_size),
243
+ padding=(0,0)
244
+ )
245
+
246
+ if len(indices[2]) > 0:
247
+ block_feature = F.conv2d(
248
+ x[:,indices[2],:,:],
249
+ weight=self.block_spectral_weight_bank_w[:,indices[3],:,:],
250
+ bias=self.block_spectral_weight_bank_b,
251
+ stride=(self.patch_size, self.patch_size),
252
+ )
253
+
254
+ if len(indices[2]) > 0:
255
+ x_feature = point_feature + block_feature
256
+ else:
257
+ x_feature = point_feature
258
+
259
+ 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)
260
+ scale_aware_pos_embed = self.pos_embed_mlp(scale_aware_pos_embed)
261
+ 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))
262
+
263
+ x_feature = x_feature.permute((0,2,3,1))
264
+ x_feature = x_feature + scale_aware_pos_embed
265
+
266
+ self.multi_stage_features = []
267
+
268
+ multi_scale_merge_index = 0
269
+ for i, blk in enumerate(self.blocks):
270
+ if self.patch_size <= 8:
271
+ x_feature = torch.utils.checkpoint.checkpoint(blk, x_feature, use_reentrant=True)
272
+ else:
273
+ x_feature = blk(x_feature)
274
+
275
+ if self.merge_indexs != None:
276
+ if i in [self.merge_indexs[0], self.global_attn_indexes[0], self.global_attn_indexes[2]]:
277
+ self.multi_stage_features.append(x_feature.permute(0, 3, 1, 2))
278
+
279
+ if i in self.merge_indexs:
280
+ x_feature = self.multi_scale_convs[multi_scale_merge_index](x_feature)
281
+ multi_scale_merge_index += 1
282
+ elif i in self.global_attn_indexes:
283
+ self.multi_stage_features.append(x_feature.permute(0, 3, 1, 2))
284
+
285
+ x_feature = self.neck(x_feature.permute(0, 3, 1, 2))
286
+ self.multi_stage_features.append(x_feature)
287
+
288
+ return self.multi_stage_features
289
+
290
+
291
+ def to_2tuple(x):
292
+ if isinstance(x, container_abcs.Iterable):
293
+ return x
294
+ return tuple(repeat(x, 2))
295
+
296
+
297
+ def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.):
298
+
299
+ """Fills the input Tensor with values drawn from a truncated
300
+ normal distribution. The values are effectively drawn from the
301
+ normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)`
302
+ with values outside :math:`[a, b]` redrawn until they are within
303
+ the bounds. The method used for generating the random values works
304
+ best when :math:`a \leq \text{mean} \leq b`.
305
+ Args:
306
+ tensor: an n-dimensional `torch.Tensor`
307
+ mean: the mean of the normal distribution
308
+ std: the standard deviation of the normal distribution
309
+ a: the minimum cutoff value
310
+ b: the maximum cutoff value
311
+ Examples:
312
+ >>> w = torch.empty(3, 5)
313
+ >>> nn.init.trunc_normal_(w)
314
+ """
315
+ return _no_grad_trunc_normal_(tensor, mean, std, a, b)
316
+
317
+
318
+ def _no_grad_trunc_normal_(tensor, mean, std, a, b):
319
+ # Cut & paste from PyTorch official master until it's in a few official releases - RW
320
+ # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
321
+ def norm_cdf(x):
322
+ # Computes standard normal cumulative distribution function
323
+ return (1. + math.erf(x / math.sqrt(2.))) / 2.
324
+
325
+ if (mean < a - 2 * std) or (mean > b + 2 * std):
326
+ warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
327
+ "The distribution of values may be incorrect.",
328
+ stacklevel=2)
329
+
330
+ with torch.no_grad():
331
+ # Values are generated by using a truncated uniform distribution and
332
+ # then using the inverse CDF for the normal distribution.
333
+ # Get upper and lower cdf values
334
+ l = norm_cdf((a - mean) / std)
335
+ u = norm_cdf((b - mean) / std)
336
+
337
+ # Uniformly fill tensor with values from [l, u], then translate to
338
+ # [2l-1, 2u-1].
339
+ tensor.uniform_(2 * l - 1, 2 * u - 1)
340
+
341
+ # Use inverse cdf transform for normal distribution to get truncated
342
+ # standard normal
343
+ tensor.erfinv_()
344
+
345
+ # Transform to proper mean, std
346
+ tensor.mul_(std * math.sqrt(2.))
347
+ tensor.add_(mean)
348
+
349
+
350
+ class Block(nn.Module):
351
+ """Transformer blocks with support of window attention and residual propagation blocks"""
352
+
353
+ def __init__(
354
+ self,
355
+ dim: int,
356
+ num_heads: int,
357
+ mlp_ratio: float = 4.0,
358
+ qkv_bias: bool = True,
359
+ norm_layer: Type[nn.Module] = nn.LayerNorm,
360
+ act_layer: Type[nn.Module] = nn.GELU,
361
+ use_rel_pos: bool = False,
362
+ rel_pos_zero_init: bool = True,
363
+ window_size: int = 0,
364
+ input_size: Optional[Tuple[int, int]] = None,
365
+ ) -> None:
366
+ """
367
+ Args:
368
+ dim (int): Number of input channels.
369
+ num_heads (int): Number of attention heads in each ViT block.
370
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
371
+ qkv_bias (bool): If True, add a learnable bias to query, key, value.
372
+ norm_layer (nn.Module): Normalization layer.
373
+ act_layer (nn.Module): Activation layer.
374
+ use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
375
+ rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
376
+ window_size (int): Window size for window attention blocks. If it equals 0, then
377
+ use global attention.
378
+ input_size (tuple(int, int) or None): Input resolution for calculating the relative
379
+ positional parameter size.
380
+ """
381
+ super().__init__()
382
+ self.norm1 = norm_layer(dim)
383
+ self.attn = Attention(
384
+ dim,
385
+ num_heads=num_heads,
386
+ qkv_bias=qkv_bias,
387
+ use_rel_pos=use_rel_pos,
388
+ rel_pos_zero_init=rel_pos_zero_init,
389
+ input_size=input_size if window_size == 0 else (window_size, window_size),
390
+ )
391
+
392
+ self.norm2 = norm_layer(dim)
393
+ self.mlp = MLPBlock(embedding_dim=dim, mlp_dim=int(dim * mlp_ratio), act=act_layer)
394
+
395
+ self.window_size = window_size
396
+
397
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
398
+ shortcut = x
399
+ x = self.norm1(x)
400
+ # Window partition
401
+ if self.window_size > 0:
402
+ H, W = x.shape[1], x.shape[2]
403
+ x, pad_hw = window_partition(x, self.window_size)
404
+
405
+ x = self.attn(x)
406
+ # Reverse window partition
407
+ if self.window_size > 0:
408
+ x = window_unpartition(x, self.window_size, pad_hw, (H, W))
409
+
410
+ x = shortcut + x
411
+ x = x + self.mlp(self.norm2(x))
412
+
413
+ return x
414
+
415
+
416
+ class Attention(nn.Module):
417
+ """Multi-head Attention block with relative position embeddings."""
418
+
419
+ def __init__(
420
+ self,
421
+ dim: int,
422
+ num_heads: int = 8,
423
+ qkv_bias: bool = True,
424
+ use_rel_pos: bool = False,
425
+ rel_pos_zero_init: bool = True,
426
+ input_size: Optional[Tuple[int, int]] = None,
427
+ ) -> None:
428
+ """
429
+ Args:
430
+ dim (int): Number of input channels.
431
+ num_heads (int): Number of attention heads.
432
+ qkv_bias (bool): If True, add a learnable bias to query, key, value.
433
+ rel_pos (bool): If True, add relative positional embeddings to the attention map.
434
+ rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
435
+ input_size (tuple(int, int) or None): Input resolution for calculating the relative
436
+ positional parameter size.
437
+ """
438
+ super().__init__()
439
+ self.num_heads = num_heads
440
+ head_dim = dim // num_heads
441
+ self.scale = head_dim**-0.5
442
+
443
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
444
+ self.proj = nn.Linear(dim, dim)
445
+
446
+ self.use_rel_pos = use_rel_pos
447
+ if self.use_rel_pos:
448
+ assert (
449
+ input_size is not None
450
+ ), "Input size must be provided if using relative positional encoding."
451
+ # initialize relative positional embeddings
452
+ self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim))
453
+ self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim))
454
+
455
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
456
+ B, H, W, _ = x.shape
457
+ # qkv with shape (3, B, nHead, H * W, C)
458
+ qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
459
+ # q, k, v with shape (B * nHead, H * W, C)
460
+ q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0)
461
+
462
+ attn = (q * self.scale) @ k.transpose(-2, -1)
463
+
464
+ if self.use_rel_pos:
465
+ attn = add_decomposed_rel_pos(attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W))
466
+
467
+ attn = attn.softmax(dim=-1)
468
+ x = (attn @ v).view(B, self.num_heads, H, W, -1).permute(0, 2, 3, 1, 4).reshape(B, H, W, -1)
469
+ x = self.proj(x)
470
+
471
+ return x
472
+
473
+
474
+ def window_partition(x: torch.Tensor, window_size: int) -> Tuple[torch.Tensor, Tuple[int, int]]:
475
+ """
476
+ Partition into non-overlapping windows with padding if needed.
477
+ Args:
478
+ x (tensor): input tokens with [B, H, W, C].
479
+ window_size (int): window size.
480
+
481
+ Returns:
482
+ windows: windows after partition with [B * num_windows, window_size, window_size, C].
483
+ (Hp, Wp): padded height and width before partition
484
+ """
485
+ B, H, W, C = x.shape
486
+
487
+ pad_h = (window_size - H % window_size) % window_size
488
+ pad_w = (window_size - W % window_size) % window_size
489
+ if pad_h > 0 or pad_w > 0:
490
+ x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h))
491
+ Hp, Wp = H + pad_h, W + pad_w
492
+
493
+ x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C)
494
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
495
+ return windows, (Hp, Wp)
496
+
497
+
498
+ def window_unpartition(
499
+ windows: torch.Tensor, window_size: int, pad_hw: Tuple[int, int], hw: Tuple[int, int]
500
+ ) -> torch.Tensor:
501
+ """
502
+ Window unpartition into original sequences and removing padding.
503
+ Args:
504
+ windows (tensor): input tokens with [B * num_windows, window_size, window_size, C].
505
+ window_size (int): window size.
506
+ pad_hw (Tuple): padded height and width (Hp, Wp).
507
+ hw (Tuple): original height and width (H, W) before padding.
508
+
509
+ Returns:
510
+ x: unpartitioned sequences with [B, H, W, C].
511
+ """
512
+ Hp, Wp = pad_hw
513
+ H, W = hw
514
+ B = windows.shape[0] // (Hp * Wp // window_size // window_size)
515
+ x = windows.view(B, Hp // window_size, Wp // window_size, window_size, window_size, -1)
516
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1)
517
+
518
+ if Hp > H or Wp > W:
519
+ x = x[:, :H, :W, :].contiguous()
520
+ return x
521
+
522
+
523
+ def get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor:
524
+ """
525
+ Get relative positional embeddings according to the relative positions of
526
+ query and key sizes.
527
+ Args:
528
+ q_size (int): size of query q.
529
+ k_size (int): size of key k.
530
+ rel_pos (Tensor): relative position embeddings (L, C).
531
+
532
+ Returns:
533
+ Extracted positional embeddings according to relative positions.
534
+ """
535
+ max_rel_dist = int(2 * max(q_size, k_size) - 1)
536
+ # Interpolate rel pos if needed.
537
+ if rel_pos.shape[0] != max_rel_dist:
538
+ # Interpolate rel pos.
539
+ rel_pos_resized = F.interpolate(
540
+ rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1),
541
+ size=max_rel_dist,
542
+ mode="linear",
543
+ )
544
+ rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0)
545
+ else:
546
+ rel_pos_resized = rel_pos
547
+
548
+ # Scale the coords with short length if shapes for q and k are different.
549
+ q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0)
550
+ k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0)
551
+ relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0)
552
+
553
+ return rel_pos_resized[relative_coords.long()]
554
+
555
+
556
+ def add_decomposed_rel_pos(
557
+ attn: torch.Tensor,
558
+ q: torch.Tensor,
559
+ rel_pos_h: torch.Tensor,
560
+ rel_pos_w: torch.Tensor,
561
+ q_size: Tuple[int, int],
562
+ k_size: Tuple[int, int],
563
+ ) -> torch.Tensor:
564
+ """
565
+ Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`.
566
+ https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py # noqa B950
567
+ Args:
568
+ attn (Tensor): attention map.
569
+ q (Tensor): query q in the attention layer with shape (B, q_h * q_w, C).
570
+ rel_pos_h (Tensor): relative position embeddings (Lh, C) for height axis.
571
+ rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis.
572
+ q_size (Tuple): spatial sequence size of query q with (q_h, q_w).
573
+ k_size (Tuple): spatial sequence size of key k with (k_h, k_w).
574
+
575
+ Returns:
576
+ attn (Tensor): attention map with added relative positional embeddings.
577
+ """
578
+ q_h, q_w = q_size
579
+ k_h, k_w = k_size
580
+ Rh = get_rel_pos(q_h, k_h, rel_pos_h)
581
+ Rw = get_rel_pos(q_w, k_w, rel_pos_w)
582
+
583
+ B, _, dim = q.shape
584
+ r_q = q.reshape(B, q_h, q_w, dim)
585
+ rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh)
586
+ rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw)
587
+
588
+ attn = (
589
+ attn.view(B, q_h, q_w, k_h, k_w) + rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :]
590
+ ).view(B, q_h * q_w, k_h * k_w)
591
+
592
+ return attn
593
+
594
+
595
+ class PatchMerging(nn.Module):
596
+ r""" Patch Merging Layer.
597
+
598
+ Args:
599
+ input_resolution (tuple[int]): Resolution of input feature.
600
+ dim (int): Number of input channels.
601
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
602
+ """
603
+
604
+ def __init__(self, dim, norm_layer=nn.LayerNorm):
605
+ super().__init__()
606
+ self.dim = dim
607
+ self.reduction = nn.Linear(4 * dim, dim, bias=False)
608
+ self.norm = norm_layer(4 * dim)
609
+
610
+ def forward(self, x):
611
+ """
612
+ x: B, H*W, C
613
+ """
614
+ B, H, W, C = x.shape
615
+ assert H % 2 == 0 and W % 2 == 0, f"x size ({H}*{W}) are not even."
616
+
617
+ x = x.view(B, H, W, C)
618
+
619
+ x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
620
+ x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
621
+ x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
622
+ x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
623
+ x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
624
+ x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
625
+
626
+ x = self.norm(x)
627
+ x = self.reduction(x)
628
+ x = x.view(B, H // 2, W // 2, C)
629
+
630
+ return x
631
+
632
+ def extra_repr(self) -> str:
633
+ return f"input_resolution={self.input_resolution}, dim={self.dim}"
634
+
635
+ def flops(self):
636
+ H, W = self.input_resolution
637
+ flops = H * W * self.dim
638
+ flops += (H // 2) * (W // 2) * 4 * self.dim * 2 * self.dim
639
+ return flops
640
+
641
+ class PatchEmbed(nn.Module):
642
+ """
643
+ Image to Patch Embedding.
644
+ """
645
+
646
+ def __init__(
647
+ self,
648
+ kernel_size: Tuple[int, int] = (16, 16),
649
+ stride: Tuple[int, int] = (16, 16),
650
+ padding: Tuple[int, int] = (0, 0),
651
+ in_chans: int = 3,
652
+ embed_dim: int = 768,
653
+ ) -> None:
654
+ """
655
+ Args:
656
+ kernel_size (Tuple): kernel size of the projection layer.
657
+ stride (Tuple): stride of the projection layer.
658
+ padding (Tuple): padding size of the projection layer.
659
+ in_chans (int): Number of input image channels.
660
+ embed_dim (int): Patch embedding dimension.
661
+ """
662
+ super().__init__()
663
+
664
+ self.proj = nn.Conv2d(
665
+ in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding
666
+ )
667
+
668
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
669
+ x = self.proj(x)
670
+ # B C H W -> B H W C
671
+ x = x.permute(0, 2, 3, 1)
672
+ return x
HyperVision/modeling/mask_decoder.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ from torch.nn import functional as F
4
+ from typing import List, Tuple, Type
5
+ from .common import LayerNorm2d
6
+
7
+
8
+ class MaskDecoder(nn.Module):
9
+ def __init__(
10
+ self,
11
+ *,
12
+ transformer_dim: int,
13
+ transformer: nn.Module,
14
+ num_multimask_outputs: int = 3,
15
+ activation: Type[nn.Module] = nn.GELU,
16
+ iou_head_depth: int = 3,
17
+ iou_head_hidden_dim: int = 256,
18
+ class_number = -1,
19
+ ) -> None:
20
+ """
21
+ Predicts masks given an image and prompt embeddings, using a
22
+ transformer architecture.
23
+
24
+ Arguments:
25
+ transformer_dim (int): the channel dimension of the transformer
26
+ transformer (nn.Module): the transformer used to predict masks
27
+ num_multimask_outputs (int): the number of masks to predict
28
+ when disambiguating masks
29
+ activation (nn.Module): the type of activation to use when
30
+ upscaling masks
31
+ iou_head_depth (int): the depth of the MLP used to predict
32
+ mask quality
33
+ iou_head_hidden_dim (int): the hidden dimension of the MLP
34
+ used to predict mask quality
35
+ class_number: the number of semantic classes for decoder-only tuning
36
+ """
37
+ super().__init__()
38
+ self.transformer_dim = transformer_dim
39
+ self.transformer = transformer
40
+
41
+ self.num_multimask_outputs = num_multimask_outputs
42
+
43
+ self.iou_token = nn.Embedding(1, transformer_dim)
44
+ self.num_mask_tokens = num_multimask_outputs + 1
45
+ self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim)
46
+ self.class_number = class_number
47
+
48
+ self.output_upscaling = nn.Sequential(
49
+ nn.ConvTranspose2d(transformer_dim, transformer_dim // 4, kernel_size=2, stride=2),
50
+ LayerNorm2d(transformer_dim // 4),
51
+ activation(),
52
+ nn.ConvTranspose2d(transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2),
53
+ activation(),
54
+ )
55
+ self.output_hypernetworks_mlps = nn.ModuleList(
56
+ [
57
+ MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3)
58
+ for i in range(self.num_mask_tokens)
59
+ ]
60
+ )
61
+
62
+ self.iou_prediction_head = MLP(
63
+ transformer_dim, iou_head_hidden_dim, self.num_mask_tokens, iou_head_depth
64
+ )
65
+
66
+ if self.class_number != -1:
67
+ self.class_seg_head = nn.Conv2d(transformer_dim // 8, self.class_number, 3, 1, 1)
68
+
69
+ def forward(
70
+ self,
71
+ image_embeddings: torch.Tensor,
72
+ image_pe: torch.Tensor,
73
+ sparse_prompt_embeddings: torch.Tensor,
74
+ dense_prompt_embeddings: torch.Tensor,
75
+ multimask_output: bool,
76
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
77
+ """
78
+ Predict masks given image and prompt embeddings.
79
+
80
+ Arguments:
81
+ image_embeddings (torch.Tensor): the embeddings from the image encoder
82
+ image_pe (torch.Tensor): positional encoding with the shape of image_embeddings
83
+ sparse_prompt_embeddings (torch.Tensor): the embeddings of the points and boxes
84
+ dense_prompt_embeddings (torch.Tensor): the embeddings of the mask inputs
85
+ multimask_output (bool): Whether to return multiple masks or a single
86
+ mask.
87
+
88
+ Returns:
89
+ torch.Tensor: batched predicted masks
90
+ torch.Tensor: batched predictions of mask quality
91
+ """
92
+ masks, iou_pred = self.predict_masks(
93
+ image_embeddings=image_embeddings,
94
+ image_pe=image_pe,
95
+ sparse_prompt_embeddings=sparse_prompt_embeddings,
96
+ dense_prompt_embeddings=dense_prompt_embeddings,
97
+ )
98
+
99
+ # Select the correct mask or masks for output
100
+
101
+ if self.class_number != -1:
102
+ return masks
103
+
104
+ if multimask_output:
105
+ mask_slice = slice(1, None)
106
+ else:
107
+ mask_slice = slice(0, 1)
108
+ masks = masks[:, mask_slice, :, :]
109
+ iou_pred = iou_pred[:, mask_slice]
110
+
111
+ # Prepare output
112
+ return masks, iou_pred
113
+
114
+ def predict_masks(
115
+ self,
116
+ image_embeddings: torch.Tensor,
117
+ image_pe: torch.Tensor,
118
+ sparse_prompt_embeddings: torch.Tensor,
119
+ dense_prompt_embeddings: torch.Tensor,
120
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
121
+ """Predicts masks. See 'forward' for more details."""
122
+ # Concatenate output tokens
123
+ output_tokens = torch.cat([self.iou_token.weight, self.mask_tokens.weight], dim=0)
124
+ output_tokens = output_tokens.unsqueeze(0).expand(sparse_prompt_embeddings.size(0), -1, -1)
125
+ tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1)
126
+
127
+ src = torch.repeat_interleave(image_embeddings, 1, dim=0)
128
+
129
+ src = src + dense_prompt_embeddings
130
+ pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0)
131
+ b, c, h, w = src.shape
132
+
133
+ # Run the transformer
134
+ hs, src = self.transformer(src, pos_src, tokens)
135
+ iou_token_out = hs[:, 0, :]
136
+ mask_tokens_out = hs[:, 1 : (1 + self.num_mask_tokens), :]
137
+
138
+ # Upscale mask embeddings and predict masks using the mask tokens
139
+ src = src.transpose(1, 2).view(b, c, h, w)
140
+ self.upscaled_embedding = self.output_upscaling(src)
141
+ b, c, h, w = self.upscaled_embedding.shape
142
+ if self.class_number == -1:
143
+ hyper_in_list: List[torch.Tensor] = []
144
+ for i in range(self.num_mask_tokens):
145
+ hyper_in_list.append(self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :]))
146
+ hyper_in = torch.stack(hyper_in_list, dim=1)
147
+ masks = (hyper_in @ self.upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w)
148
+ else:
149
+ masks = self.class_seg_head(self.upscaled_embedding)
150
+
151
+ # Generate mask quality predictions
152
+ iou_pred = self.iou_prediction_head(iou_token_out)
153
+ return masks, iou_pred
154
+
155
+
156
+ # Lightly adapted from
157
+ # https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py # noqa
158
+ class MLP(nn.Module):
159
+ def __init__(
160
+ self,
161
+ input_dim: int,
162
+ hidden_dim: int,
163
+ output_dim: int,
164
+ num_layers: int,
165
+ sigmoid_output: bool = False,
166
+ ) -> None:
167
+ super().__init__()
168
+ self.num_layers = num_layers
169
+ h = [hidden_dim] * (num_layers - 1)
170
+ self.layers = nn.ModuleList(
171
+ nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim])
172
+ )
173
+ self.sigmoid_output = sigmoid_output
174
+
175
+ def forward(self, x):
176
+ for i, layer in enumerate(self.layers):
177
+ x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
178
+ if self.sigmoid_output:
179
+ x = F.sigmoid(x)
180
+ return x
HyperVision/modeling/prompt_encoder.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import numpy as np
8
+ import torch
9
+ from torch import nn
10
+
11
+ from typing import Any, Optional, Tuple, Type
12
+ from .mask_decoder import MLP
13
+ from .common import LayerNorm2d
14
+
15
+
16
+ class PromptEncoder(nn.Module):
17
+ def __init__(
18
+ self,
19
+ embed_dim: int,
20
+ image_embedding_size: Tuple[int, int],
21
+ input_image_size: Tuple[int, int],
22
+ mask_in_chans: int,
23
+ activation: Type[nn.Module] = nn.GELU,
24
+ ) -> None:
25
+ """
26
+ Encodes prompts for input to SAM's mask decoder.
27
+
28
+ Arguments:
29
+ embed_dim (int): The prompts' embedding dimension
30
+ image_embedding_size (tuple(int, int)): The spatial size of the
31
+ image embedding, as (H, W).
32
+ input_image_size (int): The padded size of the image as input
33
+ to the image encoder, as (H, W).
34
+ mask_in_chans (int): The number of hidden channels used for
35
+ encoding input masks.
36
+ activation (nn.Module): The activation to use when encoding
37
+ input masks.
38
+ """
39
+ super().__init__()
40
+ self.embed_dim = embed_dim
41
+ self.input_image_size = input_image_size
42
+ self.image_embedding_size = image_embedding_size
43
+ self.pe_layer = PositionEmbeddingRandom(embed_dim // 2)
44
+
45
+ self.num_point_embeddings: int = 4 # pos/neg point + 2 box corners
46
+ point_embeddings = [nn.Embedding(1, embed_dim) for i in range(self.num_point_embeddings)]
47
+ self.point_embeddings = nn.ModuleList(point_embeddings)
48
+ self.not_a_point_embed = nn.Embedding(1, embed_dim)
49
+
50
+ self.mask_input_size = (4 * image_embedding_size[0], 4 * image_embedding_size[1])
51
+ self.mask_downscaling = nn.Sequential(
52
+ nn.Conv2d(1, mask_in_chans // 4, kernel_size=2, stride=2),
53
+ LayerNorm2d(mask_in_chans // 4),
54
+ activation(),
55
+ nn.Conv2d(mask_in_chans // 4, mask_in_chans, kernel_size=2, stride=2),
56
+ LayerNorm2d(mask_in_chans),
57
+ activation(),
58
+ nn.Conv2d(mask_in_chans, embed_dim, kernel_size=1),
59
+ )
60
+ self.no_mask_embed = nn.Embedding(1, embed_dim)
61
+
62
+ def get_dense_pe(self) -> torch.Tensor:
63
+ """
64
+ Returns the positional encoding used to encode point prompts,
65
+ applied to a dense set of points the shape of the image encoding.
66
+
67
+ Returns:
68
+ torch.Tensor: Positional encoding with shape
69
+ 1x(embed_dim)x(embedding_h)x(embedding_w)
70
+ """
71
+ return self.pe_layer(self.image_embedding_size).unsqueeze(0)
72
+
73
+ def _embed_points(
74
+ self,
75
+ points: torch.Tensor,
76
+ labels: torch.Tensor,
77
+ pad: bool,
78
+ ) -> torch.Tensor:
79
+ """Embeds point prompts."""
80
+ points = points + 0.5 # Shift to center of pixel
81
+ if pad:
82
+ padding_point = torch.zeros((points.shape[0], 1, 2), device=points.device)
83
+ padding_label = -torch.ones((labels.shape[0], 1), device=labels.device)
84
+ points = torch.cat([points, padding_point], dim=1)
85
+ labels = torch.cat([labels, padding_label], dim=1)
86
+ point_embedding = self.pe_layer.forward_with_coords(points, self.input_image_size)
87
+ point_embedding[labels == -1] = 0.0
88
+ point_embedding[labels == -1] += self.not_a_point_embed.weight
89
+ point_embedding[labels == 0] += self.point_embeddings[0].weight
90
+ point_embedding[labels == 1] += self.point_embeddings[1].weight
91
+ return point_embedding
92
+
93
+ def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor:
94
+ """Embeds box prompts."""
95
+ boxes = boxes + 0.5 # Shift to center of pixel
96
+ coords = boxes.reshape(-1, 2, 2)
97
+ corner_embedding = self.pe_layer.forward_with_coords(coords, self.input_image_size)
98
+ corner_embedding[:, 0, :] += self.point_embeddings[2].weight
99
+ corner_embedding[:, 1, :] += self.point_embeddings[3].weight
100
+ return corner_embedding
101
+
102
+ def _embed_masks(self, masks: torch.Tensor) -> torch.Tensor:
103
+ """Embeds mask inputs."""
104
+ mask_embedding = self.mask_downscaling(masks)
105
+ return mask_embedding
106
+
107
+ def _get_batch_size(
108
+ self,
109
+ points: Optional[Tuple[torch.Tensor, torch.Tensor]],
110
+ boxes: Optional[torch.Tensor],
111
+ masks: Optional[torch.Tensor],
112
+ ) -> int:
113
+ """
114
+ Gets the batch size of the output given the batch size of the input prompts.
115
+ """
116
+ if points is not None:
117
+ return points[0].shape[0]
118
+ elif boxes is not None:
119
+ return boxes.shape[0]
120
+ elif masks is not None:
121
+ return masks.shape[0]
122
+ else:
123
+ return 1
124
+
125
+ def _get_device(self) -> torch.device:
126
+ return self.point_embeddings[0].weight.device
127
+
128
+ def forward(
129
+ self,
130
+ points: Optional[Tuple[torch.Tensor, torch.Tensor]],
131
+ boxes: Optional[torch.Tensor],
132
+ masks: Optional[torch.Tensor],
133
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
134
+ """
135
+ Embeds different types of prompts, returning both sparse and dense
136
+ embeddings.
137
+
138
+ Arguments:
139
+ points (tuple(torch.Tensor, torch.Tensor) or none): point coordinates
140
+ and labels to embed.
141
+ boxes (torch.Tensor or none): boxes to embed
142
+ masks (torch.Tensor or none): masks to embed
143
+
144
+ Returns:
145
+ torch.Tensor: sparse embeddings for the points and boxes, with shape
146
+ BxNx(embed_dim), where N is determined by the number of input points
147
+ and boxes.
148
+ torch.Tensor: dense embeddings for the masks, in the shape
149
+ Bx(embed_dim)x(embed_H)x(embed_W)
150
+ """
151
+ bs = self._get_batch_size(points, boxes, masks)
152
+ sparse_embeddings = torch.empty((bs, 0, self.embed_dim), device=self._get_device())
153
+ if points is not None:
154
+ coords, labels = points
155
+ point_embeddings = self._embed_points(coords, labels, pad=(boxes is None))
156
+ sparse_embeddings = torch.cat([sparse_embeddings, point_embeddings], dim=1)
157
+ if boxes is not None:
158
+ box_embeddings = self._embed_boxes(boxes)
159
+ sparse_embeddings = torch.cat([sparse_embeddings, box_embeddings], dim=1)
160
+
161
+ if masks is not None:
162
+ dense_embeddings = self._embed_masks(masks)
163
+ else:
164
+ dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).expand(
165
+ bs, -1, self.image_embedding_size[0], self.image_embedding_size[1]
166
+ )
167
+
168
+ return sparse_embeddings, dense_embeddings
169
+
170
+
171
+ class PositionEmbeddingRandom(nn.Module):
172
+ """
173
+ Positional encoding using random spatial frequencies.
174
+ """
175
+
176
+ def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None:
177
+ super().__init__()
178
+ if scale is None or scale <= 0.0:
179
+ scale = 1.0
180
+ self.register_buffer(
181
+ "positional_encoding_gaussian_matrix",
182
+ scale * torch.randn((2, num_pos_feats)),
183
+ )
184
+
185
+ def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor:
186
+ """Positionally encode points that are normalized to [0,1]."""
187
+ # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape
188
+ coords = 2 * coords - 1
189
+ coords = coords @ self.positional_encoding_gaussian_matrix
190
+ coords = 2 * np.pi * coords
191
+ # outputs d_1 x ... x d_n x C shape
192
+ return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1)
193
+
194
+ def forward(self, size: Tuple[int, int]) -> torch.Tensor:
195
+ """Generate positional encoding for a grid of the specified size."""
196
+ h, w = size
197
+ device: Any = self.positional_encoding_gaussian_matrix.device
198
+ grid = torch.ones((h, w), device=device, dtype=torch.float32)
199
+ y_embed = grid.cumsum(dim=0) - 0.5
200
+ x_embed = grid.cumsum(dim=1) - 0.5
201
+ y_embed = y_embed / h
202
+ x_embed = x_embed / w
203
+
204
+ pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1))
205
+ return pe.permute(2, 0, 1) # C x H x W
206
+
207
+ def forward_with_coords(
208
+ self, coords_input: torch.Tensor, image_size: Tuple[int, int]
209
+ ) -> torch.Tensor:
210
+ """Positionally encode points that are not normalized to [0,1]."""
211
+ coords = coords_input.clone()
212
+ coords[:, :, 0] = coords[:, :, 0] / image_size[1]
213
+ coords[:, :, 1] = coords[:, :, 1] / image_size[0]
214
+ return self._pe_encoding(coords.to(torch.float)) # B x N x C
HyperVision/modeling/sam.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ from torch.nn import functional as F
4
+
5
+ from typing import Any, Dict, List, Tuple
6
+
7
+ from .image_encoder import ImageEncoderViT
8
+ from .mask_decoder import MaskDecoder
9
+ from .prompt_encoder import PromptEncoder
10
+
11
+ """
12
+ We use the meta-architecture of SAM.
13
+ """
14
+
15
+ class Sam(nn.Module):
16
+ mask_threshold: float = 0.0
17
+
18
+ def __init__(
19
+ self,
20
+ image_encoder: ImageEncoderViT,
21
+ prompt_encoder: PromptEncoder,
22
+ mask_decoder: MaskDecoder,
23
+ ) -> None:
24
+ """
25
+ SAM predicts object masks from an image and input prompts.
26
+
27
+ Arguments:
28
+ image_encoder (ImageEncoderViT): The backbone used to encode the
29
+ image into image embeddings that allow for efficient mask prediction.
30
+ prompt_encoder (PromptEncoder): Encodes various types of input prompts.
31
+ mask_decoder (MaskDecoder): Predicts masks from the image embeddings
32
+ and encoded prompts.
33
+
34
+ """
35
+ super().__init__()
36
+ self.image_encoder = image_encoder
37
+ self.prompt_encoder = prompt_encoder
38
+ self.mask_decoder = mask_decoder
39
+
40
+ @property
41
+ def device(self) -> Any:
42
+ return self.image_encoder.point_spectral_weight_bank_w.device
43
+
44
+ @torch.no_grad()
45
+ def forward(
46
+ self,
47
+ batched_input: List[Dict[str, Any]],
48
+ multimask_output: bool,
49
+ ) -> List[Dict[str, torch.Tensor]]:
50
+ """
51
+ Predicts masks end-to-end from provided images and prompts.
52
+ If prompts are not known in advance, using SamPredictor is
53
+ recommended over calling the model directly.
54
+
55
+ Arguments:
56
+ batched_input (list(dict)): A list over input images, each a
57
+ dictionary with the following keys. A prompt key can be
58
+ excluded if it is not present.
59
+ 'image': The image as a torch tensor in 3xHxW format,
60
+ already transformed for input to the model.
61
+ 'original_size': (tuple(int, int)) The original size of
62
+ the image before transformation, as (H, W).
63
+ 'point_coords': (torch.Tensor) Batched point prompts for
64
+ this image, with shape BxNx2. Already transformed to the
65
+ input frame of the model.
66
+ 'point_labels': (torch.Tensor) Batched labels for point prompts,
67
+ with shape BxN.
68
+ 'boxes': (torch.Tensor) Batched box inputs, with shape Bx4.
69
+ Already transformed to the input frame of the model.
70
+ 'mask_inputs': (torch.Tensor) Batched mask inputs to the model,
71
+ in the form Bx1xHxW.
72
+ multimask_output (bool): Whether the model should predict multiple
73
+ disambiguating masks, or return a single mask.
74
+
75
+ Returns:
76
+ (list(dict)): A list over input images, where each element is
77
+ as dictionary with the following keys.
78
+ 'masks': (torch.Tensor) Batched binary mask predictions,
79
+ with shape BxCxHxW, where B is the number of input prompts,
80
+ C is determined by multimask_output, and (H, W) is the
81
+ original size of the image.
82
+ 'iou_predictions': (torch.Tensor) The model's predictions
83
+ of mask quality, in shape BxC.
84
+ 'low_res_logits': (torch.Tensor) Low resolution logits with
85
+ shape BxCxHxW, where H=W=256. Can be passed as mask input
86
+ to subsequent iterations of prediction.
87
+ """
88
+ input_images = torch.stack([self.preprocess(x["image"]) for x in batched_input], dim=0)
89
+ image_embeddings = self.image_encoder(input_images)
90
+
91
+ outputs = []
92
+ for image_record, curr_embedding in zip(batched_input, image_embeddings):
93
+ if "point_coords" in image_record:
94
+ points = (image_record["point_coords"], image_record["point_labels"])
95
+ else:
96
+ points = None
97
+ sparse_embeddings, dense_embeddings = self.prompt_encoder(
98
+ points=points,
99
+ boxes=image_record.get("boxes", None),
100
+ masks=image_record.get("mask_inputs", None),
101
+ )
102
+ low_res_masks, iou_predictions = self.mask_decoder(
103
+ image_embeddings=curr_embedding.unsqueeze(0),
104
+ image_pe=self.prompt_encoder.get_dense_pe(),
105
+ sparse_prompt_embeddings=sparse_embeddings,
106
+ dense_prompt_embeddings=dense_embeddings,
107
+ multimask_output=multimask_output,
108
+ )
109
+ masks = self.postprocess_masks(
110
+ low_res_masks,
111
+ input_size=image_record["image"].shape[-2:],
112
+ original_size=image_record["original_size"],
113
+ )
114
+ masks = masks > self.mask_threshold
115
+ outputs.append(
116
+ {
117
+ "masks": masks,
118
+ "iou_predictions": iou_predictions,
119
+ "low_res_logits": low_res_masks,
120
+ }
121
+ )
122
+ return outputs
123
+
124
+ def postprocess_masks(
125
+ self,
126
+ masks: torch.Tensor,
127
+ input_size: Tuple[int, ...],
128
+ original_size: Tuple[int, ...],
129
+ ) -> torch.Tensor:
130
+ """
131
+ Remove padding and upscale masks to the original image size.
132
+
133
+ Arguments:
134
+ masks (torch.Tensor): Batched masks from the mask_decoder,
135
+ in BxCxHxW format.
136
+ input_size (tuple(int, int)): The size of the image input to the
137
+ model, in (H, W) format. Used to remove padding.
138
+ original_size (tuple(int, int)): The original size of the image
139
+ before resizing for input to the model, in (H, W) format.
140
+
141
+ Returns:
142
+ (torch.Tensor): Batched masks in BxCxHxW format, where (H, W)
143
+ is given by original_size.
144
+ """
145
+ masks = F.interpolate(
146
+ masks,
147
+ (self.image_encoder.img_size, self.image_encoder.img_size),
148
+ mode="bilinear",
149
+ align_corners=False,
150
+ )
151
+ masks = masks[..., : input_size[0], : input_size[1]]
152
+ masks = F.interpolate(masks, original_size, mode="bilinear", align_corners=False)
153
+ return masks
154
+
155
+ def preprocess(self, x: torch.Tensor) -> torch.Tensor:
156
+ """Normalize pixel values and pad to a square input."""
157
+
158
+ x = x/x.max()
159
+ h, w = x.shape[-2:]
160
+ padh = self.image_encoder.img_size - h
161
+ padw = self.image_encoder.img_size - w
162
+ x = F.pad(x, (0, padw, 0, padh))
163
+ return x
HyperVision/modeling/scale_aware_PE.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+
4
+
5
+ def get_1d_sincos_pos_embed_from_grid_torch(embed_dim, pos):
6
+ """
7
+ embed_dim: output dimension for each position
8
+ pos: a list of positions to be encoded: size (M,)
9
+ out: (M, D)
10
+ """
11
+ assert embed_dim % 2 == 0
12
+ old_shape = pos
13
+ omega = torch.arange(embed_dim // 2, dtype=torch.float32, device=pos.device)
14
+ omega /= embed_dim / 2.0
15
+ omega = 1.0 / 10000**omega # (D/2,)
16
+
17
+ pos = pos.reshape(-1) # (M,)
18
+ out = torch.einsum("m,d->md", pos, omega) # (M, D/2), outer product
19
+
20
+ emb_sin = torch.sin(out) # (M, D/2)
21
+ emb_cos = torch.cos(out) # (M, D/2)
22
+
23
+ emb = torch.cat([emb_sin, emb_cos], dim=1) # (M, D)
24
+ return emb
25
+
26
+ def get_2d_sincos_pos_embed_from_grid_torch(embed_dim, grid):
27
+ assert embed_dim % 2 == 0
28
+
29
+ # use half of dimensions to encode grid_h
30
+ emb_h = get_1d_sincos_pos_embed_from_grid_torch(
31
+ embed_dim // 2, grid[0]
32
+ ) # (H*W, D/2)
33
+ emb_w = get_1d_sincos_pos_embed_from_grid_torch(
34
+ embed_dim // 2, grid[1]
35
+ ) # (H*W, D/2)
36
+
37
+ emb = torch.cat([emb_h, emb_w], dim=1) # (H*W, D)
38
+ return emb
39
+
40
+ def get_2d_sincos_pos_embed_with_resolution(
41
+ embed_dim, grid_size, res, device="cpu"
42
+ ):
43
+ """
44
+ grid_size: int of the grid height and width
45
+ res: array of size n, representing the resolution of a pixel (say, in meters),
46
+ return:
47
+ pos_embed: [n,grid_size*grid_size, embed_dim] or [n,1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
48
+ """
49
+ # res = torch.FloatTensor(res).to(device)
50
+ res = res.to(device)
51
+ grid_h = torch.arange(grid_size, dtype=torch.float32, device=device)
52
+ grid_w = torch.arange(grid_size, dtype=torch.float32, device=device)
53
+ grid = torch.meshgrid(
54
+ grid_w, grid_h, indexing="xy"
55
+ ) # here h goes first,direction reversed for numpy
56
+ grid = torch.stack(grid, dim=0) # 2 x h x w
57
+
58
+ # grid = grid.reshape([2, 1, grid_size, grid_size])
59
+ grid = torch.einsum("chw,n->cnhw", grid, res) # 2 x n x h x w
60
+ _, n, h, w = grid.shape
61
+ pos_embed = get_2d_sincos_pos_embed_from_grid_torch(
62
+ embed_dim, grid
63
+ ) # # (nxH*W, D/2)
64
+ pos_embed = pos_embed.reshape(n, h*w, embed_dim)
65
+ return pos_embed
HyperVision/modeling/transformer.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import Tensor, nn
3
+
4
+ import math
5
+ from typing import Tuple, Type
6
+
7
+ from .common import MLPBlock
8
+
9
+
10
+ class TwoWayTransformer(nn.Module):
11
+ def __init__(
12
+ self,
13
+ depth: int,
14
+ embedding_dim: int,
15
+ num_heads: int,
16
+ mlp_dim: int,
17
+ activation: Type[nn.Module] = nn.ReLU,
18
+ attention_downsample_rate: int = 2,
19
+ ) -> None:
20
+ """
21
+ A transformer decoder that attends to an input image using
22
+ queries whose positional embedding is supplied.
23
+
24
+ Args:
25
+ depth (int): number of layers in the transformer
26
+ embedding_dim (int): the channel dimension for the input embeddings
27
+ num_heads (int): the number of heads for multihead attention. Must
28
+ divide embedding_dim
29
+ mlp_dim (int): the channel dimension internal to the MLP block
30
+ activation (nn.Module): the activation to use in the MLP block
31
+ """
32
+ super().__init__()
33
+ self.depth = depth
34
+ self.embedding_dim = embedding_dim
35
+ self.num_heads = num_heads
36
+ self.mlp_dim = mlp_dim
37
+ self.layers = nn.ModuleList()
38
+
39
+ for i in range(depth):
40
+ self.layers.append(
41
+ TwoWayAttentionBlock(
42
+ embedding_dim=embedding_dim,
43
+ num_heads=num_heads,
44
+ mlp_dim=mlp_dim,
45
+ activation=activation,
46
+ attention_downsample_rate=attention_downsample_rate,
47
+ skip_first_layer_pe=(i == 0),
48
+ )
49
+ )
50
+
51
+ self.final_attn_token_to_image = Attention(
52
+ embedding_dim, num_heads, downsample_rate=attention_downsample_rate
53
+ )
54
+ self.norm_final_attn = nn.LayerNorm(embedding_dim)
55
+
56
+ def forward(
57
+ self,
58
+ image_embedding: Tensor,
59
+ image_pe: Tensor,
60
+ point_embedding: Tensor,
61
+ ) -> Tuple[Tensor, Tensor]:
62
+ """
63
+ Args:
64
+ image_embedding (torch.Tensor): image to attend to. Should be shape
65
+ B x embedding_dim x h x w for any h and w.
66
+ image_pe (torch.Tensor): the positional encoding to add to the image. Must
67
+ have the same shape as image_embedding.
68
+ point_embedding (torch.Tensor): the embedding to add to the query points.
69
+ Must have shape B x N_points x embedding_dim for any N_points.
70
+
71
+ Returns:
72
+ torch.Tensor: the processed point_embedding
73
+ torch.Tensor: the processed image_embedding
74
+ """
75
+ # BxCxHxW -> BxHWxC == B x N_image_tokens x C
76
+ bs, c, h, w = image_embedding.shape
77
+ image_embedding = image_embedding.flatten(2).permute(0, 2, 1)
78
+ image_pe = image_pe.flatten(2).permute(0, 2, 1)
79
+
80
+ # Prepare queries
81
+ queries = point_embedding
82
+ keys = image_embedding
83
+
84
+ # Apply transformer blocks and final layernorm
85
+ for layer in self.layers:
86
+ queries, keys = layer(
87
+ queries=queries,
88
+ keys=keys,
89
+ query_pe=point_embedding,
90
+ key_pe=image_pe,
91
+ )
92
+
93
+ # Apply the final attention layer from the points to the image
94
+ q = queries + point_embedding
95
+ k = keys + image_pe
96
+ attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys)
97
+ queries = queries + attn_out
98
+ queries = self.norm_final_attn(queries)
99
+
100
+ return queries, keys
101
+
102
+
103
+ class TwoWayAttentionBlock(nn.Module):
104
+ def __init__(
105
+ self,
106
+ embedding_dim: int,
107
+ num_heads: int,
108
+ mlp_dim: int = 2048,
109
+ activation: Type[nn.Module] = nn.ReLU,
110
+ attention_downsample_rate: int = 2,
111
+ skip_first_layer_pe: bool = False,
112
+ ) -> None:
113
+ """
114
+ A transformer block with four layers: (1) self-attention of sparse
115
+ inputs, (2) cross attention of sparse inputs to dense inputs, (3) mlp
116
+ block on sparse inputs, and (4) cross attention of dense inputs to sparse
117
+ inputs.
118
+
119
+ Arguments:
120
+ embedding_dim (int): the channel dimension of the embeddings
121
+ num_heads (int): the number of heads in the attention layers
122
+ mlp_dim (int): the hidden dimension of the mlp block
123
+ activation (nn.Module): the activation of the mlp block
124
+ skip_first_layer_pe (bool): skip the PE on the first layer
125
+ """
126
+ super().__init__()
127
+ self.self_attn = Attention(embedding_dim, num_heads)
128
+ self.norm1 = nn.LayerNorm(embedding_dim)
129
+
130
+ self.cross_attn_token_to_image = Attention(
131
+ embedding_dim, num_heads, downsample_rate=attention_downsample_rate
132
+ )
133
+ self.norm2 = nn.LayerNorm(embedding_dim)
134
+
135
+ self.mlp = MLPBlock(embedding_dim, mlp_dim, activation)
136
+ self.norm3 = nn.LayerNorm(embedding_dim)
137
+
138
+ self.norm4 = nn.LayerNorm(embedding_dim)
139
+ self.cross_attn_image_to_token = Attention(
140
+ embedding_dim, num_heads, downsample_rate=attention_downsample_rate
141
+ )
142
+
143
+ self.skip_first_layer_pe = skip_first_layer_pe
144
+
145
+ def forward(
146
+ self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor
147
+ ) -> Tuple[Tensor, Tensor]:
148
+ # Self attention block
149
+ if self.skip_first_layer_pe:
150
+ queries = self.self_attn(q=queries, k=queries, v=queries)
151
+ else:
152
+ q = queries + query_pe
153
+ attn_out = self.self_attn(q=q, k=q, v=queries)
154
+ queries = queries + attn_out
155
+ queries = self.norm1(queries)
156
+
157
+ # Cross attention block, tokens attending to image embedding
158
+ q = queries + query_pe
159
+ k = keys + key_pe
160
+ attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys)
161
+ queries = queries + attn_out
162
+ queries = self.norm2(queries)
163
+
164
+ # MLP block
165
+ mlp_out = self.mlp(queries)
166
+ queries = queries + mlp_out
167
+ queries = self.norm3(queries)
168
+
169
+ # Cross attention block, image embedding attending to tokens
170
+ q = queries + query_pe
171
+ k = keys + key_pe
172
+ attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries)
173
+ keys = keys + attn_out
174
+ keys = self.norm4(keys)
175
+
176
+ return queries, keys
177
+
178
+
179
+ class Attention(nn.Module):
180
+ """
181
+ An attention layer that allows for downscaling the size of the embedding
182
+ after projection to queries, keys, and values.
183
+ """
184
+
185
+ def __init__(
186
+ self,
187
+ embedding_dim: int,
188
+ num_heads: int,
189
+ downsample_rate: int = 1,
190
+ ) -> None:
191
+ super().__init__()
192
+ self.embedding_dim = embedding_dim
193
+ self.internal_dim = embedding_dim // downsample_rate
194
+ self.num_heads = num_heads
195
+ assert self.internal_dim % num_heads == 0, "num_heads must divide embedding_dim."
196
+
197
+ self.q_proj = nn.Linear(embedding_dim, self.internal_dim)
198
+ self.k_proj = nn.Linear(embedding_dim, self.internal_dim)
199
+ self.v_proj = nn.Linear(embedding_dim, self.internal_dim)
200
+ self.out_proj = nn.Linear(self.internal_dim, embedding_dim)
201
+
202
+ def _separate_heads(self, x: Tensor, num_heads: int) -> Tensor:
203
+ b, n, c = x.shape
204
+ x = x.reshape(b, n, num_heads, c // num_heads)
205
+ return x.transpose(1, 2) # B x N_heads x N_tokens x C_per_head
206
+
207
+ def _recombine_heads(self, x: Tensor) -> Tensor:
208
+ b, n_heads, n_tokens, c_per_head = x.shape
209
+ x = x.transpose(1, 2)
210
+ return x.reshape(b, n_tokens, n_heads * c_per_head) # B x N_tokens x C
211
+
212
+ def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor:
213
+ # Input projections
214
+ q = self.q_proj(q)
215
+ k = self.k_proj(k)
216
+ v = self.v_proj(v)
217
+
218
+ # Separate into heads
219
+ q = self._separate_heads(q, self.num_heads)
220
+ k = self._separate_heads(k, self.num_heads)
221
+ v = self._separate_heads(v, self.num_heads)
222
+
223
+ # Attention
224
+ _, _, _, c_per_head = q.shape
225
+ attn = q @ k.permute(0, 1, 3, 2) # B x N_heads x N_tokens x N_tokens
226
+ attn = attn / math.sqrt(c_per_head)
227
+ attn = torch.softmax(attn, dim=-1)
228
+
229
+ # Get output
230
+ out = attn @ v
231
+ out = self._recombine_heads(out)
232
+ out = self.out_proj(out)
233
+
234
+ return out
HyperVision/predictor.py ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+
4
+ from HyperVision.modeling import Sam
5
+
6
+ from typing import Optional, Tuple
7
+
8
+ from HyperVision.utils.transforms import ResizeLongestSide
9
+
10
+
11
+ class HyperVision_Predictor:
12
+ def __init__(
13
+ self,
14
+ sam_model: Sam,
15
+ ) -> None:
16
+ """
17
+ Uses SAM to calculate the image embedding for an image, and then
18
+ allow repeated, efficient mask prediction given prompts.
19
+
20
+ Arguments:
21
+ sam_model (Sam): The model to use for mask prediction.
22
+ """
23
+ super().__init__()
24
+ self.model = sam_model
25
+ self.transform = ResizeLongestSide(sam_model.image_encoder.img_size)
26
+ self.reset_image()
27
+
28
+ def set_image(
29
+ self,
30
+ image: np.ndarray,
31
+ #image_format: str = "RGB",
32
+ test_mode = False,
33
+ spectral_lengths = None,
34
+ GSD = None
35
+ ) -> None:
36
+ """
37
+ Calculates the image embeddings for the provided image, allowing
38
+ masks to be predicted with the 'predict' method.
39
+
40
+ Arguments:
41
+ image (np.ndarray): The image for calculating masks. Expects an
42
+ image in HWC uint8 format, with pixel values in [0, 255].
43
+ image_format (str): The color format of the image, in ['RGB', 'BGR'].
44
+ """
45
+
46
+ if not torch.is_tensor(image):
47
+ image = torch.as_tensor(image, device=self.device).permute((2,0,1)).unsqueeze(0).float()
48
+ input_image = self.transform.apply_image_torch(image.float())
49
+ input_image = input_image.to(self.device)
50
+ self.set_torch_image(input_image, image.shape[-2:], test_mode, spectral_lengths,GSD=GSD)
51
+
52
+
53
+ def set_torch_image(
54
+ self,
55
+ transformed_image: torch.Tensor,
56
+ original_image_size: Tuple[int, ...],
57
+ test_mode=False,
58
+ spectral_lengths=None,
59
+ GSD=None,
60
+ ) -> None:
61
+ """
62
+ Calculates the image embeddings for the provided image, allowing
63
+ masks to be predicted with the 'predict' method. Expects the input
64
+ image to be already transformed to the format expected by the model.
65
+
66
+ Arguments:
67
+ transformed_image (torch.Tensor): The input image, with shape
68
+ 1x3xHxW, which has been transformed with ResizeLongestSide.
69
+ original_image_size (tuple(int, int)): The size of the image
70
+ before transformation, in (H, W) format.
71
+ """
72
+ # assert (
73
+ # len(transformed_image.shape) == 4
74
+ # and transformed_image.shape[1] == 3
75
+ # and max(*transformed_image.shape[2:]) == self.model.image_encoder.img_size
76
+ # ), f"set_torch_image input must be BCHW with long side {self.model.image_encoder.img_size}."
77
+ self.reset_image()
78
+
79
+ self.original_size = original_image_size
80
+ self.input_size = tuple(transformed_image.shape[-2:])
81
+ input_image = self.model.preprocess(transformed_image)
82
+ self.multi_scale_features= self.model.image_encoder(input_image, test_mode, spectral_lengths, GSD)
83
+ self.features = self.multi_scale_features[-1]
84
+ self.is_image_set = True
85
+
86
+
87
+ def set_image2(
88
+ self,
89
+ image: np.ndarray,
90
+ #image_format: str = "RGB",
91
+ test_mode = False,
92
+ spectral_lengths = None,
93
+ GSD = None,
94
+ ) -> None:
95
+ """
96
+ Calculates the image embeddings for the provided image, allowing
97
+ masks to be predicted with the 'predict' method.
98
+
99
+ Arguments:
100
+ image (np.ndarray): The image for calculating masks. Expects an
101
+ image in HWC uint8 format, with pixel values in [0, 255].
102
+ image_format (str): The color format of the image, in ['RGB', 'BGR'].
103
+ """
104
+
105
+ if not torch.is_tensor(image):
106
+ image = torch.as_tensor(image, device=self.device).permute((2,0,1)).unsqueeze(0).float()
107
+ input_image = self.transform.apply_image_torch(image.float())
108
+ input_image = input_image.to(self.device)
109
+ self.set_torch_image2(input_image, image.shape[-2:], test_mode, spectral_lengths, GSD=GSD)
110
+
111
+
112
+ def set_torch_image2(
113
+ self,
114
+ transformed_image: torch.Tensor,
115
+ original_image_size: Tuple[int, ...],
116
+ test_mode=False,
117
+ spectral_lengths=None,
118
+ GSD=None
119
+ ) -> None:
120
+ input_image = self.model.preprocess(transformed_image)
121
+ self.features2 = self.model.image_encoder(input_image, test_mode, spectral_lengths, GSD)[-1]
122
+
123
+
124
+ def predict(
125
+ self,
126
+ point_coords: Optional[np.ndarray] = None,
127
+ point_labels: Optional[np.ndarray] = None,
128
+ box: Optional[np.ndarray] = None,
129
+ mask_input: Optional[np.ndarray] = None,
130
+ multimask_output: bool = True,
131
+ return_logits: bool = False,
132
+ ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
133
+ """
134
+ Predict masks for the given input prompts, using the currently set image.
135
+
136
+ Arguments:
137
+ point_coords (np.ndarray or None): A Nx2 array of point prompts to the
138
+ model. Each point is in (X,Y) in pixels.
139
+ point_labels (np.ndarray or None): A length N array of labels for the
140
+ point prompts. 1 indicates a foreground point and 0 indicates a
141
+ background point.
142
+ box (np.ndarray or None): A length 4 array given a box prompt to the
143
+ model, in XYXY format.
144
+ mask_input (np.ndarray): A low resolution mask input to the model, typically
145
+ coming from a previous prediction iteration. Has form 1xHxW, where
146
+ for SAM, H=W=256.
147
+ multimask_output (bool): If true, the model will return three masks.
148
+ For ambiguous input prompts (such as a single click), this will often
149
+ produce better masks than a single prediction. If only a single
150
+ mask is needed, the model's predicted quality score can be used
151
+ to select the best mask. For non-ambiguous prompts, such as multiple
152
+ input prompts, multimask_output=False can give better results.
153
+ return_logits (bool): If true, returns un-thresholded masks logits
154
+ instead of a binary mask.
155
+
156
+ Returns:
157
+ (np.ndarray): The output masks in CxHxW format, where C is the
158
+ number of masks, and (H, W) is the original image size.
159
+ (np.ndarray): An array of length C containing the model's
160
+ predictions for the quality of each mask.
161
+ (np.ndarray): An array of shape CxHxW, where C is the number
162
+ of masks and H=W=256. These low resolution logits can be passed to
163
+ a subsequent iteration as mask input.
164
+ """
165
+ if not self.is_image_set:
166
+ raise RuntimeError("An image must be set with .set_image(...) before mask prediction.")
167
+
168
+ # Transform input prompts
169
+ coords_torch, labels_torch, box_torch, mask_input_torch = None, None, None, None
170
+ if point_coords is not None:
171
+ assert (
172
+ point_labels is not None
173
+ ), "point_labels must be supplied if point_coords is supplied."
174
+ point_coords = self.transform.apply_coords(point_coords, self.original_size)
175
+ coords_torch = torch.as_tensor(point_coords, dtype=torch.float, device=self.device)
176
+ labels_torch = torch.as_tensor(point_labels, dtype=torch.int, device=self.device)
177
+ if len(coords_torch.shape) != 3: #
178
+ coords_torch, labels_torch = coords_torch[None, :, :], labels_torch[None, :]
179
+ if box is not None:
180
+ box = self.transform.apply_boxes(box, self.original_size)
181
+ box_torch = torch.as_tensor(box, dtype=torch.float, device=self.device)
182
+ if len(box_torch.shape) != 2:
183
+ box_torch = box_torch[None, :]
184
+ if mask_input is not None:
185
+ mask_input_torch = torch.as_tensor(mask_input, dtype=torch.float, device=self.device)
186
+ mask_input_torch = mask_input_torch[None, :, :, :]
187
+
188
+ masks, iou_predictions, low_res_masks = self.predict_torch(
189
+ coords_torch,
190
+ labels_torch,
191
+ box_torch,
192
+ mask_input_torch,
193
+ multimask_output,
194
+ return_logits=return_logits,
195
+ )
196
+ # masks_torch = masks[0] # 1 3 H W
197
+ # iou_predictions_torch = iou_predictions[0]
198
+ # low_res_masks_torch = low_res_masks[0]
199
+
200
+ masks_torch = masks # 2 3 H W
201
+ iou_predictions_torch = iou_predictions
202
+ low_res_masks_torch = low_res_masks
203
+ return masks_torch, iou_predictions_torch, low_res_masks_torch
204
+ # masks_np = masks[0].detach().cpu().numpy()
205
+ # iou_predictions_np = iou_predictions[0].detach().cpu().numpy()
206
+ # low_res_masks_np = low_res_masks[0].detach().cpu().numpy()
207
+ # return masks_np, iou_predictions_np, low_res_masks_np
208
+
209
+ #@torch.no_grad()
210
+ def predict_torch(
211
+ self,
212
+ point_coords: Optional[torch.Tensor],
213
+ point_labels: Optional[torch.Tensor],
214
+ boxes: Optional[torch.Tensor] = None,
215
+ mask_input: Optional[torch.Tensor] = None,
216
+ multimask_output: bool = True,
217
+ return_logits: bool = False,
218
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
219
+ """
220
+ Predict masks for the given input prompts, using the currently set image.
221
+ Input prompts are batched torch tensors and are expected to already be
222
+ transformed to the input frame using ResizeLongestSide.
223
+
224
+ Arguments:
225
+ point_coords (torch.Tensor or None): A BxNx2 array of point prompts to the
226
+ model. Each point is in (X,Y) in pixels.
227
+ point_labels (torch.Tensor or None): A BxN array of labels for the
228
+ point prompts. 1 indicates a foreground point and 0 indicates a
229
+ background point.
230
+ boxes (np.ndarray or None): A Bx4 array given a box prompt to the
231
+ model, in XYXY format.
232
+ mask_input (np.ndarray): A low resolution mask input to the model, typically
233
+ coming from a previous prediction iteration. Has form Bx1xHxW, where
234
+ for SAM, H=W=256. Masks returned by a previous iteration of the
235
+ predict method do not need further transformation.
236
+ multimask_output (bool): If true, the model will return three masks.
237
+ For ambiguous input prompts (such as a single click), this will often
238
+ produce better masks than a single prediction. If only a single
239
+ mask is needed, the model's predicted quality score can be used
240
+ to select the best mask. For non-ambiguous prompts, such as multiple
241
+ input prompts, multimask_output=False can give better results.
242
+ return_logits (bool): If true, returns un-thresholded masks logits
243
+ instead of a binary mask.
244
+
245
+ Returns:
246
+ (torch.Tensor): The output masks in BxCxHxW format, where C is the
247
+ number of masks, and (H, W) is the original image size.
248
+ (torch.Tensor): An array of shape BxC containing the model's
249
+ predictions for the quality of each mask.
250
+ (torch.Tensor): An array of shape BxCxHxW, where C is the number
251
+ of masks and H=W=256. These low res logits can be passed to
252
+ a subsequent iteration as mask input.
253
+ """
254
+ if not self.is_image_set:
255
+ raise RuntimeError("An image must be set with .set_image(...) before mask prediction.")
256
+
257
+ if point_coords is not None:
258
+ points = (point_coords, point_labels)
259
+ else:
260
+ points = None
261
+
262
+ # Embed prompts
263
+ sparse_embeddings, dense_embeddings = self.model.prompt_encoder(
264
+ points=points,
265
+ boxes=boxes,
266
+ masks=mask_input,
267
+ )
268
+
269
+ # Predict masks
270
+ low_res_masks, iou_predictions = self.model.mask_decoder(
271
+ image_embeddings=self.features,
272
+ image_pe=self.model.prompt_encoder.get_dense_pe(),
273
+ sparse_prompt_embeddings=sparse_embeddings,
274
+ dense_prompt_embeddings=dense_embeddings,
275
+ multimask_output=multimask_output,
276
+ )
277
+
278
+ # Upscale the masks to the original image resolution
279
+ masks = self.model.postprocess_masks(low_res_masks, self.input_size, self.original_size)
280
+
281
+ if not return_logits:
282
+ masks = masks > self.model.mask_threshold
283
+
284
+ return masks, iou_predictions, low_res_masks
285
+
286
+ def get_image_embedding(self) -> torch.Tensor:
287
+ """
288
+ Returns the image embeddings for the currently set image, with
289
+ shape 1xCxHxW, where C is the embedding dimension and (H,W) are
290
+ the embedding spatial dimension of SAM (typically C=256, H=W=64).
291
+ """
292
+ if not self.is_image_set:
293
+ raise RuntimeError(
294
+ "An image must be set with .set_image(...) to generate an embedding."
295
+ )
296
+ assert self.features is not None, "Features must exist if an image has been set."
297
+ return self.features
298
+
299
+ @property
300
+ def device(self) -> torch.device:
301
+ return self.model.device
302
+
303
+ def reset_image(self) -> None:
304
+ """Resets the currently set image."""
305
+ self.is_image_set = False
306
+ self.features = None
307
+ self.orig_h = None
308
+ self.orig_w = None
309
+ self.input_h = None
310
+ self.input_w = None
HyperVision/utils/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
HyperVision/utils/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (149 Bytes). View file
 
HyperVision/utils/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (184 Bytes). View file
 
HyperVision/utils/__pycache__/amg.cpython-310.pyc ADDED
Binary file (12.1 kB). View file
 
HyperVision/utils/__pycache__/amg.cpython-311.pyc ADDED
Binary file (23 kB). View file
 
HyperVision/utils/__pycache__/spectral_process_utils.cpython-310.pyc ADDED
Binary file (5.59 kB). View file
 
HyperVision/utils/__pycache__/spectral_process_utils.cpython-311.pyc ADDED
Binary file (8.3 kB). View file
 
HyperVision/utils/__pycache__/transforms.cpython-310.pyc ADDED
Binary file (3.93 kB). View file
 
HyperVision/utils/__pycache__/transforms.cpython-311.pyc ADDED
Binary file (6.12 kB). View file
 
HyperVision/utils/amg.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import numpy as np
8
+ import torch
9
+
10
+ import math
11
+ from copy import deepcopy
12
+ from itertools import product
13
+ from typing import Any, Dict, Generator, ItemsView, List, Tuple
14
+
15
+
16
+ class MaskData:
17
+ """
18
+ A structure for storing masks and their related data in batched format.
19
+ Implements basic filtering and concatenation.
20
+ """
21
+
22
+ def __init__(self, **kwargs) -> None:
23
+ for v in kwargs.values():
24
+ assert isinstance(
25
+ v, (list, np.ndarray, torch.Tensor)
26
+ ), "MaskData only supports list, numpy arrays, and torch tensors."
27
+ self._stats = dict(**kwargs)
28
+
29
+ def __setitem__(self, key: str, item: Any) -> None:
30
+ assert isinstance(
31
+ item, (list, np.ndarray, torch.Tensor)
32
+ ), "MaskData only supports list, numpy arrays, and torch tensors."
33
+ self._stats[key] = item
34
+
35
+ def __delitem__(self, key: str) -> None:
36
+ del self._stats[key]
37
+
38
+ def __getitem__(self, key: str) -> Any:
39
+ return self._stats[key]
40
+
41
+ def items(self) -> ItemsView[str, Any]:
42
+ return self._stats.items()
43
+
44
+ def filter(self, keep: torch.Tensor) -> None:
45
+ for k, v in self._stats.items():
46
+ if v is None:
47
+ self._stats[k] = None
48
+ elif isinstance(v, torch.Tensor):
49
+ self._stats[k] = v[torch.as_tensor(keep, device=v.device)]
50
+ elif isinstance(v, np.ndarray):
51
+ self._stats[k] = v[keep.detach().cpu().numpy()]
52
+ elif isinstance(v, list) and keep.dtype == torch.bool:
53
+ self._stats[k] = [a for i, a in enumerate(v) if keep[i]]
54
+ elif isinstance(v, list):
55
+ self._stats[k] = [v[i] for i in keep]
56
+ else:
57
+ raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.")
58
+
59
+ def cat(self, new_stats: "MaskData") -> None:
60
+ for k, v in new_stats.items():
61
+ if k not in self._stats or self._stats[k] is None:
62
+ self._stats[k] = deepcopy(v)
63
+ elif isinstance(v, torch.Tensor):
64
+ self._stats[k] = torch.cat([self._stats[k], v], dim=0)
65
+ elif isinstance(v, np.ndarray):
66
+ self._stats[k] = np.concatenate([self._stats[k], v], axis=0)
67
+ elif isinstance(v, list):
68
+ self._stats[k] = self._stats[k] + deepcopy(v)
69
+ else:
70
+ raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.")
71
+
72
+ def to_numpy(self) -> None:
73
+ for k, v in self._stats.items():
74
+ if isinstance(v, torch.Tensor):
75
+ self._stats[k] = v.detach().cpu().numpy()
76
+
77
+
78
+ def is_box_near_crop_edge(
79
+ boxes: torch.Tensor, crop_box: List[int], orig_box: List[int], atol: float = 20.0
80
+ ) -> torch.Tensor:
81
+ """Filter masks at the edge of a crop, but not at the edge of the original image."""
82
+ crop_box_torch = torch.as_tensor(crop_box, dtype=torch.float, device=boxes.device)
83
+ orig_box_torch = torch.as_tensor(orig_box, dtype=torch.float, device=boxes.device)
84
+ boxes = uncrop_boxes_xyxy(boxes, crop_box).float()
85
+ near_crop_edge = torch.isclose(boxes, crop_box_torch[None, :], atol=atol, rtol=0)
86
+ near_image_edge = torch.isclose(boxes, orig_box_torch[None, :], atol=atol, rtol=0)
87
+ near_crop_edge = torch.logical_and(near_crop_edge, ~near_image_edge)
88
+ return torch.any(near_crop_edge, dim=1)
89
+
90
+
91
+ def box_xyxy_to_xywh(box_xyxy: torch.Tensor) -> torch.Tensor:
92
+ box_xywh = deepcopy(box_xyxy)
93
+ box_xywh[2] = box_xywh[2] - box_xywh[0]
94
+ box_xywh[3] = box_xywh[3] - box_xywh[1]
95
+ return box_xywh
96
+
97
+
98
+ def batch_iterator(batch_size: int, *args) -> Generator[List[Any], None, None]:
99
+ assert len(args) > 0 and all(
100
+ len(a) == len(args[0]) for a in args
101
+ ), "Batched iteration must have inputs of all the same size."
102
+ n_batches = len(args[0]) // batch_size + int(len(args[0]) % batch_size != 0)
103
+ for b in range(n_batches):
104
+ yield [arg[b * batch_size : (b + 1) * batch_size] for arg in args]
105
+
106
+
107
+ def mask_to_rle_pytorch(tensor: torch.Tensor) -> List[Dict[str, Any]]:
108
+ """
109
+ Encodes masks to an uncompressed RLE, in the format expected by
110
+ pycoco tools.
111
+ """
112
+ # Put in fortran order and flatten h,w
113
+ b, h, w = tensor.shape
114
+ tensor = tensor.permute(0, 2, 1).flatten(1)
115
+
116
+ # Compute change indices
117
+ diff = tensor[:, 1:] ^ tensor[:, :-1]
118
+ change_indices = diff.nonzero()
119
+
120
+ # Encode run length
121
+ out = []
122
+ for i in range(b):
123
+ cur_idxs = change_indices[change_indices[:, 0] == i, 1]
124
+ cur_idxs = torch.cat(
125
+ [
126
+ torch.tensor([0], dtype=cur_idxs.dtype, device=cur_idxs.device),
127
+ cur_idxs + 1,
128
+ torch.tensor([h * w], dtype=cur_idxs.dtype, device=cur_idxs.device),
129
+ ]
130
+ )
131
+ btw_idxs = cur_idxs[1:] - cur_idxs[:-1]
132
+ counts = [] if tensor[i, 0] == 0 else [0]
133
+ counts.extend(btw_idxs.detach().cpu().tolist())
134
+ out.append({"size": [h, w], "counts": counts})
135
+ return out
136
+
137
+
138
+ def rle_to_mask(rle: Dict[str, Any]) -> np.ndarray:
139
+ """Compute a binary mask from an uncompressed RLE."""
140
+ h, w = rle["size"]
141
+ mask = np.empty(h * w, dtype=bool)
142
+ idx = 0
143
+ parity = False
144
+ for count in rle["counts"]:
145
+ mask[idx : idx + count] = parity
146
+ idx += count
147
+ parity ^= True
148
+ mask = mask.reshape(w, h)
149
+ return mask.transpose() # Put in C order
150
+
151
+
152
+ def area_from_rle(rle: Dict[str, Any]) -> int:
153
+ return sum(rle["counts"][1::2])
154
+
155
+
156
+ def calculate_stability_score(
157
+ masks: torch.Tensor, mask_threshold: float, threshold_offset: float
158
+ ) -> torch.Tensor:
159
+ """
160
+ Computes the stability score for a batch of masks. The stability
161
+ score is the IoU between the binary masks obtained by thresholding
162
+ the predicted mask logits at high and low values.
163
+ """
164
+ # One mask is always contained inside the other.
165
+ # Save memory by preventing unnecessary cast to torch.int64
166
+ intersections = (
167
+ (masks > (mask_threshold + threshold_offset))
168
+ .sum(-1, dtype=torch.int16)
169
+ .sum(-1, dtype=torch.int32)
170
+ )
171
+ unions = (
172
+ (masks > (mask_threshold - threshold_offset))
173
+ .sum(-1, dtype=torch.int16)
174
+ .sum(-1, dtype=torch.int32)
175
+ )
176
+ return intersections / unions
177
+
178
+
179
+ def build_point_grid(n_per_side: int) -> np.ndarray:
180
+ """Generates a 2D grid of points evenly spaced in [0,1]x[0,1]."""
181
+ offset = 1 / (2 * n_per_side)
182
+ points_one_side = np.linspace(offset, 1 - offset, n_per_side)
183
+ points_x = np.tile(points_one_side[None, :], (n_per_side, 1))
184
+ points_y = np.tile(points_one_side[:, None], (1, n_per_side))
185
+ points = np.stack([points_x, points_y], axis=-1).reshape(-1, 2)
186
+ return points
187
+
188
+
189
+ def build_all_layer_point_grids(
190
+ n_per_side: int, n_layers: int, scale_per_layer: int
191
+ ) -> List[np.ndarray]:
192
+ """Generates point grids for all crop layers."""
193
+ points_by_layer = []
194
+ for i in range(n_layers + 1):
195
+ n_points = int(n_per_side / (scale_per_layer**i))
196
+ points_by_layer.append(build_point_grid(n_points))
197
+ return points_by_layer
198
+
199
+
200
+ def generate_crop_boxes(
201
+ im_size: Tuple[int, ...], n_layers: int, overlap_ratio: float
202
+ ) -> Tuple[List[List[int]], List[int]]:
203
+ """
204
+ Generates a list of crop boxes of different sizes. Each layer
205
+ has (2**i)**2 boxes for the ith layer.
206
+ """
207
+ crop_boxes, layer_idxs = [], []
208
+ im_h, im_w = im_size
209
+ short_side = min(im_h, im_w)
210
+
211
+ # Original image
212
+ crop_boxes.append([0, 0, im_w, im_h])
213
+ layer_idxs.append(0)
214
+
215
+ def crop_len(orig_len, n_crops, overlap):
216
+ return int(math.ceil((overlap * (n_crops - 1) + orig_len) / n_crops))
217
+
218
+ for i_layer in range(n_layers):
219
+ n_crops_per_side = 2 ** (i_layer + 1)
220
+ overlap = int(overlap_ratio * short_side * (2 / n_crops_per_side))
221
+
222
+ crop_w = crop_len(im_w, n_crops_per_side, overlap)
223
+ crop_h = crop_len(im_h, n_crops_per_side, overlap)
224
+
225
+ crop_box_x0 = [int((crop_w - overlap) * i) for i in range(n_crops_per_side)]
226
+ crop_box_y0 = [int((crop_h - overlap) * i) for i in range(n_crops_per_side)]
227
+
228
+ # Crops in XYWH format
229
+ for x0, y0 in product(crop_box_x0, crop_box_y0):
230
+ box = [x0, y0, min(x0 + crop_w, im_w), min(y0 + crop_h, im_h)]
231
+ crop_boxes.append(box)
232
+ layer_idxs.append(i_layer + 1)
233
+
234
+ return crop_boxes, layer_idxs
235
+
236
+
237
+ def uncrop_boxes_xyxy(boxes: torch.Tensor, crop_box: List[int]) -> torch.Tensor:
238
+ x0, y0, _, _ = crop_box
239
+ offset = torch.tensor([[x0, y0, x0, y0]], device=boxes.device)
240
+ # Check if boxes has a channel dimension
241
+ if len(boxes.shape) == 3:
242
+ offset = offset.unsqueeze(1)
243
+ return boxes + offset
244
+
245
+
246
+ def uncrop_points(points: torch.Tensor, crop_box: List[int]) -> torch.Tensor:
247
+ x0, y0, _, _ = crop_box
248
+ offset = torch.tensor([[x0, y0]], device=points.device)
249
+ # Check if points has a channel dimension
250
+ if len(points.shape) == 3:
251
+ offset = offset.unsqueeze(1)
252
+ return points + offset
253
+
254
+
255
+ def uncrop_masks(
256
+ masks: torch.Tensor, crop_box: List[int], orig_h: int, orig_w: int
257
+ ) -> torch.Tensor:
258
+ x0, y0, x1, y1 = crop_box
259
+ if x0 == 0 and y0 == 0 and x1 == orig_w and y1 == orig_h:
260
+ return masks
261
+ # Coordinate transform masks
262
+ pad_x, pad_y = orig_w - (x1 - x0), orig_h - (y1 - y0)
263
+ pad = (x0, pad_x - x0, y0, pad_y - y0)
264
+ return torch.nn.functional.pad(masks, pad, value=0)
265
+
266
+
267
+ def remove_small_regions(
268
+ mask: np.ndarray, area_thresh: float, mode: str
269
+ ) -> Tuple[np.ndarray, bool]:
270
+ """
271
+ Removes small disconnected regions and holes in a mask. Returns the
272
+ mask and an indicator of if the mask has been modified.
273
+ """
274
+ import cv2 # type: ignore
275
+
276
+ assert mode in ["holes", "islands"]
277
+ correct_holes = mode == "holes"
278
+ working_mask = (correct_holes ^ mask).astype(np.uint8)
279
+ n_labels, regions, stats, _ = cv2.connectedComponentsWithStats(working_mask, 8)
280
+ sizes = stats[:, -1][1:] # Row 0 is background label
281
+ small_regions = [i + 1 for i, s in enumerate(sizes) if s < area_thresh]
282
+ if len(small_regions) == 0:
283
+ return mask, False
284
+ fill_labels = [0] + small_regions
285
+ if not correct_holes:
286
+ fill_labels = [i for i in range(n_labels) if i not in fill_labels]
287
+ # If every region is below threshold, keep largest
288
+ if len(fill_labels) == 0:
289
+ fill_labels = [int(np.argmax(sizes)) + 1]
290
+ mask = np.isin(regions, fill_labels)
291
+ return mask, True
292
+
293
+
294
+ def coco_encode_rle(uncompressed_rle: Dict[str, Any]) -> Dict[str, Any]:
295
+ from pycocotools import mask as mask_utils # type: ignore
296
+
297
+ h, w = uncompressed_rle["size"]
298
+ rle = mask_utils.frPyObjects(uncompressed_rle, h, w)
299
+ rle["counts"] = rle["counts"].decode("utf-8") # Necessary to serialize with json
300
+ return rle
301
+
302
+
303
+ def batched_mask_to_box(masks: torch.Tensor) -> torch.Tensor:
304
+ """
305
+ Calculates boxes in XYXY format around masks. Return [0,0,0,0] for
306
+ an empty mask. For input shape C1xC2x...xHxW, the output shape is C1xC2x...x4.
307
+ """
308
+ # torch.max below raises an error on empty inputs, just skip in this case
309
+ if torch.numel(masks) == 0:
310
+ return torch.zeros(*masks.shape[:-2], 4, device=masks.device)
311
+
312
+ # Normalize shape to CxHxW
313
+ shape = masks.shape
314
+ h, w = shape[-2:]
315
+ if len(shape) > 2:
316
+ masks = masks.flatten(0, -3)
317
+ else:
318
+ masks = masks.unsqueeze(0)
319
+
320
+ # Get top and bottom edges
321
+ in_height, _ = torch.max(masks, dim=-1)
322
+ in_height_coords = in_height * torch.arange(h, device=in_height.device)[None, :]
323
+ bottom_edges, _ = torch.max(in_height_coords, dim=-1)
324
+ in_height_coords = in_height_coords + h * (~in_height)
325
+ top_edges, _ = torch.min(in_height_coords, dim=-1)
326
+
327
+ # Get left and right edges
328
+ in_width, _ = torch.max(masks, dim=-2)
329
+ in_width_coords = in_width * torch.arange(w, device=in_width.device)[None, :]
330
+ right_edges, _ = torch.max(in_width_coords, dim=-1)
331
+ in_width_coords = in_width_coords + w * (~in_width)
332
+ left_edges, _ = torch.min(in_width_coords, dim=-1)
333
+
334
+ # If the mask is empty the right edge will be to the left of the left edge.
335
+ # Replace these boxes with [0, 0, 0, 0]
336
+ empty_filter = (right_edges < left_edges) | (bottom_edges < top_edges)
337
+ out = torch.stack([left_edges, top_edges, right_edges, bottom_edges], dim=-1)
338
+ out = out * (~empty_filter).unsqueeze(-1)
339
+
340
+ # Return to original shape
341
+ if len(shape) > 2:
342
+ out = out.reshape(*shape[:-2], 4)
343
+ else:
344
+ out = out[0]
345
+
346
+ return out
HyperVision/utils/spectral_process_utils.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ import numpy as np
5
+ import random
6
+ TORCH_MAJOR = int(torch.__version__.split('.')[0])
7
+ TORCH_MINOR = int(torch.__version__.split('.')[1])
8
+ from osgeo import gdal
9
+
10
+ # Preset wavelengths of key bands
11
+ spectral_wavelength = [400, 412.5, 429.5, 443, 455, 467.5, 473.375, 481.25, 488.25,
12
+ 500, 520, 531, 536, 545, 550.5, 561.25, 564.75, 565.5, 575, 580,
13
+ 596, 605, 610, 612, 626, 627.5, 630, 635, 640, 645, 650, 655, 656,
14
+ 660, 664.5, 665, 667, 671.25, 677.5, 686, 700, 705, 710, 716, 725,
15
+ 730, 740, 748.5, 760, 764.25, 776, 783, 790, 808, 820, 825, 830,
16
+ 835.3125, 842, 850, 858.5, 865, 866, 869.5, 880, 896, 905, 910, 926,
17
+ 938, 945, 950, 959, 1240, 1375, 1575, 1575.5, 1610, 1640, 1650, 2050.25,
18
+ 2130, 2195, 2217.5,2500]
19
+
20
+ # Preset wavelength indices for weight dictionary from 400-2500
21
+ weight_bank_wavelength = np.arange(400,2510,10).tolist()
22
+
23
+ # Wavelengths for training AVIRIS hyperspectral data
24
+ input_wavelengths_hy=[ 404.6129, 414.2946, 423.9808, 433.6713, 443.3662, 453.0655,
25
+ 462.7692, 472.4773, 482.1898, 491.9066, 501.6279, 511.3535, 521.0836, 530.818, 540.5568, 550.3,
26
+ 560.0477, 569.7996, 579.556, 589.3168, 599.0819, 608.8515, 618.6254, 628.4037, 638.1865, 647.9736,
27
+ 657.7651, 667.561, 655.2923, 665.0994, 674.9012, 684.6979, 694.4894, 704.2756, 714.0566, 723.8325,
28
+ 733.6031, 743.3685, 753.1287, 762.8837, 772.6335, 782.3781, 792.1174, 801.8516, 811.5805, 821.3043,
29
+ 831.0228, 840.7361, 850.4442, 860.1471, 869.8448, 879.5372, 889.2245, 898.9066, 908.5834, 918.2551,
30
+ 927.9214, 937.5827, 947.2387, 956.8895, 966.5351, 976.1755, 985.8106, 995.4406, 1005.065, 1014.685,
31
+ 1024.299, 1033.908, 1043.512, 1053.111, 1062.704, 1072.293, 1081.876, 1091.454, 1101.026, 1110.594,
32
+ 1120.156, 1129.713, 1139.265, 1148.811, 1158.353, 1167.889, 1177.42, 1186.946, 1196.466, 1205.982,
33
+ 1215.492, 1224.997, 1234.496, 1243.991, 1253.48, 1262.964, 1253.373, 1263.346, 1273.318, 1283.291,
34
+ 1293.262, 1303.234, 1313.206, 1323.177, 1333.148, 1343.119, 1353.089, 1363.06, 1373.03, 1383.0,
35
+ 1392.969, 1402.939, 1412.908, 1422.877, 1432.845, 1442.814, 1452.782, 1462.75, 1472.718, 1482.685,
36
+ 1492.652, 1502.619, 1512.586, 1522.552, 1532.518, 1542.484, 1552.45, 1562.416, 1572.381, 1582.346,
37
+ 1592.311, 1602.275, 1612.24, 1622.204, 1632.167, 1642.131, 1652.094, 1662.057, 1672.02, 1681.983,
38
+ 1691.945, 1701.907, 1711.869, 1721.831, 1731.792, 1741.753, 1751.714, 1761.675, 1771.635, 1781.596,
39
+ 1791.556, 1801.515, 1811.475, 1821.434, 1831.393, 1841.352, 1851.31, 1861.269, 1871.227, 1880.184,
40
+ 1874.164, 1884.225, 1894.285, 1904.342, 1914.396, 1924.448, 1934.499, 1944.546, 1954.592, 1964.635,
41
+ 1974.675, 1984.714, 1994.75, 2004.784, 2014.815, 2024.845, 2034.872, 2044.896, 2054.919, 2064.939,
42
+ 2074.956, 2084.972, 2094.985, 2104.996, 2115.004, 2125.01, 2135.014, 2145.016, 2155.015, 2165.012,
43
+ 2175.007, 2184.999, 2194.989, 2204.977, 2214.962, 2224.945, 2234.926, 2244.905, 2254.881, 2264.854,
44
+ 2274.826, 2284.795, 2294.762, 2304.727, 2314.689, 2324.649, 2334.607, 2344.562, 2354.516, 2364.467,
45
+ 2374.415, 2384.361, 2394.305, 2404.247, 2414.186, 2424.123, 2434.058, 2443.99, 2453.92, 2463.848,
46
+ 2473.773, 2483.696, 2493.617, 2503.536]
47
+
48
+
49
+ # Wavelengths for training multispectral data
50
+ input_wavelengths_mu=[
51
+ 425,480,545,605,660,725,835,950
52
+ ]
53
+
54
+ def generate_random_indices(N, T):
55
+ indices = []
56
+ for _ in range(T):
57
+ index = random.randint(0, N)
58
+ indices.append(index)
59
+ return indices
60
+
61
+
62
+ #bandfeature = [4,5,7,8,9]
63
+ def split_by_wavelengths(tensor, indices, num_blocks,input_wavelengths):
64
+ B, C, H, W = tensor.shape
65
+ blocks = []
66
+ # 遍历光谱波长
67
+ for i in range(len(spectral_wavelength) - 1):
68
+ start_wavelength = spectral_wavelength[i]
69
+ end_wavelength = spectral_wavelength[i + 1]
70
+
71
+ block_indices = []
72
+ #is_first = True
73
+ for j, wavelength in enumerate(input_wavelengths):
74
+ if start_wavelength <= wavelength <= end_wavelength and j not in indices:
75
+ block_indices.append(j)
76
+ if not block_indices:
77
+ blocks.append(torch.empty(B, 0, H, W, device=tensor.device))
78
+ else:
79
+ block = tensor[:, block_indices, :, :]
80
+ blocks.append(block)
81
+
82
+ if len(blocks) < num_blocks:
83
+ blocks.append(torch.empty(B, 0, H, W, device=tensor.device))
84
+
85
+ return blocks
86
+
87
+
88
+ def find_corresponding_indices(input_wavelengths, target_wavelengths,dis):
89
+ corresponding_indices = []
90
+ unmatched_indices = []
91
+ matched_indices = []
92
+ for target_index, target_wavelength in enumerate(target_wavelengths):
93
+ found_corresponding = False
94
+ for input_index, input_wavelength in enumerate(input_wavelengths):
95
+ if abs(target_wavelength - input_wavelength) <= dis:
96
+ corresponding_indices.append(input_index)
97
+ found_corresponding = True
98
+ matched_indices.append(target_index)
99
+ break
100
+ if not found_corresponding:
101
+ unmatched_indices.append(target_index)
102
+ return corresponding_indices, unmatched_indices, matched_indices
103
+
104
+
105
+ def read_img(img_path: str):
106
+ """
107
+ Read imagery as ndarray
108
+ :param img_path:
109
+ :param gdal_read:
110
+ :return:
111
+ """
112
+ dataset = gdal.Open(img_path)
113
+ w, h = dataset.RasterXSize, dataset.RasterYSize
114
+ img = dataset.ReadAsArray(0, 0, w, h)
115
+ if len(img.shape) == 3:
116
+ img = np.transpose(img, axes=(1, 2, 0)) # [c,h,w]->[h,w,c]
117
+ return img
118
+
119
+
120
+ def write_img(img: np.ndarray, save_path: str):
121
+ """
122
+ Save ndarray as imagery
123
+ :param img:
124
+ :param save_path:
125
+ :param gdal_write:
126
+ :return:
127
+ """
128
+ if 'int8' in img.dtype.name:
129
+ datatype = gdal.GDT_Byte
130
+ elif 'int16' in img.dtype.name:
131
+ datatype = gdal.GDT_UInt16
132
+ else:
133
+ datatype = gdal.GDT_Float32
134
+
135
+ if len(img.shape) == 3:
136
+ img = np.transpose(img, axes=(2, 0, 1)) # [h,w,c]->[c,h,w]
137
+ elif len(img.shape) == 2:
138
+ img = np.expand_dims(img, axis=0)
139
+
140
+ img_bands, img_height, img_width = img.shape
141
+
142
+ driver = gdal.GetDriverByName("GTiff")
143
+ dataset = driver.Create(save_path, int(img_width), int(img_height), int(img_bands), datatype)
144
+ for i in range(img_bands):
145
+ dataset.GetRasterBand(i + 1).WriteArray(img[i])
146
+ del dataset
HyperVision/utils/transforms.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import numpy as np
8
+ import torch
9
+ from torch.nn import functional as F
10
+ from torchvision.transforms.functional import resize, to_pil_image # type: ignore
11
+
12
+ from copy import deepcopy
13
+ from typing import Tuple
14
+
15
+
16
+ class ResizeLongestSide:
17
+ """
18
+ Resizes images to the longest side 'target_length', as well as provides
19
+ methods for resizing coordinates and boxes. Provides methods for
20
+ transforming both numpy array and batched torch tensors.
21
+ """
22
+
23
+ def __init__(self, target_length: int) -> None:
24
+ self.target_length = target_length
25
+
26
+ def apply_image(self, image: np.ndarray) -> np.ndarray:
27
+ """
28
+ Expects a numpy array with shape HxWxC in uint8 format.
29
+ """
30
+ target_size = self.get_preprocess_shape(image.shape[0], image.shape[1], self.target_length)
31
+ return np.array(resize(to_pil_image(image), target_size))
32
+
33
+ def apply_coords(self, coords: np.ndarray, original_size: Tuple[int, ...]) -> np.ndarray:
34
+ """
35
+ Expects a numpy array of length 2 in the final dimension. Requires the
36
+ original image size in (H, W) format.
37
+ """
38
+ old_h, old_w = original_size
39
+ new_h, new_w = self.get_preprocess_shape(
40
+ original_size[0], original_size[1], self.target_length
41
+ )
42
+ coords = deepcopy(coords).astype(float)
43
+ coords[..., 0] = coords[..., 0] * (new_w / old_w)
44
+ coords[..., 1] = coords[..., 1] * (new_h / old_h)
45
+ return coords
46
+
47
+ def apply_boxes(self, boxes: np.ndarray, original_size: Tuple[int, ...]) -> np.ndarray:
48
+ """
49
+ Expects a numpy array shape Bx4. Requires the original image size
50
+ in (H, W) format.
51
+ """
52
+ boxes = self.apply_coords(boxes.reshape(-1, 2, 2), original_size)
53
+ return boxes.reshape(-1, 4)
54
+
55
+ def apply_image_torch(self, image: torch.Tensor) -> torch.Tensor:
56
+ """
57
+ Expects batched images with shape BxCxHxW and float format. This
58
+ transformation may not exactly match apply_image. apply_image is
59
+ the transformation expected by the model.
60
+ """
61
+ # Expects an image in BCHW format. May not exactly match apply_image.
62
+ target_size = self.get_preprocess_shape(image.shape[2], image.shape[3], self.target_length)
63
+ return F.interpolate(
64
+ image, target_size, mode="bilinear", align_corners=False, antialias=True
65
+ )
66
+
67
+ def apply_coords_torch(
68
+ self, coords: torch.Tensor, original_size: Tuple[int, ...]
69
+ ) -> torch.Tensor:
70
+ """
71
+ Expects a torch tensor with length 2 in the last dimension. Requires the
72
+ original image size in (H, W) format.
73
+ """
74
+ old_h, old_w = original_size
75
+ new_h, new_w = self.get_preprocess_shape(
76
+ original_size[0], original_size[1], self.target_length
77
+ )
78
+ coords = deepcopy(coords).to(torch.float)
79
+ coords[..., 0] = coords[..., 0] * (new_w / old_w)
80
+ coords[..., 1] = coords[..., 1] * (new_h / old_h)
81
+ return coords
82
+
83
+ def apply_boxes_torch(
84
+ self, boxes: torch.Tensor, original_size: Tuple[int, ...]
85
+ ) -> torch.Tensor:
86
+ """
87
+ Expects a torch tensor with shape Bx4. Requires the original image
88
+ size in (H, W) format.
89
+ """
90
+ boxes = self.apply_coords_torch(boxes.reshape(-1, 2, 2), original_size)
91
+ return boxes.reshape(-1, 4)
92
+
93
+ @staticmethod
94
+ def get_preprocess_shape(oldh: int, oldw: int, long_side_length: int) -> Tuple[int, int]:
95
+ """
96
+ Compute the output size given input size and target long side length.
97
+ """
98
+ scale = long_side_length * 1.0 / max(oldh, oldw)
99
+ newh, neww = oldh * scale, oldw * scale
100
+ neww = int(neww + 0.5)
101
+ newh = int(newh + 0.5)
102
+ return (newh, neww)