
    WpfZA                         d Z ddlZddlmZmZ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 ddlm Z  ej!        Z"ej#        Z$ej%        Z&ej'        Z(ej)        Z*e j+        Z,ej-        Z.ej/        Z0dZ1dZ2dZ3dZ4dZ5dZ6dZ7dZ8dZ9dZ:dZ;dZ<ej=         G d d                      Z>ej=         G d  d!                      Z? G d" d#ej@                  ZAdS )$zMediaPipe image segmenter task.    N)CallableListMappingOptional)packet_creator)packet_getter)image)packet)&tensors_to_segmentation_calculator_pb2)!image_segmenter_graph_options_pb2)segmenter_options_pb2)rect)base_options)	task_info)doc_controls)base_vision_task_api)image_processing_options)vision_task_running_modeconfidence_masksCONFIDENCE_MASKScategory_maskCATEGORY_MASKimage_in	image_outIMAGEnorm_rect_in	NORM_RECTz/mediapipe.tasks.TensorsToSegmentationCalculatorz:mediapipe.tasks.vision.image_segmenter.ImageSegmenterGraphi  c                   h    e Zd ZU dZdZeeej                          e	d<   dZ
eej                 e	d<   dS )ImageSegmenterResultaW  Output result of ImageSegmenter.

  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        m/var/www/html/nettyfy-visnx/env/lib/python3.11/site-packages/mediapipe/tasks/python/vision/image_segmenter.pyr   r   ?   sT           :>HT,"456===04-,,-44444r(   r   c                       e Zd ZU dZeed<   ej        Zeed<   dZ	e
ed<   dZe
ed<   dZeeeej        egdf                  ed	<   ej        d
efd            ZdS )ImageSegmenterOptionsa7  Options for the image segmenter task.

  Attributes:
    base_options: Base options for the image segmenter task.
    running_mode: The running mode of the task. Default to the image mode. Image
      segmenter task has three running modes: 1) The image mode for segmenting
      objects on single image inputs. 2) The video mode for segmenting objects
      on the decoded frames of a video. 3) The live stream mode for segmenting
      objects on a live stream of input data, such as from camera.
    output_confidence_masks: Whether to output confidence masks.
    output_category_mask: Whether to output category mask.
    result_callback: The user-defined result callback for processing live stream
      data. The result callback should only be specified when the running mode
      is set to the live stream mode.
  r   running_modeToutput_confidence_masksFoutput_category_maskNresult_callbackreturnc                     | j                                         }| j        t          j        k    rdnd|_        t                      }t          ||          S )z3Generates an ImageSegmenterOptions protobuf object.FT)r   segmenter_options)r   to_pb2r,   _RunningModer   use_stream_mode_SegmenterOptionsProto _ImageSegmenterGraphOptionsProto)selfbase_options_protosegmenter_options_protos      r)   r3   zImageSegmenterOptions.to_pb2h   sc     *1133"l&888d & 566+'1   r(   )r    r!   r"   r#   _BaseOptionsr&   r4   r   r,   r-   boolr.   r/   r   r   r   r$   r%   intr   do_not_generate_docsr7   r3   r'   r(   r)   r+   r+   N   s            +1,111"&4&&&$$$$  8$l&8#>DE    $
6 
 
 
 %$
 
 
r(   r+   c            	       &    e Zd ZdZd fdZddZededd fd            Zede	dd fd	            Z
	 dd
ej        dee         defdZ	 dd
ej        dedee         defdZ	 dd
ej        dedee         ddfdZedee         fd            Z xZS )ImageSegmentera  Class that performs image segmentation on images.

  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_category_mask` is True, uint8 Image, Image vector of size 1.
    - if `output_confidence_masks` is True, 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
  r0   Nc                     t          t          |                               |||           |                                  dS )z(Initializes the `ImageSegmenter` object.N)superr@   __init___populate_labels)r8   graph_configr,   packet_callback	__class__s       r)   rC   zImageSegmenter.__init__   sF    	.$((lO   	r(   c                    g | _         | j                                        }d}|j        D ]}t          |j        v r|rt          dt           d          d}|j        j        t          j
                 }|j        rjt          t          |j                            D ]H}||j        vrt          d| d          | j                             |j        |         j                   IdS )zPopulate the labelmap in TensorsToSegmentationCalculator to labels field.

    Raises:
      ValueError if there is an error during finding
      TensorsToSegmentationCalculator.
    FzThe graph has more than one .Tz"The labelmap has no expected key: N)_labels_runnerget_graph_confignode(_TENSORS_TO_SEGMENTATION_CALCULATOR_NAMEname
ValueErroroptions
Extensions+TensorsToSegmentationCalculatorOptionsProtoextlabel_itemsrangelenappend)r8   rE   found_tensors_to_segmentationrM   rQ   is         r)   rD   zImageSegmenter._populate_labels   s    DL<0022L$)!! = =	1TY	>	>( 	=9= = =   )-%,)7;
  	=W01122 = =a+++HAHHHIIIL 3A 6 ;<<<<= =r(   
model_pathc                     t          |          }t          |t          j                  }|                     |          S )a[  Creates an `ImageSegmenter` object from a TensorFlow Lite model and the default `ImageSegmenterOptions`.

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

    Args:
      model_path: Path to the model.

    Returns:
      `ImageSegmenter` object that's created from the model file and the default
      `ImageSegmenterOptions`.

    Raises:
      ValueError: If failed to create `ImageSegmenter` object from the provided
        file such as invalid file path.
      RuntimeError: If other types of error occurred.
    )model_asset_path)r   r,   )r;   r+   r4   r   create_from_options)clsr[   r   rQ   s       r)   create_from_model_pathz%ImageSegmenter.create_from_model_path   sF    &  <<<L#!0B  G ""7+++r(   rQ   c                    dt           t          t          j        f         ffd}d                    t
          t          g          g}j        r4|                    d                    t          t          g                     j        r4|                    d                    t          t          g                     t          t          d                    t
          t           g          d                    t"          t$          g          g|          } | |                    j        t*          j        k              j        j        r|nd          S )a  Creates the `ImageSegmenter` object from image segmenter options.

    Args:
      options: Options for the image segmenter task.

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

    Raises:
      ValueError: If failed to create `ImageSegmenter` object from
        `ImageSegmenterOptions` such as missing the model.
      RuntimeError: If other types of error occurred.
    output_packetsc                    | t                                                    rd S t                      }j        r$t	          j        | t                             |_        j        r$t	          j	        | t                             |_        t	          j	        | t                              }| t                    j        }                    |||j        t          z             d S N)_IMAGE_OUT_STREAM_NAMEis_emptyr   r-   r   get_image_list_CONFIDENCE_MASKS_STREAM_NAMEr   r.   	get_image_CATEGORY_MASK_STREAM_NAMEr   	timestampr/   value_MICRO_SECONDS_PER_MILLISECOND)rb   segmentation_resultr	   rk   rQ   s       r)   packets_callbackz<ImageSegmenter.create_from_options.<locals>.packets_callback   s    	.	/	8	8	:	: 022		( 
/</K890
 0
, 
	% 
,9,C56-
 -
) %n5K&LMMe !78Bi


/;
;    r(   :)
task_graphinput_streamsoutput_streamstask_options)enable_flow_limitingN)r   strr
   Packetjoin
_IMAGE_TAGre   r-   rX   _CONFIDENCE_MASKS_TAGrh   r.   _CATEGORY_MASK_TAGrj   	_TaskInfo_TASK_GRAPH_NAME_IMAGE_IN_STREAM_NAME_NORM_RECT_TAG_NORM_RECT_STREAM_NAMEgenerate_graph_configr,   r4   LIVE_STREAMr/   )r_   rQ   ro   rs   r   s    `   r)   r^   z"ImageSegmenter.create_from_options   sp   $fm1C)D      2 	*4566N & 
(()+HI
J
J   # 
((&(BC
D
D   #HHj"7899HHn&<=>>
 &  I 3''!(!5'"( 	( 	
 	
 	#3=  r(   r	   r   c           	         |                      ||d          }|                     t          t          j        |          t
          t          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.

    Args:
      image: MediaPipe Image.
      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_rect_process_image_datar~   r   create_imager   create_protor3   r   rh   r   rg   r   rj   ri   r   )r8   r	   r   normalized_rectrb   rn   s         r)   segmentzImageSegmenter.segment  s    , 55 %U 6  O --~:5AA ;""$$!
 !
/  N /00$66-:-I
6
7. .* "^33*7*A
3
4+ +' r(   timestamp_msc           	      $   |                      ||d          }|                     t          t          j        |                              |t          z            t          t          j        |	                                                              |t          z            i          }t                      }t          |v r$t          j        |t                             |_        t          |v r$t          j        |t                             |_        |S )a  Performs segmentation on the provided video frames.

    Only use this method when the ImageSegmenter is created with the video
    running mode. It's required to provide the video frame's timestamp (in
    milliseconds) along with the video frame. The input timestamps should be
    monotonically increasing for adjacent calls of this method.

    Args:
      image: MediaPipe Image.
      timestamp_ms: The timestamp of the input video frame in milliseconds.
      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.
    Fr   )r   _process_video_datar~   r   r   atrm   r   r   r3   r   rh   r   rg   r   rj   ri   r   )r8   r	   r   r   r   rb   rn   s          r)   segment_for_videoz ImageSegmenter.segment_for_videoB  s   : 55 %U 6  O --~:5AADD99 
  
 	 ;""$$!
 !

"\::
;
;/  N /00$66-:-I
6
7. .* "^33*7*A
3
4+ +' r(   c           	      T   |                      ||d          }|                     t          t          j        |                              |t          z            t          t          j        |	                                                              |t          z            i           dS )a  Sends live image data (an Image with a unique timestamp) to perform image segmentation.

    Only use this method when the ImageSegmenter is created with the live stream
    running mode. The input timestamps should be monotonically increasing for
    adjacent calls of this method. This method will return immediately after the
    input image is accepted. The results will be available via the
    `result_callback` provided in the `ImageSegmenterOptions`. The
    `segment_async` method is designed to process live stream data such as
    camera input. To lower the overall latency, image segmenter may drop the
    input images if needed. In other words, it's not guaranteed to have output
    per input image.

    The `result_callback` prvoides:
      - A segmentation result object that contains a list of segmentation masks
        as images.
      - The input image that the image segmenter runs on.
      - The input timestamp in milliseconds.

    Args:
      image: MediaPipe Image.
      timestamp_ms: The timestamp of the input image in milliseconds.
      image_processing_options: Options for image processing.

    Raises:
      ValueError: If the current input timestamp is smaller than what the image
        segmenter has already processed.
    Fr   N)
r   _send_live_stream_datar~   r   r   r   rm   r   r   r3   )r8   r	   r   r   r   s        r)   segment_asynczImageSegmenter.segment_asyncx  s    B 55 %U 6  O 	~:5AADD99 
  
 	 ;""$$!
 !

"\::
;
;!     r(   c                     | j         S )a|  Get the category label list the ImageSegmenter can recognize.

    For CATEGORY_MASK type, the index in the category mask corresponds to the
    category in the label list.
    For CONFIDENCE_MASK type, the output mask list at index corresponds to the
    category in the label list.

    If there is no label map provided in the model file, empty label list is
    returned.
    )rJ   )r8   s    r)   labelszImageSegmenter.labels  s     <r(   )r0   Nrd   )r    r!   r"   r#   rC   rD   classmethodrv   r`   r+   r^   r$   r%   r   _ImageProcessingOptionsr   r   r=   r   r   propertyr   r   __classcell__)rG   s   @r)   r@   r@   v   s        0     = = = =8 ,c ,6F , , , ;,0 G)GG G G ;GX EI+ ++ !))@ A+ 	+ + + +b EI	4 44 4 !))@ A	4
 4 4 4 4t EI	+ ++ + !))@ A	+
 + + + +Z d3i    8    r(   r@   )Br#   dataclassestypingr   r   r   r   mediapipe.pythonr   r   $mediapipe.python._framework_bindingsr	   r$   r
   5mediapipe.tasks.cc.vision.image_segmenter.calculatorsr   /mediapipe.tasks.cc.vision.image_segmenter.protor   r   ,mediapipe.tasks.python.components.containersr   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   NormalizedRect_NormalizedRectBaseOptionsr;   SegmenterOptionsr6   ImageSegmenterGraphOptionsr7   &TensorsToSegmentationCalculatorOptionsrS   VisionTaskRunningModer4   ImageProcessingOptionsr   TaskInfor|   rh   rz   rj   r{   r~   re   ry   r   r   rN   r}   rm   	dataclassr   r+   BaseVisionTaskApir@   r'   r(   r)   <module>r      s   & %     4 4 4 4 4 4 4 4 4 4 4 4 + + + + + + * * * * * * F F F F F F 7 7 7 7 7 7 h h h h h h ] ] ] ] ] ] Q Q Q Q Q Q = = = = = = K K K K K K E E E E E E J J J J J J C C C C C C j j j j j j G G G G G G%"..? %@ ! +Q , (=9P %	 2 * , $ " $ 
' 5 ) P !%  5 5 5 5 5 5 5 5 $ $ $ $ $ $ $ $N{ { { { {); { { { { {r(   