Spaces:
Runtime error
Runtime error
Commit ·
2396fdf
1
Parent(s): 53c5524
Enable smoothing mask and expanding mask
Browse files12345678976 unmodified lines868788899091924 unmodified lines9798991001011023 unmodified lines10610710810911011111233 unmodified lines1461471481491501511521531541551561571581591601611621631641651 unmodified line1671681691701711721731741751 unmodified line17717817918018118218319 unmodified lines20320420520620720820921 unmodified lines2312322332342352362371 unmodified line2392402412422432442451 unmodified line2472482492502512522532 unmodified lines25625725825926026126226326426526626711 unmodified lines279280281282283284import jsonimport osimport subprocessimport sysimport tempfileimport gradio as grimport numpy as npimport supervision as sv76 unmodified lines)def process(image_path, task, prompt, box_threshold, text_threshold, iou_threshold):global tag2text_model, sam_predictor, sam_automask_generator, grounding_dino_model, deviceoutput_gallery = []detections = None4 unmodified linesimage = Image.open(image_path)image_pil = image.convert("RGB")image = np.array(image_pil)# Extract image metadatafilename = os.path.basename(image_path)3 unmodified linesmetadata["image"]["height"] = h# Generate tagsif task in ["auto", "detect"] and prompt == "":tags, caption = generate_tags(tag2text_model, image_pil, "None", device)prompt = " . ".join(tags)print(f"Caption: {caption}")33 unmodified lines# Segmentationif task in ["auto", "segment"]:if detections:masks, scores = segment(sam_predictor, image=image, boxes=detections.xyxy)detections.mask = maskselse:masks = sam_automask_generator.generate(image)sorted_generated_masks = sorted(masks, key=lambda x: x["area"], reverse=True)xywh = np.array([mask["bbox"] for mask in sorted_generated_masks])mask = np.array([mask["segmentation"] for mask in sorted_generated_masks])scores = np.array([mask["predicted_iou"] for mask in sorted_generated_masks]1 unmodified linedetections = sv.Detections(xyxy=xywh_to_xyxy(boxes_xywh=xywh), mask=mask)# opacity = 0.4# mask_image, _ = show_anns_sam(masks)# annotated_image = np.uint8(mask_image * opacity + image * (1 - opacity))mask_annotator = sv.MaskAnnotator()mask_image = np.zeros_like(image, dtype=np.uint8)1 unmodified linemask_image, detections=detections, opacity=1)annotated_image = mask_annotator.annotate(image, detections=detections)output_gallery.append(mask_image)output_gallery.append(annotated_image)# ToDo: Extract metadata19 unmodified linesmeta_file = tempfile.NamedTemporaryFile(delete=False, suffix=".json")meta_file_path = meta_file.namewith open(meta_file_path, "w") as fp:json.dump(metadata, fp)return output_gallery, meta_file_path21 unmodified linesvalue=0.3,step=0.05,label="Box threshold",info="Hash size to use for image hashing",)text_threshold = gr.Slider(minimum=0,1 unmodified linevalue=0.25,step=0.05,label="Text threshold",info="Number of history images used to find out duplicate image",)iou_threshold = gr.Slider(minimum=0,1 unmodified linevalue=0.5,step=0.05,label="IOU threshold",info="Minimum similarity threshold (in percent) to consider 2 images to be similar",)run_button = gr.Button(label="Run")2 unmodified lineslabel="Generated images", show_label=False, elem_id="gallery").style(preview=True, grid=2, object_fit="scale-down")meta_file = gr.File(label="Metadata file")with gr.Row(elem_classes=["container"]):gr.Examples([["examples/dog.png", "auto", ""],["examples/eiffel.png", "auto", ""],["examples/eiffel.png", "segment", ""],["examples/girl.png", "auto", "girl . face"],["examples/horse.png", "detect", "horse"],11 unmodified linesbox_threshold,text_threshold,iou_threshold,],outputs=[gallery, meta_file],)1234567891076 unmodified lines878889909192939495969798991001011024 unmodified lines1071081091101111121133 unmodified lines11711811912012112212333 unmodified lines1571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941 unmodified line1961971981992002012021 unmodified line20420520620720820921021121221321421521619 unmodified lines23623723823924024124221 unmodified lines2642652662672682691 unmodified line2712722732742752761 unmodified line2782792802812822832842852862872882892902912922932942952 unmodified lines29829930030130230330430530630730811 unmodified lines320321322323324325326327import functoolsimport jsonimport osimport sysimport tempfileimport cv2import gradio as grimport numpy as npimport supervision as sv76 unmodified lines)def process(image_path,task,prompt,box_threshold,text_threshold,iou_threshold,kernel_size,expand_mask,):global tag2text_model, sam_predictor, sam_automask_generator, grounding_dino_model, deviceoutput_gallery = []detections = None4 unmodified linesimage = Image.open(image_path)image_pil = image.convert("RGB")image = np.array(image_pil)orig_image = image.copy()# Extract image metadatafilename = os.path.basename(image_path)3 unmodified linesmetadata["image"]["height"] = h# Generate tagsif task in ["auto", "detection"] and prompt == "":tags, caption = generate_tags(tag2text_model, image_pil, "None", device)prompt = " . ".join(tags)print(f"Caption: {caption}")33 unmodified lines# Segmentationif task in ["auto", "segment"]:kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * kernel_size + 1, 2 * kernel_size + 1))if detections:masks, scores = segment(sam_predictor, image=orig_image, boxes=detections.xyxy)if expand_mask:masks = [cv2.dilate(mask.astype(np.uint8), kernel) for mask in masks]else:masks = [cv2.morphologyEx(mask.astype(np.uint8), cv2.MORPH_CLOSE, kernel)for mask in masks]detections.mask = masksbinary_mask = functools.reduce(lambda x, y: x + y, detections.mask).astype(np.bool)else:masks = sam_automask_generator.generate(orig_image)sorted_generated_masks = sorted(masks, key=lambda x: x["area"], reverse=True)xywh = np.array([mask["bbox"] for mask in sorted_generated_masks])mask = np.array([cv2.dilate(mask["segmentation"].astype(np.uint8), kernel)for mask in sorted_generated_masks])scores = np.array([mask["predicted_iou"] for mask in sorted_generated_masks]1 unmodified linedetections = sv.Detections(xyxy=xywh_to_xyxy(boxes_xywh=xywh), mask=mask)binary_mask = Nonemask_annotator = sv.MaskAnnotator()mask_image = np.zeros_like(image, dtype=np.uint8)1 unmodified linemask_image, detections=detections, opacity=1)annotated_image = mask_annotator.annotate(image, detections=detections)output_gallery.append(mask_image)if binary_mask is not None:binary_mask_image = binary_mask * 255cutout_image = np.expand_dims(binary_mask, axis=-1) * orig_imageoutput_gallery.append(binary_mask_image)output_gallery.append(cutout_image)output_gallery.append(annotated_image)# ToDo: Extract metadata19 unmodified linesmeta_file = tempfile.NamedTemporaryFile(delete=False, suffix=".json")meta_file_path = meta_file.namewith open(meta_file_path, "w", encoding="utf-8") as fp:json.dump(metadata, fp)return output_gallery, meta_file_path21 unmodified linesvalue=0.3,step=0.05,label="Box threshold",)text_threshold = gr.Slider(minimum=0,1 unmodified linevalue=0.25,step=0.05,label="Text threshold",)iou_threshold = gr.Slider(minimum=0,1 unmodified linevalue=0.5,step=0.05,label="IOU threshold",info="Intersection over Union threshold",)kernel_size = gr.Slider(minimum=1,maximum=5,value=2,step=1,label="Kernel size",info="Use to smooth segment masks",)expand_mask = gr.Checkbox(label="Expand mask",)run_button = gr.Button(label="Run")2 unmodified lineslabel="Generated images", show_label=False, elem_id="gallery").style(preview=True, grid=2, object_fit="scale-down")meta_file = gr.File(label="Metadata file")with gr.Row(elem_classes=["container"]):gr.Examples([["examples/dog.png", "auto", ""],["examples/eiffel.jpg", "auto", "tower . lake . grass . sky"],["examples/eiffel.png", "segment", ""],["examples/girl.png", "auto", "girl . face"],["examples/horse.png", "detect", "horse"],11 unmodified linesbox_threshold,text_threshold,iou_threshold,kernel_size,expand_mask,],outputs=[gallery, meta_file],)
app.py+58-15