|
| 1 | +import os |
| 2 | +import random |
| 3 | +from datetime import datetime |
| 4 | + |
| 5 | +import numpy as np |
| 6 | + |
| 7 | +from data_juicer.utils.cache_utils import DATA_JUICER_ASSETS_CACHE |
| 8 | +from data_juicer.utils.constant import Fields, MetaKeys |
| 9 | +from data_juicer.utils.lazy_loader import LazyLoader |
| 10 | +from data_juicer.utils.model_utils import check_model, get_model, prepare_model |
| 11 | + |
| 12 | +from ..base_op import OPERATORS, TAGGING_OPS, UNFORKABLE, Mapper |
| 13 | +from ..op_fusion import LOADED_VIDEOS |
| 14 | + |
| 15 | +OP_NAME = "video_object_segmenting_mapper" |
| 16 | + |
| 17 | +cv2 = LazyLoader("cv2", "opencv-python") |
| 18 | +ultralytics = LazyLoader("ultralytics") |
| 19 | +torch = LazyLoader("torch") |
| 20 | +transformers = LazyLoader("transformers") |
| 21 | + |
| 22 | + |
| 23 | +@TAGGING_OPS.register_module(OP_NAME) |
| 24 | +@UNFORKABLE.register_module(OP_NAME) |
| 25 | +@OPERATORS.register_module(OP_NAME) |
| 26 | +@LOADED_VIDEOS.register_module(OP_NAME) |
| 27 | +class VideoObjectSegmentingMapper(Mapper): |
| 28 | + """Text-guided semantic segmentation of valid objects throughout the video (YOLOE + SAM2).""" |
| 29 | + |
| 30 | + _accelerator = "cuda" |
| 31 | + |
| 32 | + def __init__( |
| 33 | + self, |
| 34 | + sam2_hf_model: str = "facebook/sam2.1-hiera-tiny", |
| 35 | + yoloe_path: str = "yoloe-11l-seg.pt", |
| 36 | + yoloe_conf: float = 0.5, |
| 37 | + torch_dtype: str = "bf16", |
| 38 | + if_binarize: bool = True, |
| 39 | + if_save_visualization: bool = False, |
| 40 | + save_visualization_dir: str = DATA_JUICER_ASSETS_CACHE, |
| 41 | + *args, |
| 42 | + **kwargs, |
| 43 | + ): |
| 44 | + """ |
| 45 | + Initialization method. |
| 46 | +
|
| 47 | + :param hf_model: Hugginface model id of SAM2. |
| 48 | + :param yoloe_path: The path to the YOLOE model. |
| 49 | + :param yoloe_conf: Confidence threshold for YOLOE object detection. |
| 50 | + :param torch_dtype: The floating point type used for model inference. Can |
| 51 | + be one of ['fp32', 'fp16', 'bf16']. |
| 52 | + :param if_binarize: Whether the final mask requires binarization. |
| 53 | + If 'if_save_visualization' is set to True, 'if_binarize' will |
| 54 | + automatically be adjusted to True. |
| 55 | + :param if_save_visualization: Whether to save visualization results. |
| 56 | + :param save_visualization_dir: The path for saving visualization results. |
| 57 | +
|
| 58 | + """ |
| 59 | + |
| 60 | + super().__init__(*args, **kwargs) |
| 61 | + |
| 62 | + # Requires the weights for YOLOE and mobileclip_blt. |
| 63 | + self.yoloe_model = ultralytics.YOLO(check_model(yoloe_path)) |
| 64 | + torch_dtype_dict = {"fp32": torch.float32, "fp16": torch.float16, "bf16": torch.bfloat16} |
| 65 | + self.torch_dtype = torch_dtype_dict[torch_dtype] |
| 66 | + self.sam2_model_key = prepare_model( |
| 67 | + model_type="huggingface", torch_dtype=self.torch_dtype, pretrained_model_name_or_path=sam2_hf_model |
| 68 | + ) |
| 69 | + |
| 70 | + self.tag_field_name = MetaKeys.video_object_segment_tags |
| 71 | + self.yoloe_conf = yoloe_conf |
| 72 | + self.if_save_visualization = if_save_visualization |
| 73 | + self.save_visualization_dir = save_visualization_dir |
| 74 | + self.if_binarize = True if if_save_visualization else if_binarize |
| 75 | + |
| 76 | + def process_single(self, sample=None, rank=None): |
| 77 | + # check if it's generated already |
| 78 | + if self.tag_field_name in sample[Fields.meta]: |
| 79 | + return sample |
| 80 | + |
| 81 | + # there is no video in this sample |
| 82 | + if self.video_key not in sample or not sample[self.video_key]: |
| 83 | + sample[Fields.meta][self.tag_field_name] = { |
| 84 | + "segment_data": [], |
| 85 | + "cls_id_dict": [], |
| 86 | + "object_cls_list": [], |
| 87 | + "yoloe_conf_list": [], |
| 88 | + } |
| 89 | + return sample |
| 90 | + |
| 91 | + sam2_model, sam2_processor = get_model(model_key=self.sam2_model_key, rank=rank, use_cuda=self.use_cuda()) |
| 92 | + |
| 93 | + # Perform semantic segmentation on the first frame using YOLOE |
| 94 | + videoCapture = cv2.VideoCapture(sample[self.video_key][0]) |
| 95 | + success, initial_frame = videoCapture.read() |
| 96 | + random_num_str = str(random.randint(10000, 99999)) |
| 97 | + now_time_str = str(datetime.now()) |
| 98 | + if success: |
| 99 | + if not os.path.exists(DATA_JUICER_ASSETS_CACHE): |
| 100 | + os.makedirs(DATA_JUICER_ASSETS_CACHE, exist_ok=True) |
| 101 | + |
| 102 | + temp_video_name = sample[self.video_key][0].split("/")[-1].replace(".mp4", "") |
| 103 | + temp_initial_frame_path = os.path.join( |
| 104 | + DATA_JUICER_ASSETS_CACHE, |
| 105 | + f"{temp_video_name}_initial_frame_{now_time_str}_{random_num_str}.jpg", |
| 106 | + ) |
| 107 | + cv2.imwrite(temp_initial_frame_path, initial_frame) |
| 108 | + else: |
| 109 | + # Failed to load initial frame |
| 110 | + sample[Fields.meta][self.tag_field_name] = { |
| 111 | + "segment_data": [], |
| 112 | + "cls_id_dict": [], |
| 113 | + "object_cls_list": [], |
| 114 | + "yoloe_conf_list": [], |
| 115 | + } |
| 116 | + return sample |
| 117 | + |
| 118 | + self.yoloe_model.set_classes( |
| 119 | + sample["main_character_list"], self.yoloe_model.get_text_pe(sample["main_character_list"]) |
| 120 | + ) |
| 121 | + results = self.yoloe_model.predict(temp_initial_frame_path, verbose=False, conf=self.yoloe_conf) |
| 122 | + yoloe_bboxes = results[0].boxes.xyxy.tolist() |
| 123 | + bboxes_cls = results[0].boxes.cls.tolist() |
| 124 | + bboxes_cls = [int(x) for x in bboxes_cls] |
| 125 | + cls_id_dict = results[0].names |
| 126 | + yoloe_conf_list = results[0].boxes.conf.tolist() |
| 127 | + |
| 128 | + obj_ids = [] |
| 129 | + object_cls_list = [] |
| 130 | + input_boxes = [] |
| 131 | + for temp_cls, temp_box in zip(bboxes_cls, yoloe_bboxes): |
| 132 | + obj_ids.append(len(obj_ids)) |
| 133 | + object_cls_list.append(temp_cls) |
| 134 | + input_boxes.append([int(x) for x in temp_box]) |
| 135 | + |
| 136 | + input_boxes = [input_boxes] |
| 137 | + os.remove(temp_initial_frame_path) |
| 138 | + |
| 139 | + if len(obj_ids) == 0: |
| 140 | + sample[Fields.meta][self.tag_field_name] = { |
| 141 | + "segment_data": [], |
| 142 | + "cls_id_dict": [], |
| 143 | + "object_cls_list": [], |
| 144 | + "yoloe_conf_list": [], |
| 145 | + } |
| 146 | + return sample |
| 147 | + |
| 148 | + # Track objects with SAM2 |
| 149 | + video_frames, _ = transformers.video_utils.load_video(sample[self.video_key][0]) |
| 150 | + |
| 151 | + inference_session = sam2_processor.init_video_session( |
| 152 | + video=video_frames, |
| 153 | + inference_device="cuda" if self.use_cuda() else "cpu", |
| 154 | + dtype=self.torch_dtype, |
| 155 | + ) |
| 156 | + |
| 157 | + ann_frame_idx = 0 |
| 158 | + sam2_processor.add_inputs_to_inference_session( |
| 159 | + inference_session=inference_session, |
| 160 | + frame_idx=ann_frame_idx, |
| 161 | + obj_ids=obj_ids, |
| 162 | + input_boxes=input_boxes, |
| 163 | + ) |
| 164 | + |
| 165 | + # Get masks for all objects on the first frame |
| 166 | + outputs = sam2_model( |
| 167 | + inference_session=inference_session, |
| 168 | + frame_idx=ann_frame_idx, |
| 169 | + ) |
| 170 | + video_res_masks = sam2_processor.post_process_masks( |
| 171 | + [outputs.pred_masks], |
| 172 | + original_sizes=[[inference_session.video_height, inference_session.video_width]], |
| 173 | + binarize=False, |
| 174 | + )[0] |
| 175 | + |
| 176 | + # Propagate all objects through the video |
| 177 | + video_segments = [] |
| 178 | + for sam2_video_output in sam2_model.propagate_in_video_iterator(inference_session): |
| 179 | + video_res_masks = sam2_processor.post_process_masks( |
| 180 | + [sam2_video_output.pred_masks], |
| 181 | + original_sizes=[[inference_session.video_height, inference_session.video_width]], |
| 182 | + binarize=self.if_binarize, |
| 183 | + )[0] |
| 184 | + video_segments.append([video_res_masks[i].tolist() for i, obj_id in enumerate(inference_session.obj_ids)]) |
| 185 | + |
| 186 | + sample[Fields.meta][self.tag_field_name] = {} |
| 187 | + sample[Fields.meta][self.tag_field_name]["segment_data"] = video_segments |
| 188 | + sample[Fields.meta][self.tag_field_name]["cls_id_dict"] = [cls_id_dict[key] for key in cls_id_dict] |
| 189 | + sample[Fields.meta][self.tag_field_name]["object_cls_list"] = object_cls_list |
| 190 | + sample[Fields.meta][self.tag_field_name]["yoloe_conf_list"] = yoloe_conf_list |
| 191 | + |
| 192 | + if self.if_save_visualization: |
| 193 | + if not os.path.exists(self.save_visualization_dir): |
| 194 | + os.makedirs(self.save_visualization_dir, exist_ok=True) |
| 195 | + |
| 196 | + for temp_frame_masks_id, temp_frame_masks in enumerate( |
| 197 | + sample[Fields.meta][self.tag_field_name]["segment_data"] |
| 198 | + ): |
| 199 | + for temp_obj_id, temp_mask in enumerate(temp_frame_masks): |
| 200 | + temp_img = np.zeros((initial_frame.shape[0], initial_frame.shape[1], 3), np.uint8) |
| 201 | + temp_mask = np.squeeze(np.array(temp_mask)) |
| 202 | + temp_img[temp_mask] = [225, 225, 225] |
| 203 | + |
| 204 | + temp_mask_path = os.path.join( |
| 205 | + self.save_visualization_dir, |
| 206 | + f"{temp_video_name}_mask_{str(temp_obj_id)}_{str(temp_frame_masks_id)}_{now_time_str}_{random_num_str}.jpg", |
| 207 | + ) |
| 208 | + cv2.imwrite(temp_mask_path, temp_img) |
| 209 | + |
| 210 | + return sample |
0 commit comments