
    uki(                     l   d Z ddlZddlZddlmZmZ ddlmZ ddlmZ ddl	m
Z ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ej@                  Z!ejD                  Z#ejH                  Z%ejL                  Z'ejP                  Z)ejT                  Z+ejX                  Z-dZ.dZ/dZ0dZ1dZ2dZ3dZ4dZ5dZ6dZ7dZ8dZ9ejt                   G d d             Z;ejt                   G d d              Z<ejt                   G d! d"             Z=d#e=d$e#fd%Z> G d& d'ej~                        Z@y)(z%MediaPipe interactive segmenter task.    N)ListOptional)packet_creator)packet_getter)image)!image_segmenter_graph_options_pb2)segmenter_options_pb2)keypointbase_options)	task_info)doc_controls)base_vision_task_api)image_processing_options)vision_task_running_mode)render_data_pb2confidence_masksCONFIDENCE_MASKScategory_maskCATEGORY_MASKimage_in	image_outroi_inROInorm_rect_in	NORM_RECTIMAGEzFmediapipe.tasks.vision.interactive_segmenter.InteractiveSegmenterGraphc                   h    e Zd ZU dZdZeeej                        e	d<   dZ
eej                     e	d<   y)InteractiveSegmenterResulta]  Output result of InteractiveSegmenter.

  confidence_masks: multiple masks of float image where, for each mask, each
  pixel represents the prediction confidence, usually in the [0, 1] range.

  category_mask: a category mask of uint8 image where each pixel represents the
  class which the pixel in the original image was predicted to belong to.
  Nr   r   )__name__
__module____qualname____doc__r   r   r   image_moduleImage__annotations__r        n/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/mediapipe/tasks/python/vision/interactive_segmenter.pyr   r   <   s9     :>HT,"4"456=04-,,,-4r(   r   c                   b    e Zd ZU dZeed<   dZeed<   dZeed<   e	j                  defd       Zy	)
InteractiveSegmenterOptionszOptions for the interactive segmenter task.

  Attributes:
    base_options: Base options for the interactive segmenter task.
    output_confidence_masks: Whether to output confidence masks.
    output_category_mask: Whether to output category mask.
  r   Toutput_confidence_masksFoutput_category_maskreturnc                 r    | j                   j                         }d|_        t               }t	        ||      S )z8Generates an ImageSegmenterGraphOptions protobuf object.F)r   segmenter_options)r   to_pb2use_stream_mode_SegmenterOptionsProto _ImageSegmenterGraphOptionsProto)selfbase_options_protosegmenter_options_protos      r)   r1   z"InteractiveSegmenterOptions.to_pb2Y   s>     **113).&46+'1 r(   N)r    r!   r"   r#   _BaseOptionsr&   r,   boolr-   r   do_not_generate_docsr4   r1   r'   r(   r)   r+   r+   K   sE     "&4&$$$$6  %r(   r+   c                   n    e Zd ZU dZ G d dej
                        Zeed<   dZe	e
j                     ed<   y)RegionOfInterestz.The Region-Of-Interest (ROI) to interact with.c                       e Zd ZdZdZy)RegionOfInterest.Formatr      N)r    r!   r"   UNSPECIFIEDKEYPOINTr'   r(   r)   Formatr>   i   s    KHr(   rB   formatNr
   )r    r!   r"   r#   enumEnumrB   r&   r
   r   keypoint_moduleNormalizedKeypointr'   r(   r)   r<   r<   e   s1    6tyy  .;?(H_778?r(   r<   roir.   c                    t               }| | j                  t        j                  j                  k(  rt        d      | j                  t        j                  j                  k(  r| j                  |j                  j                         }d|j                  _        |j                  }d|_        | j                  j                  |_        | j                  j                  |_        |S t        d      t        d      )z1Converts region of interest to render data proto.z&RegionOfInterest format not specified.   Tz7Please specify the Region-of-interest for segmentation.zUnrecognized format.)_RenderDataProtorC   r<   rB   r@   
ValueErrorrA   r
   render_annotationsaddcolorrpoint
normalizedxy)rH   result
annotationrQ   s       r)   _convert_roi_to_render_datarW   q   s    &_
zz%,,888?@@	'..77	7		!..224
 
  ,,..,,..
N
OO)**r(   c            	       z    e Zd ZdZededd fd       Zededd fd       Z	 dde	j                  d	ed
ee   defdZy)InteractiveSegmenteraK  Class that performs interactive segmentation on images.

  Users can represent user interaction through `RegionOfInterest`, which gives
  a hint to InteractiveSegmenter to perform segmentation focusing on the given
  region of interest.

  The API expects a TFLite model with mandatory TFLite Model Metadata.

  Input tensor:
    (kTfLiteUInt8/kTfLiteFloat32)
    - image input of size `[batch x height x width x channels]`.
    - batch inference is not supported (`batch` is required to be 1).
    - RGB and greyscale inputs are supported (`channels` is required to be
      1 or 3).
    - if type is kTfLiteFloat32, NormalizationOptions are required to be
      attached to the metadata for input normalization.
  Output tensors:
    (kTfLiteUInt8/kTfLiteFloat32)
    - list of segmented masks.
    - if `output_type` is CATEGORY_MASK, uint8 Image, Image vector of size 1.
    - if `output_type` is CONFIDENCE_MASK, float32 Image list of size
      `channels`.
    - batch is always 1

  An example of such model can be found at:
  https://tfhub.dev/tensorflow/lite-model/deeplabv3/1/metadata/2
  
model_pathr.   c                 T    t        |      }t        |      }| j                  |      S )a  Creates an `InteractiveSegmenter` object from a TensorFlow Lite model and the default `InteractiveSegmenterOptions`.

    Note that the created `InteractiveSegmenter` instance is in image mode, for
    performing image segmentation on single image inputs.

    Args:
      model_path: Path to the model.

    Returns:
      `InteractiveSegmenter` object that's created from the model file and the
      default `InteractiveSegmenterOptions`.

    Raises:
      ValueError: If failed to create `InteractiveSegmenter` object from the
        provided file such as invalid file path.
      RuntimeError: If other types of error occurred.
    )model_asset_pathr   )r8   r+   create_from_options)clsrZ   r   optionss       r)   create_from_model_pathz+InteractiveSegmenter.create_from_model_path   s)    &  <L)|DG""7++r(   r_   c           	      $   dj                  t        t        g      g}|j                  r*|j	                  dj                  t
        t        g             |j                  r*|j	                  dj                  t        t        g             t        t        dj                  t        t        g      dj                  t        t        g      dj                  t        t         g      g||      } | |j#                  d      t$        j&                  d      S )a  Creates the `InteractiveSegmenter` object from interactive segmenter options.

    Args:
      options: Options for the interactive segmenter task.

    Returns:
      `InteractiveSegmenter` object that's created from `options`.

    Raises:
      ValueError: If failed to create `InteractiveSegmenter` object from
        `InteractiveSegmenterOptions` such as missing the model.
      RuntimeError: If other types of error occurred.
    :)
task_graphinput_streamsoutput_streamstask_optionsF)enable_flow_limitingN)join
_IMAGE_TAG_IMAGE_OUT_STREAM_NAMEr,   append_CONFIDENCE_MASKS_TAG_CONFIDENCE_MASKS_STREAM_NAMEr-   _CATEGORY_MASK_TAG_CATEGORY_MASK_STREAM_NAME	_TaskInfo_TASK_GRAPH_NAME_IMAGE_IN_STREAM_NAME_ROI_TAG_ROI_STREAM_NAME_NORM_RECT_TAG_NORM_RECT_STREAM_NAMEgenerate_graph_config_RunningModer   )r^   r_   re   r   s       r)   r]   z(InteractiveSegmenter.create_from_options   s    & 	*456N &&
(()+HI
J ##
((&(BC
D #HHj"789HHh 012HHn&<=>

 &	I ''U'C r(   Nr   rH   r   c                    | j                  ||d      }t        |      }| j                  t        t	        j
                  |      t        t	        j                  |      t        t	        j                  |j                               i      }t               }t        |v r!t        j                  |t                 |_        t        |v r!t        j                   |t                 |_        |S )a  Performs the actual segmentation task on the provided MediaPipe Image.

    The image can be of any size with format RGB.

    Args:
      image: MediaPipe Image.
      roi: Optional user-specified region of interest for segmentation.
      image_processing_options: Options for image processing.

    Returns:
      If the output_type is CATEGORY_MASK, the returned vector of images is
      per-category segmented image mask.
      If the output_type is CONFIDENCE_MASK, the returned vector of images
      contains only one confidence image mask. A segmentation result object that
      contains a list of segmentation masks as images.

    Raises:
      ValueError: If any of the input arguments is invalid.
      RuntimeError: If image segmentation failed to run.
    F)roi_allowed)convert_to_normalized_rectrW   _process_image_datarr   r   create_imagert   create_protorv   r1   r   rm   r   get_image_listr   ro   	get_imager   )r5   r   rH   r   normalized_rectrender_data_protooutput_packetssegmentation_results           r)   segmentzInteractiveSegmenter.segment   s    4 55 %U 6 O 4C8--~::5A.556GH ; ;""$!
/ N 56$6-:-I-I
6
7.* "^3*7*A*A
3
4+' r(   )N)r    r!   r"   r#   classmethodstrr`   r+   r]   r$   r%   r<   r   _ImageProcessingOptionsr   r   r'   r(   r)   rY   rY      s    8 ,c ,6L , ,, -/-- -f EI	11 1 !))@ A	1
 "1r(   rY   )Ar#   dataclassesrD   typingr   r   mediapipe.pythonr   r   $mediapipe.python._framework_bindingsr   r$   /mediapipe.tasks.cc.vision.image_segmenter.protor   r	   ,mediapipe.tasks.python.components.containersr
   rF   mediapipe.tasks.python.corer   base_options_moduler   task_info_module1mediapipe.tasks.python.core.optional_dependenciesr   "mediapipe.tasks.python.vision.corer   r   image_processing_options_moduler   mediapipe.utilr   BaseOptionsr8   
RenderDatarK   SegmenterOptionsr3   ImageSegmenterGraphOptionsr4   VisionTaskRunningModerx   ImageProcessingOptionsr   TaskInforp   rm   rl   ro   rn   rr   rj   rt   rs   rv   ru   ri   rq   	dataclassr   r+   r<   rW   BaseVisionTaskApirY   r'   r(   r)   <module>r      s`   ,   ! + * F ] Q T K E J C j G *".."-- .?? %@@ ! (==9PP %%	 2 * , $ " $  ' 
L 
 5 5 5   2 @ @ @+%5 +:J +.U/AA Ur(   