Spaces:
Running
Running
Updated the 'sam_utils.py' and 'app.py' modules to implement automated mask generation, result highlighting and mark generation functionalities.
Browse filesFiles changed (3)
- Dockerfile+1-1
- app.py+69-24
- sam_utils.py+10-1
30 unmodified lines3132333435363730 unmodified linesRUN pip install torch==2.0.1+cu117 torchvision==0.15.2+cu117 -f https://download.pytorch.org/whl/torch_stable.html# Install dependenciesRUN pip install --no-cache-dir gradio==3.50.2 opencv-python supervision==0.17.0rc3 \pillow requests# Install SAM and Detectron230 unmodified lines3132333435363730 unmodified linesRUN pip install torch==2.0.1+cu117 torchvision==0.15.2+cu117 -f https://download.pytorch.org/whl/torch_stable.html# Install dependenciesRUN pip install --no-cache-dir gradio==3.50.2 opencv-python supervision==0.17.0rc4 \pillow requests# Install SAM and Detectron2
123456789101112131415162 unmodified lines1920212223249 unmodified lines343536373839404 unmodified lines454647484950514 unmodified lines5657585960616263644 unmodified lines697071727374757677787980818283848586878889909114 unmodified lines1061071081091101111122 unmodified lines1151161171181191201211221231241256 unmodified lines132133134135136137138139140141142143144145146147148149150151152153import osfrom typing import List, Dict, Tuple, Anyimport cv2import gradio as grimport numpy as npimport supervision as svimport torchfrom segment_anything import sam_model_registry, SamAutomaticMaskGeneratorfrom gpt4v import prompt_imagefrom utils import postprocess_masks, Visualizerfrom sam_utils import sam_interactive_inferenceHOME = os.getenv("HOME")DEVICE = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')2 unmodified lines# SAM_CHECKPOINT = "weights/sam_vit_h_4b8939.pth"SAM_MODEL_TYPE = "vit_h"MARKDOWN = """[](https://arxiv.org/pdf/2310.11441.pdf)9 unmodified lines- [ ] Support for alphabetic labels- [ ] Support for Semantic-SAM (multi-level)- [ ] Support for result highlighting- [ ] Support for mask filtering based on granularity"""4 unmodified linesimage_and_mask: Dict[str, np.ndarray],annotation_mode: List[str],mask_alpha: float) -> Tuple[Tuple[np.ndarray, List[Any]], sv.Detections]:image = image_and_mask['image']mask = cv2.cvtColor(image_and_mask['mask'], cv2.COLOR_RGB2GRAY)is_interactive = not np.all(mask == 0)4 unmodified linesmask=mask,model=SAM)else:mask_generator = SamAutomaticMaskGenerator(SAM)result = mask_generator.generate(image=image)detections = sv.Detections.from_sam(result)detections = postprocess_masks(detections=detections)bgr_image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)4 unmodified lineswith_mask="Mask" in annotation_mode,with_polygon="Polygon" in annotation_mode,with_label="Mark" in annotation_mode)return (cv2.cvtColor(annotated_image, cv2.COLOR_BGR2RGB), []), detectionsdef prompt(message, history, image: np.ndarray, api_key: str) -> str:if api_key == "":return "⚠️ Please set your OpenAI API key first"if image is None:return "⚠️ Please generate SoM visual prompt first"return prompt_image(api_key=api_key,image=cv2.cvtColor(image, cv2.COLOR_BGR2RGB),prompt=message)def on_image_input_clear():return None, Noneimage_input = gr.Image(14 unmodified linesvalue=0.05,label="Mask Alpha")image_output = gr.AnnotatedImage(label="SoM Visual Prompt")openai_api_key = gr.Textbox(show_label=False,placeholder="Before you start chatting, set your OpenAI API key here",2 unmodified lineschatbot = gr.Chatbot(label="GPT-4V + SoM",height=256)run_button = gr.Button("Run")with gr.Blocks() as demo:gr.Markdown(MARKDOWN)detections_state = gr.State()with gr.Row():with gr.Column():image_input.render()6 unmodified linesslider_mask_alpha.render()with gr.Column():image_output.render()run_button.render()with gr.Row():openai_api_key.render()with gr.Row():gr.ChatInterface(chatbot=chatbot,fn=prompt,additional_inputs=[image_output, openai_api_key])run_button.click(fn=inference,inputs=[image_input, checkbox_annotation_mode, slider_mask_alpha],outputs=[image_output, detections_state])image_input.clear(fn=on_image_input_clear,outputs=[image_output, detections_state])demo.queue().launch(debug=False, show_error=True)123456789101112131415162 unmodified lines1920212223242526279 unmodified lines3738394041424 unmodified lines474849505152534 unmodified lines585960616263646566674 unmodified lines7273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412514 unmodified lines1401411421431441451461471481491501512 unmodified lines1541551561571581591601611621631641656 unmodified lines172173174175176177178179180181182183184185186187188189190191192193194195196197198import osfrom typing import List, Dict, Tuple, Any, Optionalimport cv2import gradio as grimport numpy as npimport supervision as svimport torchfrom segment_anything import sam_model_registryfrom gpt4v import prompt_imagefrom utils import postprocess_masks, Visualizer, extract_numbers_in_bracketsfrom sam_utils import sam_interactive_inference, sam_inferenceHOME = os.getenv("HOME")DEVICE = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')2 unmodified lines# SAM_CHECKPOINT = "weights/sam_vit_h_4b8939.pth"SAM_MODEL_TYPE = "vit_h"ANNOTATED_IMAGE_KEY = "annotated_image"DETECTIONS_KEY = "detections"MARKDOWN = """[](https://arxiv.org/pdf/2310.11441.pdf)9 unmodified lines- [ ] Support for alphabetic labels- [ ] Support for Semantic-SAM (multi-level)- [ ] Support for mask filtering based on granularity"""4 unmodified linesimage_and_mask: Dict[str, np.ndarray],annotation_mode: List[str],mask_alpha: float) -> Tuple[Tuple[np.ndarray, List[Tuple[np.ndarray, str]]], Dict[str, Any]]:image = image_and_mask['image']mask = cv2.cvtColor(image_and_mask['mask'], cv2.COLOR_RGB2GRAY)is_interactive = not np.all(mask == 0)4 unmodified linesmask=mask,model=SAM)else:detections = sam_inference(image=image,model=SAM)detections = postprocess_masks(detections=detections)bgr_image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)4 unmodified lineswith_mask="Mask" in annotation_mode,with_polygon="Polygon" in annotation_mode,with_label="Mark" in annotation_mode)annotated_image = cv2.cvtColor(annotated_image, cv2.COLOR_BGR2RGB)state = {ANNOTATED_IMAGE_KEY: annotated_image,DETECTIONS_KEY: detections}return (annotated_image, []), statedef prompt(message: str,history: List[List[str]],state: Dict[str, Any],api_key: Optional[str]) -> str:if api_key == "":return "⚠️ Please set your OpenAI API key first"if state is None or ANNOTATED_IMAGE_KEY not in state:return "⚠️ Please generate SoM visual prompt first"return prompt_image(api_key=api_key,image=cv2.cvtColor(state[ANNOTATED_IMAGE_KEY], cv2.COLOR_BGR2RGB),prompt=message)def on_image_input_clear():return None, {}def highlight(state: Dict[str, Any],history: List[List[str]]) -> Optional[Tuple[np.ndarray, List[Tuple[np.ndarray, str]]]]:if DETECTIONS_KEY not in state or ANNOTATED_IMAGE_KEY not in state:return Nonedetections: sv.Detections = state[DETECTIONS_KEY]annotated_image: np.ndarray = state[ANNOTATED_IMAGE_KEY]response = history[-1][-1]detections_ids = extract_numbers_in_brackets(text=response)highlighted_detections = [(detections.mask[detection_id], str(detection_id))for detection_idin detections_ids]return annotated_image, highlighted_detectionsimage_input = gr.Image(14 unmodified linesvalue=0.05,label="Mask Alpha")image_output = gr.AnnotatedImage(label="SoM Visual Prompt",color_map={str(i): sv.ColorPalette.default().by_idx(i).as_hex()for i in range(64)})openai_api_key = gr.Textbox(show_label=False,placeholder="Before you start chatting, set your OpenAI API key here",2 unmodified lineschatbot = gr.Chatbot(label="GPT-4V + SoM",height=256)generate_button = gr.Button("Generate Marks")highlight_button = gr.Button("Highlight Marks")with gr.Blocks() as demo:gr.Markdown(MARKDOWN)inference_state = gr.State({})with gr.Row():with gr.Column():image_input.render()6 unmodified linesslider_mask_alpha.render()with gr.Column():image_output.render()generate_button.render()highlight_button.render()with gr.Row():openai_api_key.render()with gr.Row():gr.ChatInterface(chatbot=chatbot,fn=prompt,additional_inputs=[inference_state, openai_api_key])generate_button.click(fn=inference,inputs=[image_input, checkbox_annotation_mode, slider_mask_alpha],outputs=[image_output, inference_state])image_input.clear(fn=on_image_input_clear,outputs=[image_output, inference_state])highlight_button.click(fn=highlight,inputs=[inference_state, chatbot],outputs=[image_output])demo.queue().launch(debug=False, show_error=True)
1 unmodified line23456781 unmodified lineimport supervision as svfrom segment_anything.modeling.sam import Samfrom segment_anything import SamPredictordef sam_interactive_inference(1 unmodified line2345678910111213141516171 unmodified lineimport supervision as svfrom segment_anything.modeling.sam import Samfrom segment_anything import SamPredictor, SamAutomaticMaskGeneratordef sam_inference(image: np.ndarray,model: Sam) -> sv.Detections:mask_generator = SamAutomaticMaskGenerator(model)result = mask_generator.generate(image=image)return sv.Detections.from_sam(result)def sam_interactive_inference(
Dockerfile+1-1
app.py+69-24
sam_utils.py+10-1