{"repo_id":"Track-Anything","entity_id":"py:demo","uri":"program://Track-Anything/module/demo#L1-L87","kind":"module","name":"demo","path":"demo.py","language":"python","start_line":1,"end_line":87,"context_start_line":1,"context_end_line":87,"code":"from metaseg import SegAutoMaskPredictor, SegManualMaskPredictor, SahiAutoSegmentation, sahi_sliced_predict\n\n# For image\n\ndef automask_image_app(image_path, model_type, points_per_side, points_per_batch, min_area):\n SegAutoMaskPredictor().image_predict(\n source=image_path,\n model_type=model_type, # vit_l, vit_h, vit_b\n points_per_side=points_per_side,\n points_per_batch=points_per_batch,\n min_area=min_area,\n output_path=\"output.png\",\n show=False,\n save=True,\n )\n return \"output.png\"\n\n\n# For video\n\ndef automask_video_app(video_path, model_type, points_per_side, points_per_batch, min_area):\n SegAutoMaskPredictor().video_predict(\n source=video_path,\n model_type=model_type, # vit_l, vit_h, vit_b\n points_per_side=points_per_side,\n points_per_batch=points_per_batch,\n min_area=min_area,\n output_path=\"output.mp4\",\n )\n return \"output.mp4\"\n\n\n# For manuel box and point selection\n\ndef manual_app(image_path, model_type, input_point, input_label, input_box, multimask_output, random_color):\n SegManualMaskPredictor().image_predict(\n source=image_path,\n model_type=model_type, # vit_l, vit_h, vit_b\n input_point=input_point,\n input_label=input_label,\n input_box=input_box,\n multimask_output=multimask_output,\n random_color=random_color,\n output_path=\"output.png\",\n show=False,\n save=True,\n )\n return \"output.png\"\n\n\n# For sahi sliced prediction\n\ndef sahi_autoseg_app(\n image_path,\n sam_model_type,\n detection_model_type,\n detection_model_path,\n conf_th,\n image_size,\n slice_height,\n slice_width,\n overlap_height_ratio,\n overlap_width_ratio,\n):\n boxes = sahi_sliced_predict(\n image_path=image_path,\n detection_model_type=detection_model_type, # yolov8, detectron2, mmdetection, torchvision\n detection_model_path=detection_model_path,\n conf_th=conf_th,\n image_size=image_size,\n slice_height=slice_height,\n slice_width=slice_width,\n overlap_height_ratio=overlap_height_ratio,\n overlap_width_ratio=overlap_width_ratio,\n )\n\n SahiAutoSegmentation().predict(\n source=image_path,\n model_type=sam_model_type,\n input_box=boxes,\n multimask_output=False,\n random_color=False,\n show=False,\n save=True,\n )\n \n return \"output.png\"","source_hash":"e112615210a4a3c358dc95f368064333cbd942b56960ed8a14a913eb455b8f05","truncated":false} {"repo_id":"Track-Anything","entity_id":"py:demo.automask_image_app","uri":"program://Track-Anything/function/demo.automask_image_app#L5-L16","kind":"function","name":"automask_image_app","path":"demo.py","language":"python","start_line":5,"end_line":16,"context_start_line":1,"context_end_line":36,"code":"from metaseg import SegAutoMaskPredictor, SegManualMaskPredictor, SahiAutoSegmentation, sahi_sliced_predict\n\n# For image\n\ndef automask_image_app(image_path, model_type, points_per_side, points_per_batch, min_area):\n SegAutoMaskPredictor().image_predict(\n source=image_path,\n model_type=model_type, # vit_l, vit_h, vit_b\n points_per_side=points_per_side,\n points_per_batch=points_per_batch,\n min_area=min_area,\n output_path=\"output.png\",\n show=False,\n save=True,\n )\n return \"output.png\"\n\n\n# For video\n\ndef automask_video_app(video_path, model_type, points_per_side, points_per_batch, min_area):\n SegAutoMaskPredictor().video_predict(\n source=video_path,\n model_type=model_type, # vit_l, vit_h, vit_b\n points_per_side=points_per_side,\n points_per_batch=points_per_batch,\n min_area=min_area,\n output_path=\"output.mp4\",\n )\n return \"output.mp4\"\n\n\n# For manuel box and point selection\n\ndef manual_app(image_path, model_type, input_point, input_label, input_box, multimask_output, random_color):\n SegManualMaskPredictor().image_predict(","source_hash":"e112615210a4a3c358dc95f368064333cbd942b56960ed8a14a913eb455b8f05","truncated":false} {"repo_id":"Track-Anything","entity_id":"py:demo.automask_video_app","uri":"program://Track-Anything/function/demo.automask_video_app#L21-L30","kind":"function","name":"automask_video_app","path":"demo.py","language":"python","start_line":21,"end_line":30,"context_start_line":1,"context_end_line":50,"code":"from metaseg import SegAutoMaskPredictor, SegManualMaskPredictor, SahiAutoSegmentation, sahi_sliced_predict\n\n# For image\n\ndef automask_image_app(image_path, model_type, points_per_side, points_per_batch, min_area):\n SegAutoMaskPredictor().image_predict(\n source=image_path,\n model_type=model_type, # vit_l, vit_h, vit_b\n points_per_side=points_per_side,\n points_per_batch=points_per_batch,\n min_area=min_area,\n output_path=\"output.png\",\n show=False,\n save=True,\n )\n return \"output.png\"\n\n\n# For video\n\ndef automask_video_app(video_path, model_type, points_per_side, points_per_batch, min_area):\n SegAutoMaskPredictor().video_predict(\n source=video_path,\n model_type=model_type, # vit_l, vit_h, vit_b\n points_per_side=points_per_side,\n points_per_batch=points_per_batch,\n min_area=min_area,\n output_path=\"output.mp4\",\n )\n return \"output.mp4\"\n\n\n# For manuel box and point selection\n\ndef manual_app(image_path, model_type, input_point, input_label, input_box, multimask_output, random_color):\n SegManualMaskPredictor().image_predict(\n source=image_path,\n model_type=model_type, # vit_l, vit_h, vit_b\n input_point=input_point,\n input_label=input_label,\n input_box=input_box,\n multimask_output=multimask_output,\n random_color=random_color,\n output_path=\"output.png\",\n show=False,\n save=True,\n )\n return \"output.png\"\n\n","source_hash":"e112615210a4a3c358dc95f368064333cbd942b56960ed8a14a913eb455b8f05","truncated":false} {"repo_id":"Track-Anything","entity_id":"py:demo.manual_app","uri":"program://Track-Anything/function/demo.manual_app#L35-L48","kind":"function","name":"manual_app","path":"demo.py","language":"python","start_line":35,"end_line":48,"context_start_line":15,"context_end_line":68,"code":" )\n return \"output.png\"\n\n\n# For video\n\ndef automask_video_app(video_path, model_type, points_per_side, points_per_batch, min_area):\n SegAutoMaskPredictor().video_predict(\n source=video_path,\n model_type=model_type, # vit_l, vit_h, vit_b\n points_per_side=points_per_side,\n points_per_batch=points_per_batch,\n min_area=min_area,\n output_path=\"output.mp4\",\n )\n return \"output.mp4\"\n\n\n# For manuel box and point selection\n\ndef manual_app(image_path, model_type, input_point, input_label, input_box, multimask_output, random_color):\n SegManualMaskPredictor().image_predict(\n source=image_path,\n model_type=model_type, # vit_l, vit_h, vit_b\n input_point=input_point,\n input_label=input_label,\n input_box=input_box,\n multimask_output=multimask_output,\n random_color=random_color,\n output_path=\"output.png\",\n show=False,\n save=True,\n )\n return \"output.png\"\n\n\n# For sahi sliced prediction\n\ndef sahi_autoseg_app(\n image_path,\n sam_model_type,\n detection_model_type,\n detection_model_path,\n conf_th,\n image_size,\n slice_height,\n slice_width,\n overlap_height_ratio,\n overlap_width_ratio,\n):\n boxes = sahi_sliced_predict(\n image_path=image_path,\n detection_model_type=detection_model_type, # yolov8, detectron2, mmdetection, torchvision\n detection_model_path=detection_model_path,","source_hash":"e112615210a4a3c358dc95f368064333cbd942b56960ed8a14a913eb455b8f05","truncated":false} {"repo_id":"Track-Anything","entity_id":"py:demo.sahi_autoseg_app","uri":"program://Track-Anything/function/demo.sahi_autoseg_app#L53-L87","kind":"function","name":"sahi_autoseg_app","path":"demo.py","language":"python","start_line":53,"end_line":87,"context_start_line":33,"context_end_line":87,"code":"# For manuel box and point selection\n\ndef manual_app(image_path, model_type, input_point, input_label, input_box, multimask_output, random_color):\n SegManualMaskPredictor().image_predict(\n source=image_path,\n model_type=model_type, # vit_l, vit_h, vit_b\n input_point=input_point,\n input_label=input_label,\n input_box=input_box,\n multimask_output=multimask_output,\n random_color=random_color,\n output_path=\"output.png\",\n show=False,\n save=True,\n )\n return \"output.png\"\n\n\n# For sahi sliced prediction\n\ndef sahi_autoseg_app(\n image_path,\n sam_model_type,\n detection_model_type,\n detection_model_path,\n conf_th,\n image_size,\n slice_height,\n slice_width,\n overlap_height_ratio,\n overlap_width_ratio,\n):\n boxes = sahi_sliced_predict(\n image_path=image_path,\n detection_model_type=detection_model_type, # yolov8, detectron2, mmdetection, torchvision\n detection_model_path=detection_model_path,\n conf_th=conf_th,\n image_size=image_size,\n slice_height=slice_height,\n slice_width=slice_width,\n overlap_height_ratio=overlap_height_ratio,\n overlap_width_ratio=overlap_width_ratio,\n )\n\n SahiAutoSegmentation().predict(\n source=image_path,\n model_type=sam_model_type,\n input_box=boxes,\n multimask_output=False,\n random_color=False,\n show=False,\n save=True,\n )\n \n return \"output.png\"","source_hash":"e112615210a4a3c358dc95f368064333cbd942b56960ed8a14a913eb455b8f05","truncated":false} {"repo_id":"Track-Anything","entity_id":"py:app","uri":"program://Track-Anything/module/app#L1-L602","kind":"module","name":"app","path":"app.py","language":"python","start_line":1,"end_line":602,"context_start_line":1,"context_end_line":602,"code":"import gradio as gr\nimport argparse\nimport gdown\nimport cv2\nimport numpy as np\nimport os\nimport sys\nsys.path.append(sys.path[0]+\"/tracker\")\nsys.path.append(sys.path[0]+\"/tracker/model\")\nfrom track_anything import TrackingAnything\nfrom track_anything import parse_augment\nimport requests\nimport json\nimport torchvision\nimport torch \nfrom tools.painter import mask_painter\nimport psutil\nimport time\ntry: \n from mmcv.cnn import ConvModule\nexcept:\n os.system(\"mim install mmcv\")\n\n# download checkpoints\ndef download_checkpoint(url, folder, filename):\n os.makedirs(folder, exist_ok=True)\n filepath = os.path.join(folder, filename)\n\n if not os.path.exists(filepath):\n print(\"download checkpoints ......\")\n response = requests.get(url, stream=True)\n with open(filepath, \"wb\") as f:\n for chunk in response.iter_content(chunk_size=8192):\n if chunk:\n f.write(chunk)\n\n print(\"download successfully!\")\n\n return filepath\n\ndef download_checkpoint_from_google_drive(file_id, folder, filename):\n os.makedirs(folder, exist_ok=True)\n filepath = os.path.join(folder, filename)\n\n if not os.path.exists(filepath):\n print(\"Downloading checkpoints from Google Drive... tips: If you cannot see the progress bar, please try to download it manuall \\\n and put it in the checkpointes directory. E2FGVI-HQ-CVPR22.pth: https://github.com/MCG-NKU/E2FGVI(E2FGVI-HQ model)\")\n url = f\"https://drive.google.com/uc?id={file_id}\"\n gdown.download(url, filepath, quiet=False)\n print(\"Downloaded successfully!\")\n\n return filepath\n\n# convert points input to prompt state\ndef get_prompt(click_state, click_input):\n inputs = json.loads(click_input)\n points = click_state[0]\n labels = click_state[1]\n for input in inputs:\n points.append(input[:2])\n labels.append(input[2])\n click_state[0] = points\n click_state[1] = labels\n prompt = {\n \"prompt_type\":[\"click\"],\n \"input_point\":click_state[0],\n \"input_label\":click_state[1],\n \"multimask_output\":\"True\",\n }\n return prompt\n\n\n# extract frames from upload video\ndef get_frames_from_video(video_input, video_state):\n \"\"\"\n Args:\n video_path:str\n timestamp:float64\n Return \n [[0:nearest_frame], [nearest_frame:], nearest_frame]\n \"\"\"\n video_path = video_input\n frames = []\n user_name = time.time()\n operation_log = [(\"\",\"\"),(\"Upload video already. Try click the image for adding targets to track and inpaint.\",\"Normal\")]\n try:\n cap = cv2.VideoCapture(video_path)\n fps = cap.get(cv2.CAP_PROP_FPS)\n while cap.isOpened():\n ret, frame = cap.read()\n if ret == True:\n current_memory_usage = psutil.virtual_memory().percent\n frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n if current_memory_usage > 90:\n operation_log = [(\"Memory usage is too high (>90%). Stop the video extraction. Please reduce the video resolution or frame rate.\", \"Error\")]\n print(\"Memory usage is too high (>90%). Please reduce the video resolution or frame rate.\")\n break\n else:\n break\n except (OSError, TypeError, ValueError, KeyError, SyntaxError) as e:\n print(\"read_frame_source:{} error. {}\\n\".format(video_path, str(e)))\n image_size = (frames[0].shape[0],frames[0].shape[1]) \n # initialize video_state\n video_state = {\n \"user_name\": user_name,\n \"video_name\": os.path.split(video_path)[-1],\n \"origin_images\": frames,\n \"painted_images\": frames.copy(),\n \"masks\": [np.zeros((frames[0].shape[0],frames[0].shape[1]), np.uint8)]*len(frames),\n \"logits\": [None]*len(frames),\n \"select_frame_number\": 0,\n \"fps\": fps\n }\n video_info = \"Video Name: {}, FPS: {}, Total Frames: {}, Image Size:{}\".format(video_state[\"video_name\"], video_state[\"fps\"], len(frames), image_size)\n model.samcontroler.sam_controler.reset_image() \n model.samcontroler.sam_controler.set_image(video_state[\"origin_images\"][0])\n return video_state, video_info, video_state[\"origin_images\"][0], gr.update(visible=True, maximum=len(frames), value=1), gr.update(visible=True, maximum=len(frames), value=len(frames)), \\\n gr.update(visible=True),\\\n gr.update(visible=True), gr.update(visible=True), \\\n gr.update(visible=True), gr.update(visible=True), \\\n gr.update(visible=True), gr.update(visible=True), \\\n gr.update(visible=True), gr.update(visible=True), \\\n gr.update(visible=True, value=operation_log)\n\ndef run_example(example):\n return video_input\n# get the select frame from gradio slider\ndef select_template(image_selection_slider, video_state, interactive_state, mask_dropdown):\n\n # images = video_state[1]\n image_selection_slider -= 1\n video_state[\"select_frame_number\"] = image_selection_slider\n\n # once select a new template frame, set the image in sam\n\n model.samcontroler.sam_controler.reset_image()\n model.samcontroler.sam_controler.set_image(video_state[\"origin_images\"][image_selection_slider])\n\n # update the masks when select a new template frame\n # if video_state[\"masks\"][image_selection_slider] is not None:\n # video_state[\"painted_images\"][image_selection_slider] = mask_painter(video_state[\"origin_images\"][image_selection_slider], video_state[\"masks\"][image_selection_slider])\n if mask_dropdown:\n print(\"ok\")\n operation_log = [(\"\",\"\"), (\"Select frame {}. Try click image and add mask for tracking.\".format(image_selection_slider),\"Normal\")]\n\n\n return video_state[\"painted_images\"][image_selection_slider], video_state, interactive_state, operation_log\n\n# set the tracking end frame\ndef get_end_number(track_pause_number_slider, video_state, interactive_state):\n interactive_state[\"track_end_number\"] = track_pause_number_slider\n operation_log = [(\"\",\"\"),(\"Set the tracking finish at frame {}\".format(track_pause_number_slider),\"Normal\")]\n\n return video_state[\"painted_images\"][track_pause_number_slider],interactive_state, operation_log\n\ndef get_resize_ratio(resize_ratio_slider, interactive_state):\n interactive_state[\"resize_ratio\"] = resize_ratio_slider\n\n return interactive_state\n\n# use sam to get the mask\ndef sam_refine(video_state, point_prompt, click_state, interactive_state, evt:gr.SelectData):\n \"\"\"\n Args:\n template_frame: PIL.Image\n point_prompt: flag for positive or negative button click\n click_state: [[points], [labels]]\n \"\"\"\n if point_prompt == \"Positive\":\n coordinate = \"[[{},{},1]]\".format(evt.index[0], evt.index[1])\n interactive_state[\"positive_click_times\"] += 1\n else:\n coordinate = \"[[{},{},0]]\".format(evt.index[0], evt.index[1])\n interactive_state[\"negative_click_times\"] += 1\n \n # prompt for sam model\n model.samcontroler.sam_controler.reset_image()\n model.samcontroler.sam_controler.set_image(video_state[\"origin_images\"][video_state[\"select_frame_number\"]])\n prompt = get_prompt(click_state=click_state, click_input=coordinate)\n\n mask, logit, painted_image = model.first_frame_click( \n image=video_state[\"origin_images\"][video_state[\"select_frame_number\"]], \n points=np.array(prompt[\"input_point\"]),\n labels=np.array(prompt[\"input_label\"]),\n multimask=prompt[\"multimask_output\"],\n )\n video_state[\"masks\"][video_state[\"select_frame_number\"]] = mask\n video_state[\"logits\"][video_state[\"select_frame_number\"]] = logit\n video_state[\"painted_images\"][video_state[\"select_frame_number\"]] = painted_image\n\n operation_log = [(\"\",\"\"), (\"Use SAM for segment. You can try add positive and negative points by clicking. Or press Clear clicks button to refresh the image. Press Add mask button when you are satisfied with the segment\",\"Normal\")]\n return painted_image, video_state, interactive_state, operation_log\n\ndef add_multi_mask(video_state, interactive_state, mask_dropdown):\n try:\n mask = video_state[\"masks\"][video_state[\"select_frame_number\"]]\n interactive_state[\"multi_mask\"][\"masks\"].append(mask)\n interactive_state[\"multi_mask\"][\"mask_names\"].append(\"mask_{:03d}\".format(len(interactive_state[\"multi_mask\"][\"masks\"])))\n mask_dropdown.append(\"mask_{:03d}\".format(len(interactive_state[\"multi_mask\"][\"masks\"])))\n select_frame, run_status = show_mask(video_state, interactive_state, mask_dropdown)\n\n operation_log = [(\"\",\"\"),(\"Added a mask, use the mask select for target tracking or inpainting.\",\"Normal\")]\n except:\n operation_log = [(\"Please click the left image to generate mask.\", \"Error\"), (\"\",\"\")]\n return interactive_state, gr.update(choices=interactive_state[\"multi_mask\"][\"mask_names\"], value=mask_dropdown), select_frame, [[],[]], operation_log\n\ndef clear_click(video_state, click_state):\n click_state = [[],[]]\n template_frame = video_state[\"origin_images\"][video_state[\"select_frame_number\"]]\n operation_log = [(\"\",\"\"), (\"Clear points history and refresh the image.\",\"Normal\")]\n return template_frame, click_state, operation_log\n\ndef remove_multi_mask(interactive_state, mask_dropdown):\n interactive_state[\"multi_mask\"][\"mask_names\"]= []\n interactive_state[\"multi_mask\"][\"masks\"] = []\n\n operation_log = [(\"\",\"\"), (\"Remove all mask, please add new masks\",\"Normal\")]\n return interactive_state, gr.update(choices=[],value=[]), operation_log\n\ndef show_mask(video_state, interactive_state, mask_dropdown):\n mask_dropdown.sort()\n select_frame = video_state[\"origin_images\"][video_state[\"select_frame_number\"]]\n for i in range(len(mask_dropdown)):\n mask_number = int(mask_dropdown[i].split(\"_\")[1]) - 1\n mask = interactive_state[\"multi_mask\"][\"masks\"][mask_number]\n select_frame = mask_painter(select_frame, mask.astype('uint8'), mask_color=mask_number+2)\n \n operation_log = [(\"\",\"\"), (\"Select {} for tracking or inpainting\".format(mask_dropdown),\"Normal\")]\n return select_frame, operation_log\n\n# tracking vos\ndef vos_tracking_video(video_state, interactive_state, mask_dropdown):\n operation_log = [(\"\",\"\"), (\"Track the selected masks, and then you can select the masks for inpainting.\",\"Normal\")]\n model.xmem.clear_memory()\n if interactive_state[\"track_end_number\"]:\n following_frames = video_state[\"origin_images\"][video_state[\"select_frame_number\"]:interactive_state[\"track_end_number\"]]\n else:\n following_frames = video_state[\"origin_images\"][video_state[\"select_frame_number\"]:]\n\n if interactive_state[\"multi_mask\"][\"masks\"]:\n if len(mask_dropdown) == 0:\n mask_dropdown = [\"mask_001\"]\n mask_dropdown.sort()\n template_mask = interactive_state[\"multi_mask\"][\"masks\"][int(mask_dropdown[0].split(\"_\")[1]) - 1] * (int(mask_dropdown[0].split(\"_\")[1]))\n for i in range(1,len(mask_dropdown)):\n mask_number = int(mask_dropdown[i].split(\"_\")[1]) - 1 \n template_mask = np.clip(template_mask+interactive_state[\"multi_mask\"][\"masks\"][mask_number]*(mask_number+1), 0, mask_number+1)\n video_state[\"masks\"][video_state[\"select_frame_number\"]]= template_mask\n else: \n template_mask = video_state[\"masks\"][video_state[\"select_frame_number\"]]\n fps = video_state[\"fps\"]\n\n # operation error\n if len(np.unique(template_mask))==1:\n template_mask[0][0]=1\n operation_log = [(\"Error! Please add at least one mask to track by clicking the left image.\",\"Error\"), (\"\",\"\")]\n # return video_output, video_state, interactive_state, operation_error\n masks, logits, painted_images = model.generator(images=following_frames, template_mask=template_mask)\n # clear GPU memory\n model.xmem.clear_memory()\n\n if interactive_state[\"track_end_number\"]: \n video_state[\"masks\"][video_state[\"select_frame_number\"]:interactive_state[\"track_end_number\"]] = masks\n video_state[\"logits\"][video_state[\"select_frame_number\"]:interactive_state[\"track_end_number\"]] = logits\n video_state[\"painted_images\"][video_state[\"select_frame_number\"]:interactive_state[\"track_end_number\"]] = painted_images\n else:\n video_state[\"masks\"][video_state[\"select_frame_number\"]:] = masks\n video_state[\"logits\"][video_state[\"select_frame_number\"]:] = logits\n video_state[\"painted_images\"][video_state[\"select_frame_number\"]:] = painted_images\n\n video_output = generate_video_from_frames(video_state[\"painted_images\"], output_path=\"./result/track/{}\".format(video_state[\"video_name\"]), fps=fps) # import video_input to name the output video\n interactive_state[\"inference_times\"] += 1\n \n print(\"For generating this tracking result, inference times: {}, click times: {}, positive: {}, negative: {}\".format(interactive_state[\"inference_times\"], \n interactive_state[\"positive_click_times\"]+interactive_state[\"negative_click_times\"],\n interactive_state[\"positive_click_times\"],\n interactive_state[\"negative_click_times\"]))\n\n #### shanggao code for mask save\n if interactive_state[\"mask_save\"]:\n if not os.path.exists('./result/mask/{}'.format(video_state[\"video_name\"].split('.')[0])):\n os.makedirs('./result/mask/{}'.format(video_state[\"video_name\"].split('.')[0]))\n i = 0\n print(\"save mask\")\n for mask in video_state[\"masks\"]:\n np.save(os.path.join('./result/mask/{}'.format(video_state[\"video_name\"].split('.')[0]), '{:05d}.npy'.format(i)), mask)\n i+=1\n # save_mask(video_state[\"masks\"], video_state[\"video_name\"])\n #### shanggao code for mask save\n return video_output, video_state, interactive_state, operation_log\n\n# extracting masks from mask_dropdown\n# def extract_sole_mask(video_state, mask_dropdown):\n# combined_masks = \n# unique_masks = np.unique(combined_masks)\n# return 0 \n\n# inpaint \ndef inpaint_video(video_state, interactive_state, mask_dropdown):\n operation_log = [(\"\",\"\"), (\"Removed the selected masks.\",\"Normal\")]\n\n frames = np.asarray(video_state[\"origin_images\"])\n fps = video_state[\"fps\"]\n inpaint_masks = np.asarray(video_state[\"masks\"])\n if len(mask_dropdown) == 0:\n mask_dropdown = [\"mask_001\"]\n mask_dropdown.sort()\n # convert mask_dropdown to mask numbers\n inpaint_mask_numbers = [int(mask_dropdown[i].split(\"_\")[1]) for i in range(len(mask_dropdown))]\n # interate through all masks and remove the masks that are not in mask_dropdown\n unique_masks = np.unique(inpaint_masks)\n num_masks = len(unique_masks) - 1\n for i in range(1, num_masks + 1):\n if i in inpaint_mask_numbers:\n continue\n inpaint_masks[inpaint_masks==i] = 0\n # inpaint for videos\n\n try:\n inpainted_frames = model.baseinpainter.inpaint(frames, inpaint_masks, ratio=interactive_state[\"resize_ratio\"]) # numpy array, T, H, W, 3\n except:\n operation_log = [(\"Error! You are trying to inpaint without masks input. Please track the selected mask first, and then press inpaint. If VRAM exceeded, please use the resize ratio to scaling down the image size.\",\"Error\"), (\"\",\"\")]\n inpainted_frames = video_state[\"origin_images\"]\n video_output = generate_video_from_frames(inpainted_frames, output_path=\"./result/inpaint/{}\".format(video_state[\"video_name\"]), fps=fps) # import video_input to name the output video\n\n return video_output, operation_log\n\n\n# generate video after vos inference\ndef generate_video_from_frames(frames, output_path, fps=30):\n \"\"\"\n Generates a video from a list of frames.\n \n Args:\n frames (list of numpy arrays): The frames to include in the video.\n output_path (str): The path to save the generated video.\n fps (int, optional): The frame rate of the output video. Defaults to 30.\n \"\"\"\n # height, width, layers = frames[0].shape\n # fourcc = cv2.VideoWriter_fourcc(*\"mp4v\")\n # video = cv2.VideoWriter(output_path, fourcc, fps, (width, height))\n # print(output_path)\n # for frame in frames:\n # video.write(frame)\n \n # video.release()\n frames = torch.from_numpy(np.asarray(frames))\n if not os.path.exists(os.path.dirname(output_path)):\n os.makedirs(os.path.dirname(output_path))\n torchvision.io.write_video(output_path, frames, fps=fps, video_codec=\"libx264\")\n return output_path\n\n\n# args, defined in track_anything.py\nargs = parse_augment()\n\n# check and download checkpoints if needed\nSAM_checkpoint_dict = {\n 'vit_h': \"sam_vit_h_4b8939.pth\",\n 'vit_l': \"sam_vit_l_0b3195.pth\", \n \"vit_b\": \"sam_vit_b_01ec64.pth\"\n}\nSAM_checkpoint_url_dict = {\n 'vit_h': \"https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth\",\n 'vit_l': \"https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth\",\n 'vit_b': \"https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth\"\n}\nsam_checkpoint = SAM_checkpoint_dict[args.sam_model_type] \nsam_checkpoint_url = SAM_checkpoint_url_dict[args.sam_model_type] \nxmem_checkpoint = \"XMem-s012.pth\"\nxmem_checkpoint_url = \"https://github.com/hkchengrex/XMem/releases/download/v1.0/XMem-s012.pth\"\ne2fgvi_checkpoint = \"E2FGVI-HQ-CVPR22.pth\"\ne2fgvi_checkpoint_id = \"10wGdKSUOie0XmCr8SQ2A2FeDe-mfn5w3\"\n\n\nfolder =\"./checkpoints\"\nSAM_checkpoint = download_checkpoint(sam_checkpoint_url, folder, sam_checkpoint)\nxmem_checkpoint = download_checkpoint(xmem_checkpoint_url, folder, xmem_checkpoint)\ne2fgvi_checkpoint = download_checkpoint_from_google_drive(e2fgvi_checkpoint_id, folder, e2fgvi_checkpoint)\nargs.port = 12212\nargs.device = \"cuda:3\"\n# args.mask_save = True\n\n# initialize sam, xmem, e2fgvi models\nmodel = TrackingAnything(SAM_checkpoint, xmem_checkpoint, e2fgvi_checkpoint,args)\n\n\ntitle = \"\"\"
Gradio demo for Track Anything, a flexible and interactive tool for video object tracking, segmentation, and inpainting. I To use it, simply upload your video, or click one of the examples to load them. Code: https://github.com/gaomingqi/Track-Anything