U
    !?hK                     @   s   d dl mZmZ d dlZd/ddZedddddd Zedddddd Zedddddd Zedddddd Z	edddddd Z
edddddd Zeddddd d! Zed"dddd#d$d% Zed&dddd#d'd( Zed)dddd#d*d+ Zed,dddd#d-d. ZdS )0    )njitpndindexNF
   {Gz?   g      @       @      ?g      @      皙?c                 C   s.  | j tjtjfks"td| j  |j tjtjfksDtd|j  |j| jdd ksptd| j d|j t| jdkr| jd dkstd| j |dkrd|	 d	 d d
tj  }|dkrd|	 d	 d d
tj  }| tj} |tj}|	 }|dkr&|dkr&t
||| ||d | |dk jdd}| |dk jdd}t| | }t| | }t|}|\}}}}t|||| |||||||d t| }t| }t|}t|||||| ||d t| }t| }t|}t||||||| ||	|
||||d |r&|||fS |S dS )a	  
    Estimate alpha from an input image and an input trimap using Shared Matting as proposed by :cite:`GastalOliveira2010SharedMatting`.

    Parameters
    ----------
    image: numpy.ndarray
        Image with shape :math:`h \times  w \times d` for which the alpha matte should be estimated
    trimap: numpy.ndarray
        Trimap with shape :math:`h \times  w` of the image
    return_foreground_background: numpy.ndarray
        Whether to return foreground and background estimate. They will be computed either way
    trimap_expansion_radius: int
        How much to expand trimap.
    trimap_expansion_threshold: float
        Which pixel colors are similar enough to expand trimap into
    sample_gathering_angles: int
        In how many directions to search for new samples.
    sample_gathering_weights: Tuple[float, float, float, float]
        Weights for various cost functions
    sample_gathering_Np_radius: int
        Radius of Np function
    sample_refinement_radius: int
        Search region for better neighboring samples
    local_smoothing_radius1: int
        Radius for foreground/background smoothing
    local_smoothing_radius2: int
        Radius for confidence computation
    local_smoothing_radius3: int
        Radius for low frequency alpha computation
    local_smoothing_sigma_sq1: float
        Squared sigma value for foreground/background smoothing
        Defaults to :code:`(2 * local_smoothing_radius1 + 1)**2 / (9 * pi)` if not given
    local_smoothing_sigma_sq2: float
        Squared sigma value for confidence computation
    local_smoothing_sigma_sq3: float
        Squared sigma value for low frequency alpha computation
        Defaults to :code:`(2 * local_smoothing_radius3 + 1)**2 / (9 * pi)` if not given

    Returns
    -------
    alpha: numpy.ndarray
        Estimated alpha matte
    foreground: numpy.ndarray
        Estimated foreground
    background: numpy.ndarray
        Estimated background

    Example
    -------
    >>> from pymatting import *
    >>> image = load_image("data/lemur/lemur.png", "RGB")
    >>> trimap = load_image("data/lemur/lemur_trimap.png", "GRAY")
    >>> alpha, foreground, background = estimate_alpha_sm(
    ...     image,
    ...     trimap,
    ...     return_foreground_background=True,
    ...     sample_gathering_angles=4)
    z1image.dtype should be float32 or float64, but is z2trimap.dtype should be float32 or float64, but is N   zPimage height and width should match trimap height and width, but image shape is z and trimap shape is    z"image should be RGB, but shape is r
   g      "@r           )k_ik_cr	   Zaxis)
num_angleseNeAefeb	Np_radius)radius)radius1radius2radius3	sigma_sq1	sigma_sq2	sigma_sq3)dtypenpfloat32Zfloat64AssertionErrorshapelenpiZastypecopyexpand_trimapZmeanZ
zeros_likesample_gatheringsample_refinementlocal_smoothing)imagetrimapZreturn_foreground_backgroundZtrimap_expansion_radiusZtrimap_expansion_thresholdZsample_gathering_anglesZsample_gathering_weightsZsample_gathering_Np_radiusZsample_refinement_radiusZlocal_smoothing_radius1Zlocal_smoothing_radius2Zlocal_smoothing_radius3Zlocal_smoothing_sigma_sq1Zlocal_smoothing_sigma_sq2Zlocal_smoothing_sigma_sq3expanded_trimapZavg_FZavg_Bgathering_Fgathering_Bgathering_alphar   r   r   r   	refined_F	refined_Brefined_alphafinal_Ffinal_Bfinal_alpha r8   S/var/www/html/venv/lib/python3.8/site-packages/pymatting/alpha/estimate_alpha_sm.pyestimate_alpha_sm   s    L"",,








r:   zf4(f4[::1], f4[::1], f4[::1])T)cachenogilc                 C   s   |d |d  }|d |d  }|d |d  }| d |d  }| d |d  }| d |d  }|| ||  ||  d }	|| ||  ||  |	 }
t dtd|
}
|
S )Nr   r
   r   h㈵>r   r	   )maxmin)IFBZfb0Zfb1Zfb2Zib0Zib1Zib2denomalphar8   r8   r9   estimate_alpha   s    rE   zf4(f4[::1], f4[::1])c                 C   s.   d}t t| D ]}|| | ||  7 }q|S )Nr   )ranger%   )absir8   r8   r9   inner   s    rK   c                 C   s   t | ||}||d  d| |d   | d  }||d  d| |d   | d  }||d  d| |d   | d  }|| ||  ||  S )Nr   r	   r
   r   )rE   )r@   rA   rB   rG   Zd0Zd1d2r8   r8   r9   Mp2   s
    $$$rM   z/f4(f4[:, :, ::1], i8, i8, f4[::1], f4[::1], i8)c                 C   s   | j d d \}}d}t|| || d D ]`}	tdt|d |	}	t|| || d D ]0}
tdt|d |
}
|t| |	|
f ||7 }qZq,|S )Nr   r   r
   r   )r$   rF   r>   r?   rM   )r,   xyrA   rB   rhwresulty2x2r8   r8   r9   Np   s    rV   z!f4(f4[:, :, ::1], i8, i8, i8, i8)c                 C   sF  d}|| }|| }t ||}|dkr,dS tt |}	tdtd|	}	||	 }
||	 }| jd d \}}t|	d D ]}t|t||
  }t|t||
  }tdt|d |d }tdt|d |d }tdt|d |d }tdt|d |d }tdt|d |}tdt|d |}d| ||df | ||df   }d| ||df | ||df   }d| ||df | ||df   }d| ||df | ||df   }d| ||df | ||df   }d| ||df | ||df   }|
| ||  }|
| ||  }|
| ||  }|t 	|| ||  ||  7 }qx|S )Nr   r
   r   r   r   g      ?)
r!   hypotintceilr>   r?   r$   rF   floatsqrt)r,   ZpxpysxZsyrS   ZspxZspydZ	num_stepsZstep_xZstep_yrQ   rR   rJ   ZqxZqyZq_lZq_rZq_uZq_dZIx0ZIx1ZIx2ZIy0ZIy1ZIy2Zv0Zv1Zv2r8   r8   r9   Ep   s>           $r_   c                 C   s:   d}t | jd D ]}|| | ||  d 7 }qt|S )Nr   r   r   )rF   r$   r!   r[   )rG   rH   rL   rJ   r8   r8   r9   dist  s    r`   zf4(f4[::1])c                 C   s   t t| | S )N)r!   r[   rK   )rG   r8   r8   r9   length
  s    ra   z3void(f4[:, ::1], f4[:, ::1], f4[:, :, ::1], i8, f4))r;   parallelr<   c                 C   s  |j \}}t||fD ]n\}}|||f dks|||f dkrBqtj}	t|| || d D ]$}
t|| || d D ]}|dk sz||ksz|
dk sz|
|krqz||
|f dkr||
|f dkrqz|||df ||
|df  }|||df ||
|df  }|||df ||
|df  }t|| ||  ||  }t|| ||
 }||krVqz||krbqz||	k rz|}	||
|f | ||f< qzq^qd S )Nr   r
   r   )r$   r   r!   infrF   r[   rW   )r.   r-   r,   r   r   rQ   rR   rO   rN   ZclosestrT   rU   ZdrdgdbZcolor_distanceZspatial_distancer8   r8   r9   r(     s.    
      
 
 r(   zavoid(f4[:, :, ::1], f4[:, :, ::1], f4[:, ::1], f4[:, :, ::1], f4[:, ::1], i8, f4, f4, f4, f4, i8)c           0   
   C   st  |j \}}dt|| }t||fD ]H\}}tj|dftjd}tj|dftjd}tj|dftjd}tj|dftjd}|||f }|||f |||f< |||f dkr||||f< q$|||f dkr|| ||f< q$d}|| || |  }|d ||  }dtj ||  | }d}d}t|D ]@}dtj | | | }t	|}t
|}d	}d	}t|D ]}|r~|r~ q(t|||  } t|||  }!| dk s|!dk s| |ks|!|kr q(|s||!| f dkr||!| f ||< | ||df< |!||df< |d7 }d
}|sh||!| f dkrh||!| f ||< | ||df< |!||df< |d7 }d
}qhq(|dkr| ||f ||< |||df< |||df< |d7 }|dkr|||f ||< |||df< |||df< |d7 }tj}"tj}#t|D ]0}t|||||df ||df }$t|"|$}"qt|D ]0}%t|||||%df ||%df }&t|#|&}#q.|#|"|# d  }'tj}(t|D ]}t|D ]}%|| })||% }*t||)|*}+|'dd|'  |+  },t|||df  |||df  }-t|||%df  |||%df  }.t||||)|*|
| |,|  |-|  |.|	  }/|(|/kr|/}(|+|||f< |)| ||f< |*|||f< qq~q$d S )Nr   r   r    r   r
      i r   FTr=   r	   )r$   r>   r   r!   zerosr"   Zint32r&   rF   cossinrX   rc   r_   r?   rE   rW   rV   )0r/   r0   r1   r,   r-   r   r   r   r   r   r   rQ   rR   Z	max_stepsrO   rN   Z
fg_samplesZfg_samples_xyZ
bg_samplesZbg_samples_xyC_pnrJ   Zstart_angleZnum_fg_samplesZnum_bg_samplesZanglecrI   Zhas_fgZhas_bgsteprU   rT   Zmin_Ep_fZmin_Ep_bZEp_fjZEp_bZPF_pZmin_costrA   rB   alpha_pZApZDp_fZDp_bZg_pr8   r8   r9   r)   -  s    


 ( 

  $$
r)   zkvoid(f4[:, :, ::1], f4[:, :, ::1], f4[:, ::1], f4[:, :, ::1], f4[:, :, ::1], f4[:, :, ::1], f4[:, ::1], i8)c                 C   s  |j \}}	|| d d < ||d d < ||d d < t||	fD ]\}
}||
|f }||
|f dks:||
|f dkrrq:d}tj|dftjd}tj|dftjd}tj|tjd}tj|d d < t| |d D ]}t| |d D ]}|| }|
| }d|  kr
|	k rn qd|  kr$|k rn q|||f }|||f }t|||}t|}||| k r|||< |||< |||< qq|j	dd| }|j	dd| }|| |
|f< |||
|f< t
|||||
|f< q:d S )Nr   r
   r   rf   r   )r$   r   r!   rh   r"   rc   rF   rM   ZargmaxsumrE   )r2   r3   r4   r/   r0   r,   r-   r   rQ   rR   rO   rN   rk   Zmax_samplesZsample_FZsample_BZsample_costdydxrU   rT   ZF_qZB_qZcostrJ   ZF_meanZB_meanr8   r8   r9   r*     s>    
 4
r*   zvoid(f4[:, :, ::1], f4[:, :, ::1], f4[:, ::1], f4[:, :, ::1], f4[:, :, ::1], f4[:, ::1], f4[:, :, ::1], f4[:, ::1], i8, i8, i8, f4, f4, f4)c           +      C   s  |j \}}tj||ftjd}tj||ftjd}tj||ftjd}|| d d < ||d d < t||fD ]\}}|||f }|||f dksj|||f dkrqjtjdtjd}tjdtjd}d}d}|||f }t| |d D ]B}t| |d D ]*}|| }|| }d|  kr(|k rn qd|  krB|k rn qtd| || ||   }||ksx||kr|t|||f |||f  9 }|||f } ||  }!|d|   }"t|!d}!t|"d}"||!7 }||"7 }tdD ]B}#||#  |!||||#f  7  < ||#  |"||||#f  7  < qqq|| }|| }|| ||f< ||||f< t	||||||f< |d|  |||f< qjt||fD ]\}}|||f }|||f dks|||f dkr|||f |||f< qd}$d}%t|	 |	d D ]}t|	 |	d D ]}|| }|| }d|  kr4|k rn nVd|  krP|k rn n:|%|||f 7 }%|$|||f t
| ||f |||f  7 }$qq|$|%d  }$|$d7 }$t
| ||f |||f }&| ||f }|||f }td|&|$ td| tt|||  |||f< qt||fD ]\}}|||f dksP|||f dkrh|||f |||f< q"d}'d}%t|
 |
d D ]}t|
 |
d D ]}|| }|| }d|  kr|k rn nd|  kr|k rn np|| ||  }(|||f dkp|||f dk})td| || ||   |) }*|'|*|||f  7 }'|%|*7 }%qq|'|% |||f< |||f |||f  d|||f  |||f   |||f< q"d S )	Nrf   r   r
   r   r   g      r	   r=   )r$   r!   rh   r"   r   rF   expabsr>   rE   r`   r?   r[   rM   )+r5   r6   r7   r2   r3   r4   r,   r-   r   r   r   r   r   r   rQ   rR   Zfinal_confidenceZW_FBZlow_frequency_alpharO   rN   rk   ZF_pZB_pZsum_FZsum_Brp   rr   rs   rU   rT   ZWc_pqZalpha_qZW_FZW_Brm   ZD_FBZ
weight_sumZFB_distZ	alpha_sumZD_image_squaredZis_knownZW_alphar8   r8   r9   r+     s    
 4 

&$82:$8""r+   )Fr   r   r   r   r
   r   r   r   r   Nr   N)Znumbar   r   numpyr!   r:   rE   rK   rM   rV   r_   r`   ra   r(   r)   r*   r+   r8   r8   r8   r9   <module>   sN                
 $


	


-



 
6