MCPcopy Create free account
hub / github.com/chenfei-wu/TaskMatrix / Segmenting

Class Segmenting

visual_chatgpt.py:802–1024  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

800
801
802class Segmenting:
803 def __init__(self, device):
804 print(f"Inintializing Segmentation to {device}")
805 self.device = device
806 self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
807 self.model_checkpoint_path = os.path.join("checkpoints","sam")
808
809 self.download_parameters()
810 self.sam = build_sam(checkpoint=self.model_checkpoint_path).to(device)
811 self.sam_predictor = SamPredictor(self.sam)
812 self.mask_generator = SamAutomaticMaskGenerator(self.sam)
813
814 self.saved_points = []
815 self.saved_labels = []
816
817 def download_parameters(self):
818 url = "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth"
819 if not os.path.exists(self.model_checkpoint_path):
820 wget.download(url,out=self.model_checkpoint_path)
821
822
823 def show_mask(self, mask: np.ndarray,image: np.ndarray,
824 random_color: bool = False, transparency=1) -> np.ndarray:
825
826 """Visualize a mask on top of an image.
827 Args:
828 mask (np.ndarray): A 2D array of shape (H, W).
829 image (np.ndarray): A 3D array of shape (H, W, 3).
830 random_color (bool): Whether to use a random color for the mask.
831 Outputs:
832 np.ndarray: A 3D array of shape (H, W, 3) with the mask
833 visualized on top of the image.
834 transparenccy: the transparency of the segmentation mask
835 """
836
837 if random_color:
838 color = np.concatenate([np.random.random(3)], axis=0)
839 else:
840 color = np.array([30 / 255, 144 / 255, 255 / 255])
841 h, w = mask.shape[-2:]
842 mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1) * 255
843
844 image = cv2.addWeighted(image, 0.7, mask_image.astype('uint8'), transparency, 0)
845
846
847 return image
848
849 def show_box(self, box, ax, label):
850 x0, y0 = box[0], box[1]
851 w, h = box[2] - box[0], box[3] - box[1]
852 ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor='green', facecolor=(0,0,0,0), lw=2))
853 ax.text(x0, y0, label)
854
855
856 def get_mask_with_boxes(self, image_pil, image, boxes_filt):
857
858 size = image_pil.size
859 H, W = size[1], size[0]

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected