`L i \ dZddlmZddlmZmZmZddlZddl m Z ddl m Z ddl mZmZmZdd lmZmZdd lmZmZmZmZgd Zdd lmZd)dZdZd*dZdde j>dfdZ edgdejBge"gdddde j>dddZ#eeed ddgeed ddgeed ddgdejBge"gddd d)de j>e$ddZ%d*dZ&d+dZ'eejBge(e)geedd d eed dd dgd!gd"dddd#d$Z*eejBge(ee)gd%dd&Z+Gd'd(eeZ,y),z*Utilities to extract features from images.)product)IntegralNumberRealN) as_strided)sparse) BaseEstimatorTransformerMixin _fit_context) check_arraycheck_random_state)HiddenInterval RealNotIntvalidate_params)PatchExtractorextract_patches_2d grid_to_graph img_to_graphreconstruct_from_patches_2d) validate_datac"tj||z|zj|||f}tj|ddddddfj |ddddddfj f}tj|ddddfj |ddddfj f}tj|ddj |ddj f}tj |||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)nparangereshapevstackravelhstack)n_xn_yn_zvertices edges_deep edges_right edges_downedgess f/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/feature_extraction/image.py_make_edges_3dr+syysS)113S/BHHQ3B3Y/557!Q(9K9Q9Q9STUJ))Xa"f-335x127L7L7NOPKHSbM//18AB<3E3E3GHIJ IIz; ; `. 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]]) )rrGr.rW)r0r<rPrDr"r#r$s r*rrs9^ -- CIIMCc S#sD#y% @@r,left)r]rightclosedr"r#r$r<rPrDc$t||||||S)a&Graph of the pixel-to-pixel connections. Edges exist if 2 voxels are connected. Read more in the :ref:`User Guide `. 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) Coords Values (0, 0) 1 (1, 1) 1 r[)rWr`s r*rrsr S#s% PPr,c||z dz}||z dz}||z}|rht|tr||kr|St|tr||k\r|St|trd|cxkrdkrnnt||zSt d|z|S)aeCompute the number of patches that will be extracted in an image. Read more in the :ref:`User Guide `. 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. rrz!Invalid value for max_patches: %r) isinstancerrrF ValueError)i_hi_wp_hp_w max_patchesn_hn_w all_patchess r*_compute_n_patchesrms( )a-C )a-C)K kH .;3L   h 0[K5O   d ,[1D11D{[01 1@;NO Or,c,|j}t|trt|g|z}t|trt|g|z}|j}td|D}||j}t j |jt j |z t j |zdz}tt|t|z}tt|t|z} t||| } | S)ayExtracts 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 `. 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)) c36K|]}tdd|ywN)slice).0sts r* z#_extract_patches..PsCR5tR(Csr)r.strides) ndimrcrtuplerurarrayr.listr) arr patch_shapeextraction_steparr_ndim patch_stridesslicesindexing_stridespatch_indices_shaper.rupatchess r*_extract_patchesr#sHxxH+v&H45 /6* 1H <=KKM C?C CF6{** #)) rxx 4 4/9RR   $*+d;.?? @ED)*T--@@AGE7;G Nr,neitherr_ random_state)image patch_sizerirrirc|jdd\}}|\}}||kDr td||kDr tdt|d}|j||df}|jd}t ||||fd } t |||||} |rFt |} | j||z dz| } | j||z dz| } | | | d f}n| }|jd|||}|jddk(r|j| ||fS|S) aReshape a 2D image into a collection of patches. The resulting patches are allocated in a dedicated array. Read more in the :ref:`User Guide `. 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 `. 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_ndrr)r{r|)r5r)r.rdr rrrmrrandint)rrrirrerfrgrhn_colorsextracted_patches n_patchesrngi_sj_srs r*rr^sCR{{2AHCHC Sy N   Sy L    -E MM3R. )E{{2H( Ch/#3S#{CI .kk#)a-ik8kk#)a-ik8#CaK0#oob#sH5G}}RA 3455r,)r image_sizec|dd\}}|jdd\}}tj|}||z dz}||z dz}t|t t |t |D]!\} \} } || | |z| | |zfxx| z cc<#t |D]O} t |D]?} || | fxxt t| dz||| z t| dz||| z zzcc<AQ|S)aQReconstruct 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 `. 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.rzerosziprrangefloatmin) rrrerfrgrhr0rjrkpijs r*rrs^"1~HC}}Qq!HC ((: C )a-C )a-C'%*eCj"AB+ 6Aq ACKQW $%*%+3ZTs TA 1Is1q5#sQw7#a!eS#PQ':RRS SI TT Jr,c eZdZUdZedgdeedddeedddgdgd Ze e d <dddd d Z e d ddZ dZfdZxZS)raExtracts patches from a collection of images. Read more in the :ref:`User Guide `. .. 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 `. 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) Nrrrrr]rrrir_parameter_constraintsc.||_||_||_yrpr)selfrrirs r*__init__zPatchExtractor.__init__Ls$&(r,TrYc|S)aOnly 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. )rXys r*fitzPatchExtractor.fitQs . r,c t||ddddd}t|j}|jdd\}}}|j |dz|dzf}n=t |jdk7rt d |jd |j}|jdd\}}}tj||||d f}|jd }|\}} t|||| |j} || zf|z} |dkDr| |fz } tj| } t|D]*\} }t|||j| | | | z| dz| 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_2drensure_min_samplesensure_min_featuresresetNr r z0patch_size must be a tuple of two integers. Got z instead.rr)rrrr.rr8rdrrrmriempty enumerater)rrrn_imgs img_height img_widthr n_channels patch_height patch_widthr patches_shaperiirs r* transformzPatchExtractor.transformjs&   ! *$*;*;< () % I ?? "#r)9?:J4??#q( ( 3J() % I JJq6:y"= >WWR[ %/! k&  <d>N>N  )+- : > j] *M((=)"1 IB=O ,,) >GBNb1f %9 : r,cvt|}d|j_d|j_d|_|S)NFT)super__sklearn_tags__ input_tags two_d_array three_d_array requires_fit)rtags __class__s r*rzPatchExtractor.__sklearn_tags__s5w')&+#(,%! r,rp)__name__ __module__ __qualname____doc__rwrrrrdict__annotations__rr rrr __classcell__)rs@r*rr s2jdm  ZAi 8 Xq$v 6 (($D&*t$) 560>@r,r)rrp)r)-r itertoolsrnumbersrrrnumpyrnumpy.lib.stride_tricksrscipyrbaser r r utilsr rutils._param_validationrrrr__all__utils.validationrr+r3rBrMrWrNtyperrFrrmrrwryrrrrr,r*rs0 **.@@3SS - ((*$&2C2C4,^~rzz"V  #'#f.?.?t(A(AVfEFfEFfEFrzz"V #' .Q!V->->c.Q .Qj"J8v**dm ZAi 8 Xq$v 6  (( #' :>D_ _D UF4L,AB"&9 9xb%}br,