
    0Ph[                        d Z ddlmZ ddlmZmZmZ ddlZddl	m
Z
 ddlmZ ddlmZmZmZ dd	lmZmZ dd
lmZmZmZmZ g dZddlmZ d*dZd Zd+dZddej        dfdZ  edgdej!        ge"gddd          dej        ddd            Z# e eeddd          g eeddd          g eeddd          gdej!        ge"gddd          	 d*dej        e$dd            Z%d+dZ&d,dZ' eej!        ge(e)g eeddd !           eeddd!          dgd"gd#d          ddd$d%            Z* eej!        ge( ee)          gd&d          d'             Z+ G d( d)ee          Z,dS )-z*Utilities to extract features from images.    )product)IntegralNumberRealN)
as_strided)sparse   )BaseEstimatorTransformerMixin_fit_context)check_arraycheck_random_state)HiddenInterval
RealNotIntvalidate_params)PatchExtractorextract_patches_2dgrid_to_graphimg_to_graphreconstruct_from_patches_2d)validate_data   c                 |   t          j        | |z  |z                                | ||f          }t          j        |ddddddf                                         |ddddddf                                         f          }t          j        |ddddf                                         |ddddf                                         f          }t          j        |dd                                         |dd                                         f          }t          j        |||f          }|S )a%  Returns a list of edges for a 3D image.

    Parameters
    ----------
    n_x : int
        The size of the grid in the x direction.
    n_y : int
        The size of the grid in the y direction.
    n_z : integer, default=1
        The size of the grid in the z direction, defaults to 1
    Nr   )nparangereshapevstackravelhstack)n_xn_yn_zvertices
edges_deepedges_right
edges_downedgess           `/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/feature_extraction/image.py_make_edges_3dr+      s-    ysS))113S/BBHHQQQ3B3Y/5577!!!QQQ(9K9Q9Q9S9STUUJ)Xaaa"f-3355x1227L7L7N7NOPPKHSbSM//118ABB<3E3E3G3GHIIJIz;
;<<EL    c           	         |j         \  }}}t          j        || d         ||z  z  | d         ||z  z  |z  | d         ||z  z  |z  f         || d         ||z  z  | d         ||z  z  |z  | d         ||z  z  |z  f         z
            }|S )Nr   r   )shaper   abs)r)   img_r#   r$   gradients         r*   _compute_gradient_3dr3   3   s    )KAsCv!Hs#1Xs#+1Xs#s*,	

 !Hs#1Xs#+1Xs#s*,
		
 H Or,   c                 *   t          j        | j                  }||                                          }t          j        t          j        |d         |          t          j        |d         |                    }|dd|f         }|||         }t          |                                          r|                                }nd}t          j        t          j	        |           t          j        |dz                       }||         }||S ||fS )z'Apply a mask to edges (weighted or not)r   r   N)
r   r   sizer    logical_andisinlenmaxsearchsortedflatnonzero)maskr)   weightsindsind_maskmaxvalorders          r*   _mask_edges_weightsrB   G   s    9TYD

D~bgeAh55rwuQx7N7NOOH!!!X+E(#
5;;== OBN400")FQJ2G2GHHE%LEg~r,   c                    t          | ||          }||t          }n|j        }|qt          j        |          }t          ||          }|/t          |||          \  }}|                                |         }	n|                                }	|	j	        }
n|A|
                    t          d          }t          ||          }t          j        |          }
n| |z  |z  }
t          j        |j        d         |          }t          j        |
|          }	t          j        |
          }t          j        |d         |d         f          }t          j        |d         |d         f          }t#          j        t          j        |||	f          t          j        ||f          t          j        ||f          ff|
|
f|          }|t          j        u r|                                S  ||          S )z5Auxiliary function for img_to_graph and grid_to_graphNF)dtypecopyr   )rD   r   )r+   intrD   r   
atleast_3dr3   rB   squeezer    r5   astypeboolsumonesr.   r   r!   r   
coo_matrixndarraytoarray)r"   r#   r$   r<   r0   	return_asrD   r)   r=   diagn_voxelsdiag_idxi_idxj_idxgraphs                  r*   	_to_graphrW   [   s    3S))E};EEIE
mC  &uc220ugFFNE7;;==&DD99;;D9;;T;66D'e44Evd||HHSy3H'%+a.666wxu---y""HIuQxq*++EIuQxq*++EIw.//Yx())29eX5F+G+GH	
 
8  E BJ}}9Ur,   z
array-likeno_validation)r0   r<   rP   rD   Tprefer_skip_nested_validationr<   rP   rD   c          	      j    t          j        |           } | j        \  }}}t          ||||| ||          S )a  Graph of the pixel-to-pixel gradient connections.

    Edges are weighted with the gradient values.

    Read more in the :ref:`User Guide <image_feature_extraction>`.

    Parameters
    ----------
    img : array-like of shape (height, width) or (height, width, channel)
        2D or 3D image.
    mask : ndarray of shape (height, width) or             (height, width, channel), dtype=bool, default=None
        An optional mask of the image, to consider only part of the
        pixels.
    return_as : np.ndarray or a sparse matrix class,             default=sparse.coo_matrix
        The class to use to build the returned adjacency matrix.
    dtype : dtype, default=None
        The data of the returned sparse matrix. By default it is the
        dtype of img.

    Returns
    -------
    graph : ndarray or a sparse matrix class
        The computed adjacency matrix.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.feature_extraction.image import img_to_graph
    >>> img = np.array([[0, 0], [0, 1]])
    >>> img_to_graph(img, return_as=np.ndarray)
    array([[0, 0, 0, 0],
           [0, 0, 0, 1],
           [0, 0, 0, 1],
           [0, 1, 1, 1]])
    )r   rG   r.   rW   )r0   r<   rP   rD   r"   r#   r$   s          r*   r   r      s;    ^ -

CIMCcS#sD#y%@@@r,   left)r]   rightclosedr"   r#   r$   r<   rP   rD   c                ,    t          | |||||          S )a  Graph of the pixel-to-pixel connections.

    Edges exist if 2 voxels are connected.

    Parameters
    ----------
    n_x : int
        Dimension in x axis.
    n_y : int
        Dimension in y axis.
    n_z : int, default=1
        Dimension in z axis.
    mask : ndarray of shape (n_x, n_y, n_z), dtype=bool, default=None
        An optional mask of the image, to consider only part of the
        pixels.
    return_as : np.ndarray or a sparse matrix class,             default=sparse.coo_matrix
        The class to use to build the returned adjacency matrix.
    dtype : dtype, default=int
        The data of the returned sparse matrix. By default it is int.

    Returns
    -------
    graph : np.ndarray or a sparse matrix class
        The computed adjacency matrix.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.feature_extraction.image import grid_to_graph
    >>> shape_img = (4, 4, 1)
    >>> mask = np.zeros(shape=shape_img, dtype=bool)
    >>> mask[[1, 2], [1, 2], :] = True
    >>> graph = grid_to_graph(*shape_img, mask=mask)
    >>> print(graph)
    <COOrdinate sparse matrix of dtype 'int64'
      with 2 stored elements and shape (2, 2)>
      Coords	Values
      (0, 0)    1
      (1, 1)    1
    r[   )rW   r`   s         r*   r   r      s     n S#s%PPPPr,   c                 :   | |z
  dz   }||z
  dz   }||z  }|rt          |t                    r||k     r|S t          |t                    r||k    r|S t          |t                    r"d|cxk     rdk     rn nt          ||z            S t	          d|z            |S )ae  Compute the number of patches that will be extracted in an image.

    Read more in the :ref:`User Guide <image_feature_extraction>`.

    Parameters
    ----------
    i_h : int
        The image height
    i_w : int
        The image with
    p_h : int
        The height of a patch
    p_w : int
        The width of a patch
    max_patches : int or float, default=None
        The maximum number of patches to extract. If `max_patches` is a float
        between 0 and 1, it is taken to be a proportion of the total number
        of patches. If `max_patches` is None, all possible patches are extracted.
    r   r   z!Invalid value for max_patches: %r)
isinstancer   r   rF   
ValueError)i_hi_wp_hp_wmax_patchesn_hn_wall_patchess           r*   _compute_n_patchesrm      s    ( )a-C
)a-C)K 
kH.. 	P;3L3Lh00 	P[K5O5Od,, 	P[1D1D1D1D11D1D1D1D1D{[0111@;NOOOr,      c                 n   | j         }t          |t                    rt          |g|z            }t          |t                    rt          |g|z            }| j        }t          d |D                       }| |         j        }t          j        | j                  t          j        |          z
  t          j        |          z  dz   }t          t          |          t          |          z             }t          t          |          t          |          z             }	t          | ||	          }
|
S )ay  Extracts patches of any n-dimensional array in place using strides.

    Given an n-dimensional array it will return a 2n-dimensional array with
    the first n dimensions indexing patch position and the last n indexing
    the patch content. This operation is immediate (O(1)). A reshape
    performed on the first n dimensions will cause numpy to copy data, leading
    to a list of extracted patches.

    Read more in the :ref:`User Guide <image_feature_extraction>`.

    Parameters
    ----------
    arr : ndarray
        n-dimensional array of which patches are to be extracted

    patch_shape : int or tuple of length arr.ndim.default=8
        Indicates the shape of the patches to be extracted. If an
        integer is given, the shape will be a hypercube of
        sidelength given by its value.

    extraction_step : int or tuple of length arr.ndim, default=1
        Indicates step size at which extraction shall be performed.
        If integer is given, then the step is uniform in all dimensions.


    Returns
    -------
    patches : strided ndarray
        2n-dimensional array indexing patches on first n dimensions and
        containing patches on the last n dimensions. These dimensions
        are fake, but this way no data is copied. A simple reshape invokes
        a copying operation to obtain a list of patches:
        result.reshape([-1] + list(patch_shape))
    c              3   8   K   | ]}t          d d |          V  d S N)slice).0sts     r*   	<genexpr>z#_extract_patches.<locals>.<genexpr>N  s.      CCR5tR((CCCCCCr,   r   )r.   strides)
ndimrc   r   tuplerv   r   arrayr.   listr   )arrpatch_shapeextraction_steparr_ndimpatch_stridesslicesindexing_stridespatch_indices_shaper.   rv   patchess              r*   _extract_patchesr   !  s$   H xH+v&& 6[MH455/6** > 1H <==KMCC?CCCCCF6{* 
#)		rx44	4/9R9RR	
 $*++d;.?.??@@ED)**T--@-@@AAGE7;;;GNr,   neitherr_   random_state)image
patch_sizeri   r   ri   r   c                x   | j         dd         \  }}|\  }}||k    rt          d          ||k    rt          d          t          | d          } |                     ||df          } | j         d         }t	          | |||fd	          }	t          |||||          }
|rUt          |          }|                    ||z
  dz   |

          }|                    ||z
  dz   |

          }|	||df         }n|	}|                    d|||          }|j         d         dk    r|                    |
||f          S |S )a  Reshape a 2D image into a collection of patches.

    The resulting patches are allocated in a dedicated array.

    Read more in the :ref:`User Guide <image_feature_extraction>`.

    Parameters
    ----------
    image : ndarray of shape (image_height, image_width) or         (image_height, image_width, n_channels)
        The original image data. For color images, the last dimension specifies
        the channel: a RGB image would have `n_channels=3`.

    patch_size : tuple of int (patch_height, patch_width)
        The dimensions of one patch.

    max_patches : int or float, default=None
        The maximum number of patches to extract. If `max_patches` is a float
        between 0 and 1, it is taken to be a proportion of the total number
        of patches. If `max_patches` is None it corresponds to the total number
        of patches that can be extracted.

    random_state : int, RandomState instance, default=None
        Determines the random number generator used for random sampling when
        `max_patches` is not None. Use an int to make the randomness
        deterministic.
        See :term:`Glossary <random_state>`.

    Returns
    -------
    patches : array of shape (n_patches, patch_height, patch_width) or         (n_patches, patch_height, patch_width, n_channels)
        The collection of patches extracted from the image, where `n_patches`
        is either `max_patches` or the total number of patches that can be
        extracted.

    Examples
    --------
    >>> from sklearn.datasets import load_sample_image
    >>> from sklearn.feature_extraction import image
    >>> # Use the array data from the first image in this dataset:
    >>> one_image = load_sample_image("china.jpg")
    >>> print('Image shape: {}'.format(one_image.shape))
    Image shape: (427, 640, 3)
    >>> patches = image.extract_patches_2d(one_image, (2, 2))
    >>> print('Patches shape: {}'.format(patches.shape))
    Patches shape: (272214, 2, 2, 3)
    >>> # Here are just two of these patches:
    >>> print(patches[1])
    [[[174 201 231]
      [174 201 231]]
     [[173 200 230]
      [173 200 230]]]
    >>> print(patches[800])
    [[[187 214 243]
      [188 215 244]]
     [[187 214 243]
      [188 215 244]]]
    Nr	   z@Height of the patch should be less than the height of the image.z>Width of the patch should be less than the width of the image.T)allow_ndr   r   )r|   r}   )r5   r   )r.   rd   r   r   r   rm   r   randint)r   r   ri   r   re   rf   rg   rh   n_colorsextracted_patches	n_patchesrngi_sj_sr   s                  r*   r   r   \  s|   R {2A2HCHC
SyyN
 
 	
 SyyL
 
 	
 ---EMM3R.))E{2H(Ch/   #3S#{CCI $ ..kk#)a-ik88kk#)a-ik88#CaK0#oob#sH55G}RA	34555r,   )r   
image_sizec                 &   |dd         \  }}| j         dd         \  }}t          j        |          }||z
  dz   }||z
  dz   }t          | t	          t          |          t          |                              D ]$\  }	\  }
}||
|
|z   |||z   fxx         |	z  cc<   %t          |          D ]`}
t          |          D ]N}||
|fxx         t          t          |
dz   |||
z
            t          |dz   |||z
            z            z  cc<   Oa|S )aQ  Reconstruct the image from all of its patches.

    Patches are assumed to overlap and the image is constructed by filling in
    the patches from left to right, top to bottom, averaging the overlapping
    regions.

    Read more in the :ref:`User Guide <image_feature_extraction>`.

    Parameters
    ----------
    patches : ndarray of shape (n_patches, patch_height, patch_width) or         (n_patches, patch_height, patch_width, n_channels)
        The complete set of patches. If the patches contain colour information,
        channels are indexed along the last dimension: RGB patches would
        have `n_channels=3`.

    image_size : tuple of int (image_height, image_width) or         (image_height, image_width, n_channels)
        The size of the image that will be reconstructed.

    Returns
    -------
    image : ndarray of shape image_size
        The reconstructed image.

    Examples
    --------
    >>> from sklearn.datasets import load_sample_image
    >>> from sklearn.feature_extraction import image
    >>> one_image = load_sample_image("china.jpg")
    >>> print('Image shape: {}'.format(one_image.shape))
    Image shape: (427, 640, 3)
    >>> image_patches = image.extract_patches_2d(image=one_image, patch_size=(10, 10))
    >>> print('Patches shape: {}'.format(image_patches.shape))
    Patches shape: (263758, 10, 10, 3)
    >>> image_reconstructed = image.reconstruct_from_patches_2d(
    ...     patches=image_patches,
    ...     image_size=one_image.shape
    ... )
    >>> print(f"Reconstructed shape: {image_reconstructed.shape}")
    Reconstructed shape: (427, 640, 3)
    Nr	   r      )r.   r   zeroszipr   rangefloatmin)r   r   re   rf   rg   rh   r0   rj   rk   pijs               r*   r   r     sM   ^ "1"~HC}QqS!HC
(:

C
)a-C
)a-C'%**eCjj"A"ABB + +	6AqACKQW$%%%*%%%%3ZZ T Ts 	T 	TA 1IIIs1q5#sQw77#a!eS#PQ':R:RRSSSIIII	T Jr,   c            	            e Zd ZU dZedgd eeddd           eeddd          gdgd	Ze	e
d
<   dddd	dZ ed          dd            Zd Z fdZ xZS )r   a  Extracts patches from a collection of images.

    Read more in the :ref:`User Guide <image_feature_extraction>`.

    .. versionadded:: 0.9

    Parameters
    ----------
    patch_size : tuple of int (patch_height, patch_width), default=None
        The dimensions of one patch. If set to None, the patch size will be
        automatically set to `(img_height // 10, img_width // 10)`, where
        `img_height` and `img_width` are the dimensions of the input images.

    max_patches : int or float, default=None
        The maximum number of patches per image to extract. If `max_patches` is
        a float in (0, 1), it is taken to mean a proportion of the total number
        of patches. If set to None, extract all possible patches.

    random_state : int, RandomState instance, default=None
        Determines the random number generator used for random sampling when
        `max_patches is not None`. Use an int to make the randomness
        deterministic.
        See :term:`Glossary <random_state>`.

    See Also
    --------
    reconstruct_from_patches_2d : Reconstruct image from all of its patches.

    Notes
    -----
    This estimator is stateless and does not need to be fitted. However, we
    recommend to call :meth:`fit_transform` instead of :meth:`transform`, as
    parameter validation is only performed in :meth:`fit`.

    Examples
    --------
    >>> from sklearn.datasets import load_sample_images
    >>> from sklearn.feature_extraction import image
    >>> # Use the array data from the second image in this dataset:
    >>> X = load_sample_images().images[1]
    >>> X = X[None, ...]
    >>> print(f"Image shape: {X.shape}")
    Image shape: (1, 427, 640, 3)
    >>> pe = image.PatchExtractor(patch_size=(10, 10))
    >>> pe_trans = pe.transform(X)
    >>> print(f"Patches shape: {pe_trans.shape}")
    Patches shape: (263758, 10, 10, 3)
    >>> X_reconstructed = image.reconstruct_from_patches_2d(pe_trans, X.shape[1:])
    >>> print(f"Reconstructed shape: {X_reconstructed.shape}")
    Reconstructed shape: (427, 640, 3)
    Nr   r   r   r   r]   r   r   ri   r   _parameter_constraintsc                0    || _         || _        || _        d S rq   r   )selfr   ri   r   s       r*   __init__zPatchExtractor.__init__J  s    $&(r,   TrY   c                     | S )a  Only validate the parameters of the estimator.

        This method allows to: (i) validate the parameters of the estimator  and
        (ii) be consistent with the scikit-learn transformer API.

        Parameters
        ----------
        X : ndarray of shape (n_samples, image_height, image_width) or                 (n_samples, image_height, image_width, n_channels)
            Array of images from which to extract patches. For color images,
            the last dimension specifies the channel: a RGB image would have
            `n_channels=3`.

        y : Ignored
            Not used, present for API consistency by convention.

        Returns
        -------
        self : object
            Returns the instance itself.
         )r   Xys      r*   fitzPatchExtractor.fitO  s	    . r,   c           	         t          | |ddddd          }t          | j                  }|j        dd         \  }}}| j        |dz  |dz  f}n7t          | j                  dk    rt          d	| j         d
          | j        }|j        dd         \  }}}t          j        ||||df          }|j        d         }|\  }}	t          ||||	| j
                  }
||
z  f|z   }|dk    r||fz  }t          j        |          }t          |          D ]+\  }}t          ||| j
        |          |||
z  |dz   |
z  <   ,|S )a#  Transform the image samples in `X` into a matrix of patch data.

        Parameters
        ----------
        X : ndarray of shape (n_samples, image_height, image_width) or                 (n_samples, image_height, image_width, n_channels)
            Array of images from which to extract patches. For color images,
            the last dimension specifies the channel: a RGB image would have
            `n_channels=3`.

        Returns
        -------
        patches : array of shape (n_patches, patch_height, patch_width) or                 (n_patches, patch_height, patch_width, n_channels)
            The collection of patches extracted from the images, where
            `n_patches` is either `n_samples * max_patches` or the total
            number of patches that can be extracted.
        FTr   )r   	ensure_2dr   ensure_min_samplesensure_min_featuresresetNr   
   r	   z0patch_size must be a tuple of two integers. Got z	 instead.r   r   )r   r   r   r.   r   r8   rd   r   r   rm   ri   empty	enumerater   )r   r   r   n_imgs
img_height	img_widthr   
n_channelspatch_heightpatch_widthr   patches_shaper   iir   s                  r*   	transformzPatchExtractor.transformh  s   &   !
 
 
 *$*;<<()%
I?"#r)9?:JJ4?##q(( 33 3 3   J()%
IJq6:y"=>>WR[
 %/!k&	<d>N
 
	  )+-
:>>j]*M (=))"1 	 	IB=O ,)	> > >GBNb1f	%99:: r,   c                     t                                                      }d|j        _        d|j        _        d|_        |S )NFT)super__sklearn_tags__
input_tagstwo_d_arraythree_d_arrayrequires_fit)r   tags	__class__s     r*   r   zPatchExtractor.__sklearn_tags__  s9    ww''))&+#(,%!r,   rq   )__name__
__module____qualname____doc__rx   r   r   r   r   dict__annotations__r   r   r   r   r   __classcell__)r   s   @r*   r   r     s        2 2j dmHZAi888HXq$v666

 (($ $D    &*t$ ) ) ) ) )
 \555   650> > >@        r,   r   )r   rq   )rn   r   )-r   	itertoolsr   numbersr   r   r   numpyr   numpy.lib.stride_tricksr   scipyr   baser
   r   r   utilsr   r   utils._param_validationr   r   r   r   __all__utils.validationr   r+   r3   rB   rM   rW   rN   typer   rF   r   rm   r   rx   rz   r   r   r   r   r,   r*   <module>r      s   0 0
       * * * * * * * * * *     . . . . . .       @ @ @ @ @ @ @ @ @ @ 3 3 3 3 3 3 3 3 S S S S S S S S S S S S   - , , , , ,   (  (   * $&2C4, , , ,^ ~rz"V 	  #'   #f.?t (A (A (A (A (AV fEEEFfEEEFfEEEFrz"V   #'
 
 
 ,Q!V->c,Q ,Q ,Q ,Q
 
,Qf" " " "J8 8 8 8v *dmHZAi888HXq$v666

 ((	 	 #'   :>D _ _ _ _ _D UFF4LL,ABB"&  9 9	 9xb b b b b%} b b b b br,   