
    1-PhQ                         d dl Zd dlmZ d dlm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 g dZddddZd Zd Z	 	 	 	 	 	 ddZd Z	 	 	 	 	 	 ddZdS )    N)interp1d)golden_ratio)fftifftfftfreqfftshift   )warp)sart_projection_update   )convert_to_float)warn)partial)radonorder_angles_golden_ratioiradoniradon_sartTF)preserve_rangec          	          | j         dk    rt          d          |t          j        d          }t	          | |          } |rt          | j                  dz  }t          j        | j                  }t          j        t          j        d| j        d         d| j        d         f         t                    }||dz  z
  dz  
                    d          }||dz  k    }t          j        | |                   rt          d           t          fd	|z
  D                       }	| |	         }
nt          j        d          t          | j                  z  fd
| j        D             }d t!          | j        |          D             }d | j        D             }d t!          ||          D             }d t!          ||          D             }t          j        | |dd          }
|
j        d         |
j        d         k    rt          d          |
j        d         dz  }t          j        |
j        d         t'          |          f| j                  }t+          t          j        |                    D ]\  }}t          j        |          t          j        |          }}t          j        ||| ||z   dz
  z  g| || ||z
  dz
  z  gg dg          }t3          |
|d          }|
                    d          |dd|f<   |S )aV  
    Calculates the radon transform of an image given specified
    projection angles.

    Parameters
    ----------
    image : ndarray
        Input image. The rotation axis will be located in the pixel with
        indices ``(image.shape[0] // 2, image.shape[1] // 2)``.
    theta : array, optional
        Projection angles (in degrees). If `None`, the value is set to
        np.arange(180).
    circle : boolean, optional
        Assume image is zero outside the inscribed circle, making the
        width of each projection (the first dimension of the sinogram)
        equal to ``min(image.shape)``.
    preserve_range : bool, optional
        Whether to keep the original range of values. Otherwise, the input
        image is converted according to the conventions of `img_as_float`.
        Also see https://scikit-image.org/docs/dev/user_guide/data_types.html

    Returns
    -------
    radon_image : ndarray
        Radon transform (sinogram).  The tomography rotation axis will lie
        at the pixel index ``radon_image.shape[0] // 2`` along the 0th
        dimension of ``radon_image``.

    References
    ----------
    .. [1] AC Kak, M Slaney, "Principles of Computerized Tomographic
           Imaging", IEEE Press 1988.
    .. [2] B.R. Ramesh, N. Srinivasa, K. Rajgopal, "An Algorithm for Computing
           the Discrete Radon Transform With Some Applications", Proceedings of
           the Fourth IEEE Region 10 International Conference, TENCON '89, 1989

    Notes
    -----
    Based on code of Justin K. Romberg
    (https://www.clear.rice.edu/elec431/projects96/DSP/bpanalysis.html)

    r   The input image must be 2-DN   r   r	   dtypezERadon transform: image must be zero outside the reconstruction circlec           
   3      K   | ]p}|d k    rWt          t          t          j        |dz                      t          t          j        |dz            z                       nt          d          V  qdS )r   r   N)sliceintnpceil).0excess	shape_mins     a/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/skimage/transform/radon_transform.py	<genexpr>zradon.<locals>.<genexpr>O   s       
 
  A:: c"'&1*--..BGFQJ4G4G)4S0T0TUUU4[[	
 
 
 
 
 
    c                 X    g | ]&}t          t          j        |z
                      'S  )r   r   r   )r   sdiagonals     r"   
<listcomp>zradon.<locals>.<listcomp>Z   s/    ???as278a<(())???r$   c                 $    g | ]\  }}||z   d z  S r   r&   )r   r'   ps      r"   r)   zradon.<locals>.<listcomp>[   s$    EEEtq!q1ulEEEr$   c                     g | ]}|d z  S r+   r&   )r   r'   s     r"   r)   zradon.<locals>.<listcomp>\   s    222a1f222r$   c                     g | ]
\  }}||z
  S r&   r&   )r   ocncs      r"   r)   zradon.<locals>.<listcomp>]   s     HHH&"bb2gHHHr$   c                 "    g | ]\  }}|||z
  fS r&   r&   )r   pbr,   s      r"   r)   zradon.<locals>.<listcomp>^   s$    DDDeb!b!b&\DDDr$   constantmodeconstant_valueszpadded_image must be a square)r   r   r	   F)clip)ndim
ValueErrorr   aranger   minshapearrayogridobjectsumanyr   tuplesqrtmaxzippadzeroslenr   	enumeratedeg2radcossinr
   )imagethetacircler   radius	img_shapecoordsdistoutside_reconstruction_circleslicespadded_imagerF   
new_center
old_center
pad_before	pad_widthcenterradon_imageianglecos_asin_aRrotatedr(   r!   s                           @@r"   r   r      sG   V zQ6777}	#UN33E T$$	aHU[))	"(#3U[^#35Eu{1~5E#EFfUUU)q.(Q.33A66(,vqy(8%6%5677 	(  
  
 
 
 
 %y0
 
 
 
 
 V}71::EK 0 00????5;???EEs5;/D/DEEE
22ek222
HHC
J,G,GHHH
DDs:s/C/CDDD	veYZQRSSS ! 21 5558999"a'F(L.q13u::>ekRRRKbj//00 
+ 
+5ve}}bfUmmuHw%%-!*;<=55=1+< =>		
 
 |QU333#KKNNAAAqDr$   c                    t          t          j        t          j        d          | j        d         z                      }|| j        d         z
  }| j        d         dz  }|dz  }||z
  }|||z
  fdf}t          j        | |dd          S )Nr   r   r   r   r3   r4   )r   r   r   rC   r<   rF   )sinogramr(   rF   rX   rW   rY   rZ   s          r"   _sinogram_circle_to_squarerf   u   s    27271::q(99::;;H
X^A&
&C"a'JQJj(JcJ./8I6(IJJJJJr$   c           	         t          j        t          j        d| dz  dz   dt                    t          j        | dz  dz
  ddt                    f          }t          j        |           }d|d<   dt           j        |z  dz  z  |ddd<   dt          j        t          |                    z  }|d	k    rn |d
k    rLt           j        t          |           dd         z  }|ddxx         t          j	        |          |z  z  cc<   n|dk    rIt          j
        dt           j        | d          }t          t          j	        |                    }||z  }n_|dk    r%|t          t          j        |                     z  }n4|dk    r%|t          t          j        |                     z  }n	|d|dd<   |ddt           j        f         S )a{  Construct the Fourier filter.

    This computation lessens artifacts and removes a small bias as
    explained in [1], Chap 3. Equation 61.

    Parameters
    ----------
    size : int
        filter size. Must be even.
    filter_name : str
        Filter used in frequency domain filtering. Filters available:
        ramp, shepp-logan, cosine, hamming, hann. Assign None to use
        no filter.

    Returns
    -------
    fourier_filter: ndarray
        The computed Fourier filter.

    References
    ----------
    .. [1] AC Kak, M Slaney, "Principles of Computerized Tomographic
           Imaging", IEEE Press 1988.

    r	   r   r   r   g      ?Nrampshepp-logancosineFendpointhamminghann)r   concatenater:   r   rG   pirealr   r   rL   linspacer   ro   hanningnewaxis)sizefilter_namenffourier_filteromegafreqcosine_filters           r"   _get_fourier_filterr      s   4 	IaAq444IdQhlAr555	
	 	A 	AAaDBEAI!##AaddG
 Q(Nf		%	%abb))qrrbfUmme33		 	 {1beTE::: ..-'			!	!(2:d#3#3444			(2:d#3#3444		qqq!!!RZ-((r$   rj   linearc                    | j         dk    rt          d          |#t          j        dd| j        d         d          }t          |          }|| j        d         k    rt          d	          d
}||vrt          d|           d}	||	vrt          d|           t          | |          } | j        }
| j        d         }|>|r|}n9t          t          j	        t          j
        |dz  dz                                }|rt          |           } | j        d         }t          dt          dt          j        t          j        d|z                      z                      }d||z
  fdf}t          j        | |dd          }t!          ||          }t#          |d          |z  }t          j        t'          |d          d|ddf                   }t          j        ||f|
          }|dz  }t          j        d|d|f         |z
  \  }}t          j        |          |dz  z
  }t/          |j        t          j        |                    D ]{\  }}|t          j        |          z  |t          j        |          z  z
  }|dk    rt9          t          j        ||dd          }nt=          |||dd          }| ||          z  }||r|dz  |dz  z   |dz  k    }d||<   |t          j        z  d|z  z  S )a
  Inverse radon transform.

    Reconstruct an image from the radon transform, using the filtered
    back projection algorithm.

    Parameters
    ----------
    radon_image : ndarray
        Image containing radon transform (sinogram). Each column of
        the image corresponds to a projection along a different
        angle. The tomography rotation axis should lie at the pixel
        index ``radon_image.shape[0] // 2`` along the 0th dimension of
        ``radon_image``.
    theta : array, optional
        Reconstruction angles (in degrees). Default: m angles evenly spaced
        between 0 and 180 (if the shape of `radon_image` is (N, M)).
    output_size : int, optional
        Number of rows and columns in the reconstruction.
    filter_name : str, optional
        Filter used in frequency domain filtering. Ramp filter used by default.
        Filters available: ramp, shepp-logan, cosine, hamming, hann.
        Assign None to use no filter.
    interpolation : str, optional
        Interpolation method used in reconstruction. Methods available:
        'linear', 'nearest', and 'cubic' ('cubic' is slow).
    circle : boolean, optional
        Assume the reconstructed image is zero outside the inscribed circle.
        Also changes the default output_size to match the behaviour of
        ``radon`` called with ``circle=True``.
    preserve_range : bool, optional
        Whether to keep the original range of values. Otherwise, the input
        image is converted according to the conventions of `img_as_float`.
        Also see https://scikit-image.org/docs/dev/user_guide/data_types.html

    Returns
    -------
    reconstructed : ndarray
        Reconstructed image. The rotation axis will be located in the pixel
        with indices
        ``(reconstructed.shape[0] // 2, reconstructed.shape[1] // 2)``.

    .. versionchanged:: 0.19
        In ``iradon``, ``filter`` argument is deprecated in favor of
        ``filter_name``.

    References
    ----------
    .. [1] AC Kak, M Slaney, "Principles of Computerized Tomographic
           Imaging", IEEE Press 1988.
    .. [2] B.R. Ramesh, N. Srinivasa, K. Rajgopal, "An Algorithm for Computing
           the Discrete Radon Transform With Some Applications", Proceedings of
           the Fourth IEEE Region 10 International Conference, TENCON '89, 1989

    Notes
    -----
    It applies the Fourier slice theorem to reconstruct an image by
    multiplying the frequency domain of the filter with the FFT of the
    projection data. This algorithm is called filtered back projection.

    r   r   Nr   r   r	   Frm   zPThe given ``theta`` does not match the number of projections in ``radon_image``.)r   nearestcubiczUnknown interpolation: )rj   rk   rl   ro   rp   NzUnknown filter: g       @@   rd   r3   r4   )axisr   r   )xpfpleftright)kindbounds_error
fill_valueg        ) r8   r9   r   rt   r<   rH   r   r   r   floorrC   rf   rD   r   log2rF   r   r   rs   r   rG   mgridr:   rE   TrJ   rK   rL   r   interpr   rr   )r\   rN   output_sizerx   interpolationrO   r   angles_countinterpolation_typesfilter_typesr   rQ   projection_size_paddedrZ   imgr{   
projectionradon_filteredreconstructedrP   xpryprxcolr^   tinterpolantout_reconstruction_circles                               r"   r   r      s]   J 16777}AsK$5a$85IIIu::L{(+++.
 
 	

 9///B=BBCCCML,&&9K99:::";??KE!!$I 	I#KKbhrw	a/?#/E'F'FGGHHK )0==%a(	 !Sbgbga)m6L6L.M.M)M%N%NOO+i78&AI
&ij!
L
L
LC ))?MMNSq!!!N2JWT*1555jyj!!!mDEEN Hk;7uEEEMAFxl{l23f<HC
	)yA~-A.*BJu,=,=>> ( (
U"&--#u"55H$$!")cKKKKK"3]1  K 	Q' 7%(!Vc1f_	$A!36/025 A$455r$   c              #   ^  K   d}t          t          j        |                     }| |d                  }|                    d          V  |t          dz  z  }|r| |         }||z   |z  }t          j        ||          }|dz
  }|t          |          z  }t          |||         z
            }t          ||z  || z            }	t          |||         z
            }
t          |
|z  |
| z            }|	|k     r|                    |          V  n|                    |          V  |dS dS )a  Order angles to reduce the amount of correlated information in
    subsequent projections.

    Parameters
    ----------
    theta : array of floats, shape (M,)
        Projection angles in degrees. Duplicate angles are not allowed.

    Returns
    -------
    indices_generator : generator yielding unsigned integers
        The returned generator yields indices into ``theta`` such that
        ``theta[indices]`` gives the approximate golden ratio ordering
        of the projections. In total, ``len(theta)`` indices are yielded.
        All non-negative integers < ``len(theta)`` are yielded exactly once.

    Notes
    -----
    The method used here is that of the golden ratio introduced
    by T. Kohler.

    References
    ----------
    .. [1] Kohler, T. "A projection access scheme for iterative
           reconstruction based on the golden section." Nuclear Science
           Symposium Conference Record, 2004 IEEE. Vol. 6. IEEE, 2004.
    .. [2] Winkelmann, Stefanie, et al. "An optimal radial profile order
           based on the Golden Ratio for time-resolved MRI."
           Medical Imaging, IEEE Transactions on 26.1 (2007): 68-76.

    r   r   r   r	   N)	listr   argsortpopr   searchsortedrH   absr;   )rN   intervalremaining_indicesr^   angle_incrementremaining_anglesindex_aboveindex_below
diff_belowdistance_below
diff_abovedistance_aboves               r"   r   r   F  su     @ HRZ..//#A&'E



"
""""q0O
 5 !23(H4o&6>>!Aos,---!1+!>>??
Z(2J(4JKK!1+!>>??
Z(2J(4JKKN**#''444444#''44444!  5 5 5 5 5r$   333333?c                    | j         dk    rt          d          |?| j        j        dv r| j        }nSt	          d           t          j        t                    }n*t          j        |          j        dvrt          d          t          j        |          }|                     |d          } | j        d	         | j        d	         f}|%t          j	        d	d
| j        d         d|          }nbt          |          | j        d         k    r.t          dt          |           d| j        d          d          t          j        ||          }|t          j        ||          }nC|j        |k    rt          d|j         d| d          |j        |k    rt	          d|            t          j        ||          }|#t          j        | j        d         f|          }nbt          |          | j        d         k    r.t          dt          |           d| j        d          d          t          j        ||          }|8t          |          dk    rt          d          t          j        ||          }t          |          D ]V}t          |||         | dd|f         ||                   }	|||	z  z  }|"t          j        ||d	         |d                   }W|S )u*  Inverse radon transform.

    Reconstruct an image from the radon transform, using a single iteration of
    the Simultaneous Algebraic Reconstruction Technique (SART) algorithm.

    Parameters
    ----------
    radon_image : ndarray, shape (M, N)
        Image containing radon transform (sinogram). Each column of
        the image corresponds to a projection along a different angle. The
        tomography rotation axis should lie at the pixel index
        ``radon_image.shape[0] // 2`` along the 0th dimension of
        ``radon_image``.
    theta : array, shape (N,), optional
        Reconstruction angles (in degrees). Default: m angles evenly spaced
        between 0 and 180 (if the shape of `radon_image` is (N, M)).
    image : ndarray, shape (M, M), optional
        Image containing an initial reconstruction estimate. Default is an array of zeros.
    projection_shifts : array, shape (N,), optional
        Shift the projections contained in ``radon_image`` (the sinogram) by
        this many pixels before reconstructing the image. The i'th value
        defines the shift of the i'th column of ``radon_image``.
    clip : length-2 sequence of floats, optional
        Force all values in the reconstructed tomogram to lie in the range
        ``[clip[0], clip[1]]``
    relaxation : float, optional
        Relaxation parameter for the update step. A higher value can
        improve the convergence rate, but one runs the risk of instabilities.
        Values close to or higher than 1 are not recommended.
    dtype : dtype, optional
        Output data type, must be floating point. By default, if input
        data type is not float, input is cast to double, otherwise
        dtype is set to input data type.

    Returns
    -------
    reconstructed : ndarray
        Reconstructed image. The rotation axis will be located in the pixel
        with indices
        ``(reconstructed.shape[0] // 2, reconstructed.shape[1] // 2)``.

    Notes
    -----
    Algebraic Reconstruction Techniques are based on formulating the tomography
    reconstruction problem as a set of linear equations. Along each ray,
    the projected value is the sum of all the values of the cross section along
    the ray. A typical feature of SART (and a few other variants of algebraic
    techniques) is that it samples the cross section at equidistant points
    along the ray, using linear interpolation between the pixel values of the
    cross section. The resulting set of linear equations are then solved using
    a slightly modified Kaczmarz method.

    When using SART, a single iteration is usually sufficient to obtain a good
    reconstruction. Further iterations will tend to enhance high-frequency
    information, but will also often increase the noise.

    References
    ----------
    .. [1] AC Kak, M Slaney, "Principles of Computerized Tomographic
           Imaging", IEEE Press 1988.
    .. [2] AH Andersen, AC Kak, "Simultaneous algebraic reconstruction
           technique (SART): a superior implementation of the ART algorithm",
           Ultrasonic Imaging 6 pp 81--94 (1984)
    .. [3] S Kaczmarz, "Angenäherte auflösung von systemen linearer
           gleichungen", Bulletin International de l’Academie Polonaise des
           Sciences et des Lettres 35 pp 355--357 (1937)
    .. [4] Kohler, T. "A projection access scheme for iterative
           reconstruction based on the golden section." Nuclear Science
           Symposium Conference Record, 2004 IEEE. Vol. 6. IEEE, 2004.
    .. [5] Kaczmarz' method, Wikipedia,
           https://en.wikipedia.org/wiki/Kaczmarz_method

    r   z#radon_image must be two dimensionalNfdzOnly floating point data type are valid for SART inverse radon transform. Input data is cast to float. To disable this warning, please cast image_radon to float.zDOnly floating point data type are valid for inverse radon transform.F)copyr   r   r	   )rn   r   zShape of theta (z,) does not match the number of projections ()r   zShape of image (z1) does not match first dimension of radon_image (z:image dtype does not match output dtype: image is cast to zShape of projection_shifts (z clip must be a length-2 sequence)r8   r9   r   charr   r   floatastyper<   rt   rH   asarrayrG   r   r   r7   )
r\   rN   rM   projection_shiftsr7   
relaxationr   reconstructed_shapeangle_indeximage_updates
             r"   r   r     sk   d 1>???}!T))%EEB  
 HUOOEE	%	T	)	)U
 
 	
 HUOOE$$U$77K&,Q/1B11EF}AsK$5a$85PUVVV	U{(+	+	+>s5zz > >&1&7&:> > >
 
 	

 
5...},E:::	+	+	+6u{ 6 626 6 6
 
 	
 
		UeUUVVVJuE***E Hk&7&:%<EJJJ			;#4Q#7	7	7>3/@+A+A > >&1&7&:> > >
 
 	

 J'8FFFt99>>?@@@z$e,,,077 	5 	5-+;'k*	
 
 	l**GE47DG44ELr$   )NT)NNrj   r   TT)NNNNr   N)numpyr   scipy.interpolater   scipy.constantsr   	scipy.fftr   r   r   r   _warpsr
   _radon_transformr   _shared.utilsr   warningsr   	functoolsr   __all__r   rf   r   r   r   r   r&   r$   r"   <module>r      s       & & & & & & ( ( ( ( ( ( 2 2 2 2 2 2 2 2 2 2 2 2       4 4 4 4 4 4 , , , , , ,             J
I
IbE b b b b bJK K K9) 9) 9)| H6 H6 H6 H6V85 85 85z 
	
W W W W W Wr$   