a
    d.                     @   s   d dl Z d dlZd dlZd dlmZ d dlmZ	 d dl
mZ d dlmZmZ ddd	ZdddZdd Zdd Zdd Zdd Zdd Zd ddZd!ddZdS )"    N)path)
functionalmod_crop)
img2tensorscandirF   c                    s   t | tr| }nttt| dd}dd |D }|rH fdd|D }t|ddd}tj|dd}|r~d	d |D }||fS |S d
S )a  Read a sequence of images from a given folder path.

    Args:
        path (list[str] | str): List of image paths or image folder path.
        require_mod_crop (bool): Require mod crop for each image.
            Default: False.
        scale (int): Scale factor for mod_crop. Default: 1.
        return_imgname(bool): Whether return image names. Default False.

    Returns:
        Tensor: size (t, c, h, w), RGB, [0, 1].
        list[str]: Returned image name list.
    T)	full_pathc                 S   s"   g | ]}t |tjd  qS )g     o@)cv2ZimreadZastypenpfloat32).0v r   _/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/basicsr/data/data_util.py
<listcomp>       z read_img_seq.<locals>.<listcomp>c                    s   g | ]}t | qS r   r   )r   imgscaler   r   r       r   )Zbgr2rgbr   r   )Zdimc                 S   s    g | ]}t t |d  qS )r   )ospsplitextbasenamer   r   r   r   r   r   %   r   N)
isinstancelistsortedr   r   torchstack)r   Zrequire_mod_cropr   Zreturn_imgnameZ	img_pathsZimgsZimgnamesr   r   r   read_img_seq   s    
r   
reflectionc                 C   s  |d dksJ d|dv s,J d| d|d }|d }g }t | | | | d D ]}|dk r|dkrpd}q|d	kr| }q|d
kr| | | }q|| }nT||kr|dkr|}q|d	kr|d | }q|d
kr| | ||  }q|| }n|}|| qV|S )a  Generate an index list for reading `num_frames` frames from a sequence
    of images.

    Args:
        crt_idx (int): Current center index.
        max_frame_num (int): Max number of the sequence of images (from 1).
        num_frames (int): Reading num_frames frames.
        padding (str): Padding mode, one of
            'replicate' | 'reflection' | 'reflection_circle' | 'circle'
            Examples: current_idx = 0, num_frames = 5
            The generated frame indices under different padding mode:
            replicate: [0, 0, 0, 1, 2]
            reflection: [2, 1, 0, 1, 2]
            reflection_circle: [4, 3, 0, 1, 2]
            circle: [3, 4, 0, 1, 2]

    Returns:
        list[int]: A list of indices.
       r   z#num_frames should be an odd number.)	replicater    reflection_circleZcirclezWrong padding mode: .r   r"   r    r#   )rangeappend)Zcrt_idxZmax_frame_numZ
num_framespaddingZnum_padindicesiZpad_idxr   r   r   generate_frame_indices+   s2    

r*   c                 C   sr  t | dksJ dt |  t |dks<J dt | | \}}|\}}|dr`|dst| d| d| d| d| d| tt|d	}d
d |D }W d   n1 s0    Y  tt|d	}dd |D }W d   n1 s0    Y  t|t|kr0td| d| dn>g }	t|D ],}
|	t	| d|
f| d|
fg q<|	S dS )u  Generate paired paths from lmdb files.

    Contents of lmdb. Taking the `lq.lmdb` for example, the file structure is:

    lq.lmdb
    ├── data.mdb
    ├── lock.mdb
    ├── meta_info.txt

    The data.mdb and lock.mdb are standard lmdb files and you can refer to
    https://lmdb.readthedocs.io/en/release/ for more details.

    The meta_info.txt is a specified txt file to record the meta information
    of our datasets. It will be automatically created when preparing
    datasets by our provided dataset tools.
    Each line in the txt file records
    1)image name (with extension),
    2)image shape,
    3)compression level, separated by a white space.
    Example: `baboon.png (120,125,3) 1`

    We use the image name without extension as the lmdb key.
    Note that we use the same key for the corresponding lq and gt images.

    Args:
        folders (list[str]): A list of folder path. The order of list should
            be [input_folder, gt_folder].
        keys (list[str]): A list of keys identifying folders. The order should
            be in consistent with folders, e.g., ['lq', 'gt'].
            Note that this key is different from lmdb keys.

    Returns:
        list[str]: Returned path list.
    r!   GThe len of folders should be 2 with [input_folder, gt_folder]. But got >The len of keys should be 2 with [input_key, gt_key]. But got .lmdbz folder and z2 folder should both in lmdb formats. But received z: z; meta_info.txtc                 S   s   g | ]}| d d qS r$   r   splitr   liner   r   r   r      r   z*paired_paths_from_lmdb.<locals>.<listcomp>Nc                 S   s   g | ]}| d d qS r/   r0   r2   r   r   r   r      r   zKeys in z_folder and z_folder are different._path)
lenendswith
ValueErroropenr   joinsetr   r&   dict)folderskeysinput_folder	gt_folder	input_keygt_keyfinZinput_lmdb_keysZgt_lmdb_keyspathsZlmdb_keyr   r   r   paired_paths_from_lmdb_   s4    #,,*rD   c                 C   s   t | dksJ dt |  t |dks<J dt | | \}}|\}}t|d}dd |D }	W d   n1 sz0    Y  g }
|	D ]h}tt|\}}|| | }t||}t||}|
t| d|f| d|fg q|
S )	a}  Generate paired paths from an meta information file.

    Each line in the meta information file contains the image names and
    image shape (usually for gt), separated by a white space.

    Example of an meta information file:
    ```
    0001_s001.png (480,480,3)
    0001_s002.png (480,480,3)
    ```

    Args:
        folders (list[str]): A list of folder path. The order of list should
            be [input_folder, gt_folder].
        keys (list[str]): A list of keys identifying folders. The order should
            be in consistent with folders, e.g., ['lq', 'gt'].
        meta_info_file (str): Path to the meta information file.
        filename_tmpl (str): Template for each filename. Note that the
            template excludes the file extension. Usually the filename_tmpl is
            for files in the input folder.

    Returns:
        list[str]: Returned path list.
    r!   r+   r,   rc                 S   s   g | ]}|  d d qS ) r   )stripr1   r2   r   r   r   r      r   z4paired_paths_from_meta_info_file.<locals>.<listcomp>Nr4   )	r5   r8   r   r   r   formatr9   r&   r;   )r<   r=   Zmeta_info_filefilename_tmplr>   r?   r@   rA   rB   Zgt_namesrC   Zgt_namer   ext
input_name
input_pathgt_pathr   r   r    paired_paths_from_meta_info_file   s     ,(rN   c              	   C   s.  t | dksJ dt |  t |dks<J dt | | \}}|\}}tt|}tt|}t |t |ksJ | d| dt | dt | dg }	|D ]}
tt|
\}}|| | }t||}||v sJ | d| d	t||
}
|	t	| d
|f| d
|
fg q|	S )a.  Generate paired paths from folders.

    Args:
        folders (list[str]): A list of folder path. The order of list should
            be [input_folder, gt_folder].
        keys (list[str]): A list of keys identifying folders. The order should
            be in consistent with folders, e.g., ['lq', 'gt'].
        filename_tmpl (str): Template for each filename. Note that the
            template excludes the file extension. Usually the filename_tmpl is
            for files in the input folder.

    Returns:
        list[str]: Returned path list.
    r!   r+   r,   z and z+ datasets have different number of images: z, r$   z is not in z_paths.r4   )
r5   r   r   r   r   r   rH   r9   r&   r;   )r<   r=   rI   r>   r?   r@   rA   Zinput_pathsZgt_pathsrC   rM   r   rJ   rK   rL   r   r   r   paired_paths_from_folder   s,    
(rO   c                    s"   t t } fdd|D }|S )zGenerate paths from folder.

    Args:
        folder (str): Folder path.

    Returns:
        list[str]: Returned path list.
    c                    s   g | ]}t  |qS r   )r   r9   r   folderr   r   r      r   z%paths_from_folder.<locals>.<listcomp>)r   r   )rQ   rC   r   rP   r   paths_from_folder   s    
rR   c                 C   s\   |  dstd|  dtt| d}dd |D }W d   n1 sN0    Y  |S )zGenerate paths from lmdb.

    Args:
        folder (str): Folder path.

    Returns:
        list[str]: Returned path list.
    r-   zFolder zfolder should in lmdb format.r.   c                 S   s   g | ]}| d d qS r/   r0   r2   r   r   r   r     r   z#paths_from_lmdb.<locals>.<listcomp>N)r6   r7   r8   r   r9   )rQ   rB   rC   r   r   r   paths_from_lmdb   s
    	
,rS      皙?c                 C   s:   ddl m} t| | f}d|| d | d f< |||S )zGenerate Gaussian kernel used in `duf_downsample`.

    Args:
        kernel_size (int): Kernel size. Default: 13.
        sigma (float): Sigma of the Gaussian kernel. Default: 1.6.

    Returns:
        np.array: The Gaussian kernel.
    r   )filtersr   r!   )Zscipy.ndimagerV   r   zerosgaussian_filter)kernel_sizesigmarV   kernelr   r   r   generate_gaussian_kernel	  s    
r\      c              	   C   s  |dv sJ d| dd}| j dkr4d}| d} |  \}}}}}| dd	||} |d
 |d
  |d
 |d
   }	}
t| |	|	|
|
fd} t|d| }t|	| dd}tj
| ||d} | ddddd
dd
df } | |||| d
| d} |r| d} | S )ab  Downsamping with Gaussian kernel used in the DUF official code.

    Args:
        x (Tensor): Frames to be downsampled, with shape (b, t, c, h, w).
        kernel_size (int): Kernel size. Default: 13.
        scale (int): Downsampling factor. Supported scale: (2, 3, 4).
            Default: 4.

    Returns:
        Tensor: DUF downsampled frames.
    )r!      r]   z&Only support scale (2, 3, 4), but got r$   Fr]   Tr   r   r!   Zreflectg?)ZstrideNr^   )ndimZ	unsqueezesizeviewFpadr\   r   Z
from_numpyZtype_asZconv2dZsqueeze)xrY   r   Zsqueeze_flagbtchwZpad_wZpad_hrX   r   r   r   duf_downsample  s"    

" 
rl   )Fr   F)r    )rT   rU   )rT   r]   )r
   numpyr   r   osr   r   Ztorch.nnr   rd   Zbasicsr.data.transformsr   Zbasicsr.utilsr   r   r   r*   rD   rN   rO   rR   rS   r\   rl   r   r   r   r   <module>   s   
 
4;,$
