a
    d3                     @   sz   d dl Z d dlZd dlZd dlZd dlZd dlmZ dddZdej	dfddZ
dd	d
ZdddZdddZdd ZdS )    N)	make_gridTc                    s8   dd  t | tr( fdd| D S  | S dS )aO  Numpy array to tensor.

    Args:
        imgs (list[ndarray] | ndarray): Input images.
        bgr2rgb (bool): Whether to change bgr to rgb.
        float32 (bool): Whether to change to float32.

    Returns:
        list[tensor] | tensor: Tensor images. If returned results only have
            one element, just return tensor.
    c                 S   sX   | j d dkr4|r4| jdkr&| d} t| tj} t| ddd} |rT| 	 } | S )N      float64float32r      )
shapeZdtypeastypecv2cvtColorZCOLOR_BGR2RGBtorchZ
from_numpy	transposefloat)imgbgr2rgbr    r   _/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/basicsr/utils/img_util.py	_totensor   s    

zimg2tensor.<locals>._totensorc                    s   g | ]} |qS r   r   ).0r   r   r   r   r   r   
<listcomp>!       zimg2tensor.<locals>.<listcomp>N
isinstancelist)imgsr   r   r   r   r   
img2tensor	   s    

r   r   r   c              	   C   s  t | s8t| tr&tdd | D s8tdt|  t | rH| g} g }| D ]4}|d 	 
 j| }||d  |d |d   }| }|dkrt|tt|ddd }|dd	d}|rt|tj}nx|d
kr8| }|dd	d}|jd	 dkr"tj|d	d}n|rZt|tj}n"|d	krL| }ntd| |tjkrr|d  }||}|| qPt|dkr|d }|S )aT  Convert torch Tensors into image numpy arrays.

    After clamping to [min, max], values will be normalized to [0, 1].

    Args:
        tensor (Tensor or list[Tensor]): Accept shapes:
            1) 4D mini-batch Tensor of shape (B x 3/1 x H x W);
            2) 3D Tensor of shape (3/1 x H x W);
            3) 2D Tensor of shape (H x W).
            Tensor channel should be in RGB order.
        rgb2bgr (bool): Whether to change rgb to bgr.
        out_type (numpy type): output types. If ``np.uint8``, transform outputs
            to uint8 type with range [0, 255]; otherwise, float type with
            range [0, 1]. Default: ``np.uint8``.
        min_max (tuple[int]): min and max values for clamp.

    Returns:
        (Tensor or list): 3D ndarray of shape (H x W x C) OR 2D ndarray of
        shape (H x W). The channel order is BGR.
    c                 s   s   | ]}t |V  qd S )N)r   	is_tensor)r   tr   r   r   	<genexpr>;   r   ztensor2img.<locals>.<genexpr>z(tensor or list of tensors expected, got r   r      F)Znrow	normalizer   r   )Zaxisz?Only support 4D, 3D or 2D tensor. But received with dimension:      o@)r   r   r   r   all	TypeErrortypesqueezer   detachcpuclamp_Zdimr   intmathsqrtsizenumpyr   r
   r   COLOR_RGB2BGRr   npuint8roundr	   appendlen)tensorrgb2bgrZout_typemin_maxresultZ_tensorZn_dimimg_npr   r   r   
tensor2img&   s>    &

"



r;   c                 C   sh   |  d j| ddd}||d  |d |d   d }|tj  }|rdt	
|t	j}|S )aQ  This implementation is slightly faster than tensor2img.
    It now only supports torch tensor with shape (1, c, h, w).

    Args:
        tensor (Tensor): Now only support torch tensor with (1, c, h, w).
        rgb2bgr (bool): Whether to change rgb to bgr. Default: True.
        min_max (tuple[int]): min and max values for clamp.
    r   r   r      )r'   r(   r*   Zpermuter&   r   r2   r)   r/   r
   r   r0   )r6   r7   r8   outputr   r   r   tensor2img_fasta   s    	 r>   colorFc                 C   sH   t | t j}tjtjtjd}t||| }|rD|t j	d }|S )a  Read an image from bytes.

    Args:
        content (bytes): Image bytes got from files or other streams.
        flag (str): Flags specifying the color type of a loaded image,
            candidates are `color`, `grayscale` and `unchanged`.
        float32 (bool): Whether to change to float32., If True, will also norm
            to [0, 1]. Default: False.

    Returns:
        ndarray: Loaded image array.
    )r?   Z	grayscaleZ	unchangedr#   )
r1   Z
frombufferr2   r
   ZIMREAD_COLORZIMREAD_GRAYSCALEZIMREAD_UNCHANGEDZimdecoder	   r   )contentflagr   r:   Zimread_flagsr   r   r   r   imfrombytesr   s    rB   c                 C   sD   |r&t jt j|}t j|dd t|| |}|s@tddS )ay  Write image to file.

    Args:
        img (ndarray): Image array to be written.
        file_path (str): Image file path.
        params (None or list): Same as opencv's :func:`imwrite` interface.
        auto_mkdir (bool): If the parent folder of `file_path` does not exist,
            whether to create it automatically.

    Returns:
        bool: Successful or not.
    T)exist_okzFailed in writing images.N)ospathabspathdirnamemakedirsr
   imwriteIOError)r   	file_pathparamsZ
auto_mkdirdir_nameokr   r   r   rI      s    rI   c                    sF    dkr| S t | tr( fdd| D S |       df S dS )zCrop borders of images.

    Args:
        imgs (list[ndarray] | ndarray): Images with shape (h, w, c).
        crop_border (int): Crop border for each end of height and weight.

    Returns:
        list[ndarray]: Cropped images.
    r   c                    s&   g | ]}|      d f qS ).r   )r   vcrop_borderr   r   r      r   zcrop_border.<locals>.<listcomp>.Nr   )r   rQ   r   rP   r   rQ      s
    

rQ   )TT)Tr   )r?   F)NT)r
   r,   r/   r1   rD   r   Ztorchvision.utilsr   r   r2   r;   r>   rB   rI   rQ   r   r   r   r   <module>   s   
;


