
    1-Ph=                         d dl Zd dlmZ ddlmZmZmZ ddlmZ	 dddej
        fdZddZddZddZ	 ddZdddej
        ej
        d
fdZd ZdS )    N)cKDTree   )_hough_circle_hough_ellipse_hough_line)_probabilistic_hough_line	   
   c                     ddl m} t          || j        d                   } || ||||          \  }}	}
|	j        dk    r|||	         ||
         fS |t          j        g           t          j        g           fS )a  Return peaks in a straight line Hough transform.

    Identifies most prominent lines separated by a certain angle and distance
    in a Hough transform. Non-maximum suppression with different sizes is
    applied separately in the first (distances) and second (angles) dimension
    of the Hough space to identify peaks.

    Parameters
    ----------
    hspace : ndarray, shape (M, N)
        Hough space returned by the `hough_line` function.
    angles : array, shape (N,)
        Angles returned by the `hough_line` function. Assumed to be continuous.
        (`angles[-1] - angles[0] == PI`).
    dists : array, shape (M,)
        Distances returned by the `hough_line` function.
    min_distance : int, optional
        Minimum distance separating lines (maximum filter size for first
        dimension of hough space).
    min_angle : int, optional
        Minimum angle separating lines (maximum filter size for second
        dimension of hough space).
    threshold : float, optional
        Minimum intensity of peaks. Default is `0.5 * max(hspace)`.
    num_peaks : int, optional
        Maximum number of peaks. When the number of peaks exceeds `num_peaks`,
        return `num_peaks` coordinates based on peak intensity.

    Returns
    -------
    accum, angles, dists : tuple of array
        Peak values in Hough space, angles and distances.

    Examples
    --------
    >>> from skimage.transform import hough_line, hough_line_peaks
    >>> from skimage.draw import line
    >>> img = np.zeros((15, 15), dtype=bool)
    >>> rr, cc = line(0, 0, 14, 14)
    >>> img[rr, cc] = 1
    >>> rr, cc = line(0, 14, 14, 0)
    >>> img[cc, rr] = 1
    >>> hspace, angles, dists = hough_line(img)
    >>> hspace, angles, dists = hough_line_peaks(hspace, angles, dists)
    >>> len(angles)
    2

       _prominent_peaksr   min_xdistancemin_ydistance	threshold	num_peaksr   )feature.peakr   minshapesizenparray)hspaceanglesdistsmin_distance	min_angler   r   r   hads              a/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/skimage/transform/hough_transform.pyhough_line_peaksr#      s    r 0/////Iv|A//I"  GAq! 	vzz6!9eAh''28B<<"..    TFc                     t          j        t          j        |                    }t          | |                    t           j                  ||          S )a  Perform a circular Hough transform.

    Parameters
    ----------
    image : ndarray, shape (M, N)
        Input image with nonzero values representing edges.
    radius : scalar or sequence of scalars
        Radii at which to compute the Hough transform.
        Floats are converted to integers.
    normalize : boolean, optional
        Normalize the accumulator with the number
        of pixels used to draw the radius.
    full_output : boolean, optional
        Extend the output size by twice the largest
        radius in order to detect centers outside the
        input picture.

    Returns
    -------
    H : ndarray, shape (radius index, M + 2R, N + 2R)
        Hough transform accumulator for each radius.
        R designates the larger radius if full_output is True.
        Otherwise, R = 0.

    Examples
    --------
    >>> from skimage.transform import hough_circle
    >>> from skimage.draw import circle_perimeter
    >>> img = np.zeros((100, 100), dtype=bool)
    >>> rr, cc = circle_perimeter(25, 35, 23)
    >>> img[rr, cc] = 1
    >>> try_radii = np.arange(5, 50)
    >>> res = hough_circle(img, try_radii)
    >>> ridx, r, c = np.unravel_index(np.argmax(res), res.shape)
    >>> r, c, try_radii[ridx]
    (25, 35, 23)

    )	normalizefull_output)r   
atleast_1dasarrayr   astypeintp)imageradiusr&   r'   s       r"   hough_circler.   Q   sL    N ]2:f--..Fv}}RW%%   r$      c                 *    t          | ||||          S )a  Perform an elliptical Hough transform.

    Parameters
    ----------
    image : (M, N) ndarray
        Input image with nonzero values representing edges.
    threshold : int, optional
        Accumulator threshold value. A lower value will return more ellipses.
    accuracy : double, optional
        Bin size on the minor axis used in the accumulator. A higher value
        will return more ellipses, but lead to a less precise estimation of
        the minor axis lengths.
    min_size : int, optional
        Minimal major axis length.
    max_size : int, optional
        Maximal minor axis length.
        If None, the value is set to half of the smaller
        image dimension.

    Returns
    -------
    result : ndarray with fields [(accumulator, yc, xc, a, b, orientation)].
        Where ``(yc, xc)`` is the center, ``(a, b)`` the major and minor
        axes, respectively. The `orientation` value follows the
        `skimage.draw.ellipse_perimeter` convention.

    Examples
    --------
    >>> from skimage.transform import hough_ellipse
    >>> from skimage.draw import ellipse_perimeter
    >>> img = np.zeros((25, 25), dtype=np.uint8)
    >>> rr, cc = ellipse_perimeter(10, 10, 6, 8)
    >>> img[cc, rr] = 1
    >>> result = hough_ellipse(img, threshold=8)
    >>> result.tolist()
    [(10, 10.0, 10.0, 8.0, 6.0, 0.0)]

    Notes
    -----
    Potential ellipses in the image are characterized by their major and
    minor axis lengths. For any pair of nonzero pixels in the image that
    are at least half of `min_size` apart, an accumulator keeps track of
    the minor axis lengths of potential ellipses formed with all the
    other nonzero pixels. If any bin (with `bin_size = accuracy * accuracy`)
    in the histogram of those accumulated minor axis lengths is above
    `threshold`, the corresponding ellipse is added to the results.

    A higher `accuracy` will therefore lead to more ellipses being found
    in the image, at the cost of a less precise estimation of the minor
    axis length.

    References
    ----------
    .. [1] Xie, Yonghong, and Qiang Ji. "A new efficient ellipse detection
           method." Pattern Recognition, 2002. Proceedings. 16th International
           Conference on. Vol. 2. IEEE, 2002
    )r   accuracymin_sizemax_size)r   )r,   r   r1   r2   r3   s        r"   hough_ellipser4   ~   s+    t    r$   c                     | j         dk    rt          d          |3t          j        t          j         dz  t          j        dz  dd          }t          | |          S )a3  Perform a straight line Hough transform.

    Parameters
    ----------
    image : (M, N) ndarray
        Input image with nonzero values representing edges.
    theta : ndarray of double, shape (K,), optional
        Angles at which to compute the transform, in radians.
        Defaults to a vector of 180 angles evenly spaced in the
        range [-pi/2, pi/2).

    Returns
    -------
    hspace : ndarray of uint64, shape (P, Q)
        Hough transform accumulator.
    angles : ndarray
        Angles at which the transform is computed, in radians.
    distances : ndarray
        Distance values.

    Notes
    -----
    The origin is the top left corner of the original image.
    X and Y axis are horizontal and vertical edges respectively.
    The distance is the minimal algebraic distance from the origin
    to the detected line.
    The angle accuracy can be improved by decreasing the step size in
    the `theta` array.

    Examples
    --------
    Generate a test image:

    >>> img = np.zeros((100, 150), dtype=bool)
    >>> img[30, :] = 1
    >>> img[:, 65] = 1
    >>> img[35:45, 35:50] = 1
    >>> for i in range(90):
    ...     img[i, i] = 1
    >>> rng = np.random.default_rng()
    >>> img += rng.random(img.shape) > 0.95

    Apply the Hough transform:

    >>> out, angles, d = hough_line(img)
    r   #The input image `image` must be 2D.N   Fendpoint)theta)ndim
ValueErrorr   linspacepir   )r,   r:   s     r"   
hough_liner?      s]    ^ zQ>???}RUFQJ	3GGGuE****r$   2   c                     | j         dk    rt          d          |3t          j        t          j         dz  t          j        dz  dd          }t          | |||||          S )am  Return lines from a progressive probabilistic line Hough transform.

    Parameters
    ----------
    image : ndarray, shape (M, N)
        Input image with nonzero values representing edges.
    threshold : int, optional
        Threshold
    line_length : int, optional
        Minimum accepted length of detected lines.
        Increase the parameter to extract longer lines.
    line_gap : int, optional
        Maximum gap between pixels to still form a line.
        Increase the parameter to merge broken lines more aggressively.
    theta : ndarray of dtype, shape (K,), optional
        Angles at which to compute the transform, in radians.
        Defaults to a vector of 180 angles evenly spaced in the
        range [-pi/2, pi/2).
    rng : {`numpy.random.Generator`, int}, optional
        Pseudo-random number generator.
        By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`).
        If `rng` is an int, it is used to seed the generator.

    Returns
    -------
    lines : list
      List of lines identified, lines in format ((x0, y0), (x1, y1)),
      indicating line start and end.

    References
    ----------
    .. [1] C. Galamhos, J. Matas and J. Kittler, "Progressive probabilistic
           Hough transform for line detection", in IEEE Computer Society
           Conference on Computer Vision and Pattern Recognition, 1999.
    r   r6   Nr7   Fr8   )r   line_lengthline_gapr:   rng)r;   r<   r   r=   r>   _prob_hough_line)r,   r   rB   rC   r:   rD   s         r"   probabilistic_hough_linerF      ss    N zQ>???}RUFQJ	3GGG   r$   c                    ddl m} g }	g }
g }g }t          ||           D ]~\  }} ||||||          \  }}}|	                    |ft	          |          z             |
                    |           |                    |           |                    |           t          j        |	          }	t          j        |
          }
t          j        |          }t          j        |          }|rt          j        ||	z            }nt          j        |          }||         ddd         |
|         ddd         ||         ddd         |	|         ddd         f\  }}}}|t
          j        k    rt	          |          n|}|dk    r|dk    st	          |          dk    r&|d|         |d|         |d|         |d|         fS t          |||||          }||         ||         ||         ||         fS )a  Return peaks in a circle Hough transform.

    Identifies most prominent circles separated by certain distances in given
    Hough spaces. Non-maximum suppression with different sizes is applied
    separately in the first and second dimension of the Hough space to
    identify peaks. For circles with different radius but close in distance,
    only the one with highest peak is kept.

    Parameters
    ----------
    hspaces : (M, N, P) array
        Hough spaces returned by the `hough_circle` function.
    radii : (M,) array
        Radii corresponding to Hough spaces.
    min_xdistance : int, optional
        Minimum distance separating centers in the x dimension.
    min_ydistance : int, optional
        Minimum distance separating centers in the y dimension.
    threshold : float, optional
        Minimum intensity of peaks in each Hough space.
        Default is `0.5 * max(hspace)`.
    num_peaks : int, optional
        Maximum number of peaks in each Hough space. When the
        number of peaks exceeds `num_peaks`, only `num_peaks`
        coordinates based on peak intensity are considered for the
        corresponding radius.
    total_num_peaks : int, optional
        Maximum number of peaks. When the number of peaks exceeds `num_peaks`,
        return `num_peaks` coordinates based on peak intensity.
    normalize : bool, optional
        If True, normalize the accumulator by the radius to sort the prominent
        peaks.

    Returns
    -------
    accum, cx, cy, rad : tuple of array
        Peak values in Hough space, x and y center coordinates and radii.

    Examples
    --------
    >>> from skimage import transform, draw
    >>> img = np.zeros((120, 100), dtype=int)
    >>> radius, x_0, y_0 = (20, 99, 50)
    >>> y, x = draw.circle_perimeter(y_0, x_0, radius)
    >>> img[x, y] = 1
    >>> hspaces = transform.hough_circle(img, radius)
    >>> accum, cx, cy, rad = hough_circle_peaks(hspaces, [radius,])

    Notes
    -----
    Circles with bigger radius have higher peaks in Hough space. If larger
    circles are preferred over smaller ones, `normalize` should be False.
    Otherwise, circles will be returned in the order of decreasing voting
    number.
    r   r   r   Nr   r   )
r   r   zipextendlenr   r   argsortinflabel_distant_points)hspacesradiir   r   r   r   total_num_peaksr&   r   rcxcyaccumradhph_px_py_psaccum_sorted	cx_sorted	cy_sortedr_sortedtnpshould_keeps                            r"   hough_circle_peaksrb   1  s>   B 0/////
A	B	BEug&&  R((''
 
 
S# 	
##c(("###
		#
		#S
A	"B	"BHUOOE Juqy!!Jua2
1ddd
1ddd	!TTrT
	40L)Y  /"&88#l


oC
 	}11c,6G6G16L6LTcT"IdsdOYtt_htPStnUU '9m]C K 	[!++	 r$   c                 <   t          j        t          |           t                    }t          j        | |gd          }t          |          }d}t          t          |                     D ]}	||k    rd||	<   ||	         s|                    | |	         ||	         ft          j        ||                    }
|
D ]U}t          | |         | |	         z
            |k    }t          ||         ||	         z
            |k    }|r|r||	k    rd||<   V|dz  }| }|S )a  Keep points that are separated by certain distance in each dimension.

    The first point is always accepted and all subsequent points are selected
    so that they are distant from all their preceding ones.

    Parameters
    ----------
    xs : array, shape (M,)
        X coordinates of points.
    ys : array, shape (M,)
        Y coordinates of points.
    min_xdistance : int
        Minimum distance separating points in the x dimension.
    min_ydistance : int
        Minimum distance separating points in the y dimension.
    max_points : int
        Max number of distant points to keep.

    Returns
    -------
    should_keep : array of bool
        A mask array for distant points to keep.
    )dtyper   )axisr   T)
r   zerosrK   boolstackr   rangequery_ball_pointhypotabs)xsysr   r   
max_pointsis_neighborcoordinateskd_treen_ptsineighbors_inix_closey_closera   s                  r"   rN   rN     s>   0 (3r77$///K(B8!,,,Kk""GE3r77^^  J!KNNQ 	 "22A1 F F K " + +bfr!un-->bfr!un--> +w +266&*KOQJE,Kr$   )TF)r/   r   r/   N)N)r
   r@   r
   NN)numpyr   scipy.spatialr   _hough_transformr   r   r   r   rE   rM   r#   r.   r4   r?   rF   rb   rN    r$   r"   <module>r}      s%       ! ! ! ! ! ! H H H H H H H H H H K K K K K K fF/ F/ F/ F/R* * * *Z@ @ @ @F6+ 6+ 6+ 6+t GK4 4 4 4t fFv v v vr/ / / / /r$   