Files
Track-Anything/app.py

355 lines
12 KiB
Python
Raw Normal View History

2023-04-13 13:40:10 +00:00
import gradio as gr
from demo import automask_image_app, automask_video_app, sahi_autoseg_app
import argparse
import cv2
import time
2023-04-13 18:00:48 +00:00
from PIL import Image
import numpy as np
import os
import sys
sys.path.append(sys.path[0]+"/tracker")
sys.path.append(sys.path[0]+"/tracker/model")
from track_anything import TrackingAnything
from track_anything import parse_augment
import requests
2023-04-14 08:24:57 +00:00
import json
2023-04-14 13:26:26 +00:00
import torchvision
import torch
import concurrent.futures
import queue
2023-04-13 19:04:57 +00:00
def download_checkpoint(url, folder, filename):
os.makedirs(folder, exist_ok=True)
filepath = os.path.join(folder, filename)
2023-04-13 19:04:57 +00:00
if not os.path.exists(filepath):
print("download checkpoints ......")
response = requests.get(url, stream=True)
with open(filepath, "wb") as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
2023-04-14 04:02:02 +08:00
print("download successfully!")
return filepath
# convert points input to prompt state
2023-04-14 08:24:57 +00:00
def get_prompt(click_state, click_input):
inputs = json.loads(click_input)
points = click_state[0]
labels = click_state[1]
for input in inputs:
points.append(input[:2])
labels.append(input[2])
click_state[0] = points
2023-04-14 08:24:57 +00:00
click_state[1] = labels
prompt = {
"prompt_type":["click"],
"input_point":click_state[0],
"input_label":click_state[1],
"multimask_output":"True",
}
return prompt
2023-04-14 04:10:42 +00:00
def get_frames_from_video(video_input, video_state):
2023-04-13 22:27:42 +08:00
"""
2023-04-13 18:00:48 +00:00
Args:
2023-04-13 22:27:42 +08:00
video_path:str
timestamp:float64
2023-04-13 18:00:48 +00:00
Return
2023-04-14 04:46:20 +08:00
[[0:nearest_frame], [nearest_frame:], nearest_frame]
2023-04-13 22:27:42 +08:00
"""
2023-04-13 18:00:48 +00:00
video_path = video_input
2023-04-13 22:27:42 +08:00
frames = []
try:
cap = cv2.VideoCapture(video_path)
fps = cap.get(cv2.CAP_PROP_FPS)
while cap.isOpened():
ret, frame = cap.read()
if ret == True:
2023-04-17 09:09:56 +00:00
frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
2023-04-13 22:27:42 +08:00
else:
break
except (OSError, TypeError, ValueError, KeyError, SyntaxError) as e:
print("read_frame_source:{} error. {}\n".format(video_path, str(e)))
2023-04-13 18:00:48 +00:00
# initialize video_state
video_state = {
"video_name": os.path.split(video_path)[-1],
"origin_images": frames,
"painted_images": frames.copy(),
"masks": [None]*len(frames),
"logits": [None]*len(frames),
"select_frame_number": 0,
"fps": 30
}
return video_state, gr.update(visible=True, maximum=len(frames), value=1)
def select_template(image_selection_slider, video_state):
# images = video_state[1]
image_selection_slider -= 1
video_state["select_frame_number"] = image_selection_slider
2023-04-14 08:50:49 +00:00
# once select a new template frame, set the image in sam
model.samcontroler.sam_controler.reset_image()
model.samcontroler.sam_controler.set_image(video_state["origin_images"][image_selection_slider])
return video_state["painted_images"][image_selection_slider], video_state
2023-04-14 13:26:26 +00:00
2023-04-15 18:26:22 +00:00
def generate_video_from_frames(frames, output_path, fps=30):
2023-04-14 13:26:26 +00:00
"""
Generates a video from a list of frames.
Args:
frames (list of numpy arrays): The frames to include in the video.
output_path (str): The path to save the generated video.
fps (int, optional): The frame rate of the output video. Defaults to 30.
"""
frames = torch.from_numpy(np.asarray(frames))
if not os.path.exists(os.path.dirname(output_path)):
os.makedirs(os.path.dirname(output_path))
2023-04-14 13:26:26 +00:00
torchvision.io.write_video(output_path, frames, fps=fps, video_codec="libx264")
return output_path
2023-04-13 22:27:42 +08:00
def sam_refine(video_state, point_prompt, click_state, evt:gr.SelectData):
2023-04-14 08:24:57 +00:00
"""
Args:
template_frame: PIL.Image
point_prompt: flag for positive or negative button click
click_state: [[points], [labels]]
"""
if point_prompt == "Positive":
coordinate = "[[{},{},1]]".format(evt.index[0], evt.index[1])
else:
coordinate = "[[{},{},0]]".format(evt.index[0], evt.index[1])
# prompt for sam model
prompt = get_prompt(click_state=click_state, click_input=coordinate)
2023-04-14 08:50:49 +00:00
mask, logit, painted_image = model.first_frame_click(
image=video_state["origin_images"][video_state["select_frame_number"]],
2023-04-14 11:27:13 +00:00
points=np.array(prompt["input_point"]),
2023-04-14 08:24:57 +00:00
labels=np.array(prompt["input_label"]),
2023-04-14 11:27:13 +00:00
multimask=prompt["multimask_output"],
2023-04-14 08:24:57 +00:00
)
video_state["masks"][video_state["select_frame_number"]] = mask
video_state["logits"][video_state["select_frame_number"]] = logit
video_state["painted_images"][video_state["select_frame_number"]] = painted_image
2023-04-14 13:26:26 +00:00
return painted_image, video_state
2023-04-16 08:53:28 +00:00
def interactive_correction(video_state, point_prompt, click_state, select_correction_frame, evt: gr.SelectData):
"""
Args:
template_frame: PIL.Image
point_prompt: flag for positive or negative button click
click_state: [[points], [labels]]
"""
refine_image = video_state[1][select_correction_frame]
if point_prompt == "Positive":
coordinate = "[[{},{},1]]".format(evt.index[0], evt.index[1])
else:
coordinate = "[[{},{},0]]".format(evt.index[0], evt.index[1])
2023-04-16 08:53:28 +00:00
# prompt for sam model
prompt = get_prompt(click_state=click_state, click_input=coordinate)
# model.samcontroler.seg_again(refine_image)
2023-04-16 08:53:28 +00:00
corrected_mask, corrected_logit, corrected_painted_image = model.first_frame_click(
image=refine_image,
points=np.array(prompt["input_point"]),
labels=np.array(prompt["input_label"]),
multimask=prompt["multimask_output"],
)
return corrected_painted_image, [corrected_mask, corrected_logit, corrected_painted_image]
def vos_tracking_video(video_state):
2023-04-16 08:53:28 +00:00
model.xmem.clear_memory()
following_frames = video_state["origin_images"][video_state["select_frame_number"]:]
template_mask = video_state["masks"][video_state["select_frame_number"]]
fps = video_state["fps"]
masks, logits, painted_images = model.generator(images=following_frames, template_mask=template_mask)
video_state["masks"][video_state["select_frame_number"]:] = masks
video_state["logits"][video_state["select_frame_number"]:] = logits
video_state["painted_images"][video_state["select_frame_number"]:] = painted_images
video_output = generate_video_from_frames(video_state["painted_images"], output_path="./result/{}".format(video_state["video_name"]), fps=fps) # import video_input to name the output video
return video_output, video_state
2023-04-16 08:53:28 +00:00
# check and download checkpoints if needed
SAM_checkpoint = "sam_vit_h_4b8939.pth"
sam_checkpoint_url = "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth"
xmem_checkpoint = "XMem-s012.pth"
xmem_checkpoint_url = "https://github.com/hkchengrex/XMem/releases/download/v1.0/XMem-s012.pth"
folder ="./checkpoints"
SAM_checkpoint = download_checkpoint(sam_checkpoint_url, folder, SAM_checkpoint)
xmem_checkpoint = download_checkpoint(xmem_checkpoint_url, folder, xmem_checkpoint)
2023-04-14 11:27:13 +00:00
# args, defined in track_anything.py
args = parse_augment()
args.port = 12212
args.device = "cuda:2"
2023-04-16 08:53:28 +00:00
model = TrackingAnything(SAM_checkpoint, xmem_checkpoint, args)
2023-04-13 13:40:10 +00:00
with gr.Blocks() as iface:
2023-04-14 04:10:42 +00:00
"""
state for
"""
click_state = gr.State([[],[]])
video_state = gr.State(
{
"video_name": "",
"origin_images": None,
"painted_images": None,
"masks": None,
"logits": None,
"select_frame_number": 0,
"fps": 30
}
)
2023-04-14 11:27:13 +00:00
2023-04-13 13:40:10 +00:00
with gr.Row():
2023-04-14 04:10:42 +00:00
# for user video input
2023-04-13 13:40:10 +00:00
with gr.Column(scale=1.0):
2023-04-13 18:00:48 +00:00
video_input = gr.Video().style(height=720)
2023-04-13 13:40:10 +00:00
2023-04-14 04:10:42 +00:00
with gr.Row(scale=1):
# put the template frame under the radio button
with gr.Column(scale=0.5):
# click points settins, negative or positive, mode continuous or single
with gr.Row():
with gr.Row(scale=0.5):
point_prompt = gr.Radio(
choices=["Positive", "Negative"],
value="Positive",
label="Point Prompt",
interactive=True)
click_mode = gr.Radio(
choices=["Continuous", "Single"],
value="Continuous",
label="Clicking Mode",
interactive=True)
with gr.Row(scale=0.5):
clear_button_clike = gr.Button(value="Clear Clicks", interactive=True).style(height=160)
2023-04-13 18:16:04 +00:00
clear_button_image = gr.Button(value="Clear Image", interactive=True)
2023-04-14 04:10:42 +00:00
template_frame = gr.Image(type="pil",interactive=True, elem_id="template_frame").style(height=360)
image_selection_slider = gr.Slider(minimum=1, maximum=100, step=1, value=1, label="Image Selection", invisible=False)
# extract frames
2023-04-14 04:10:42 +00:00
with gr.Column():
extract_frames_button = gr.Button(value="Get video info", interactive=True, variant="primary")
2023-04-14 04:10:42 +00:00
with gr.Column(scale=0.5):
2023-04-14 13:26:26 +00:00
video_output = gr.Video().style(height=360)
2023-04-16 08:53:28 +00:00
tracking_video_predict_button = gr.Button(value="Tracking")
2023-04-13 18:00:48 +00:00
2023-04-13 13:40:10 +00:00
# first step: get the video information
extract_frames_button.click(
2023-04-13 18:00:48 +00:00
fn=get_frames_from_video,
inputs=[
video_input, video_state
2023-04-13 18:00:48 +00:00
],
outputs=[video_state, image_selection_slider],
)
2023-04-13 13:40:10 +00:00
# second step: select images from slider
image_selection_slider.release(fn=select_template,
inputs=[image_selection_slider, video_state],
outputs=[template_frame, video_state], api_name="select_image")
template_frame.select(
fn=sam_refine,
inputs=[video_state, point_prompt, click_state],
outputs=[template_frame, video_state]
)
2023-04-14 13:26:26 +00:00
tracking_video_predict_button.click(
fn=vos_tracking_video,
inputs=[video_state],
outputs=[video_output, video_state]
2023-04-16 08:53:28 +00:00
)
2023-04-16 08:53:28 +00:00
# clear input
2023-04-13 18:16:04 +00:00
video_input.clear(
lambda: (
{
"origin_images": None,
"painted_images": None,
"masks": None,
"logits": None,
"select_frame_number": 0,
"fps": 30
},
[[],[]]
),
2023-04-13 18:16:04 +00:00
[],
[
video_state,
click_state,
],
2023-04-13 18:16:04 +00:00
queue=False,
show_progress=False
)
2023-04-16 08:53:28 +00:00
clear_button_image.click(
lambda: (
{
"origin_images": None,
"painted_images": None,
"masks": None,
"logits": None,
"select_frame_number": 0,
"fps": 30
},
[[],[]]
),
[],
[
video_state,
click_state,
],
queue=False,
show_progress=False
2023-04-16 08:53:28 +00:00
)
clear_button_clike.click(
lambda: ([[],[]]),
[],
[click_state],
queue=False,
show_progress=False
)
2023-04-13 13:40:10 +00:00
iface.queue(concurrency_count=1)
iface.launch(debug=True, enable_queue=True, server_port=args.port, server_name="0.0.0.0")
2023-04-13 13:40:10 +00:00