a
    Ad                     @   s2   d dl mZmZmZ d	ddZdd Zdd ZdS )
    )ImageImageFilterImageOpsc           	      C   s&  | j \}}d}t|D ](}| dd|f dk s6 q@|d7 }qd}tt|D ](}| dd|f dk sp qz|d7 }qPd}t|D ] }| | dk s q|d7 }qd}tt|D ] }| | dk s q|d7 }qtt|| dtt|| dtt|| | |tt|| | |fS )zfinds a rectangular region that contains all masked ares in an image. Returns (x1, y1, x2, y2) coordinates of the rectangle.
    For example, if a user has painted the top-right part of a 512x512 image", the result may be (256, 0, 512, 256)r   N   )shaperangeallreversedintmaxmin)	maskpadhw	crop_lefti
crop_rightcrop_topcrop_bottom r   7/var/www/html/stable-diffusion-webui/modules/masking.pyget_crop_region   s4    




r   c                 C   s8  | \}}}}|| ||  }	|| }
|	|
kr|| |
 }t |||  }||d 8 }|||d  7 }||kr|| }||8 }||8 }|dk r||8 }||8 }||kr|}n|| |
 }t |||  }||d 8 }|||d  7 }||kr|| }||8 }||8 }|dk r||8 }||8 }||kr,|}||||fS )a	  expands crop region get_crop_region() to match the ratio of the image the region will processed in; returns expanded region
    for example, if user drew mask in a 128x32 region, and the dimensions for processing are 512x512, the region will be expanded to 128x128.   r   )r
   )crop_regionZprocessing_widthZprocessing_heightimage_widthimage_heightx1y1x2y2Zratio_crop_regionZratio_processingZdesired_heightZdesired_height_diffdiffZdesired_widthZdesired_width_diffr   r   r   expand_crop_region*   s>    


r"   c                 C   s   t d| j| jf}t d| j| jf}|j| ddt|dd |d}dD ]6\}}|t	
|d}t|D ]}|| qq\|dS )zPfills masked regions with colors from image using blur. Not extremely effective.RGBARGBaL)r   ))   r   )@   r   )   r   )   r)   )r   r   )r   r   RGB)r   newwidthheightpasteconvertr   invertfilterr   GaussianBlurr   alpha_composite)imager   Z	image_modimage_maskedradiusrepeatsblurred_r   r   r   fillS   s    &
r:   N)r   )PILr   r   r   r   r"   r:   r   r   r   r   <module>   s   
&)