o
    Me41                     @   s  d Z ddlmZ ddlZddlZejrcddlZddlZddl	Z	ej
Zejdkr3devr3eje	j d ZejeddgejejdZe \ZZe ZedkrQdZn$zddlZW n eyb   dZY nw zddlZW n eyt   dZY nw ddl	Z	ddlZddlm  mZ g Zd	d
 Z	d"ddZ d#ddZ!d#ddZ"dd Z#d$ddZ$d#ddZ%d#ddZ&d#ddZ'		d%ddZ(		d%d d!Z)dS )&at  
This file contains some common interfaces for image preprocess.
Many users are confused about the image layout. We introduce
the image layout as follows.

- CHW Layout

  - The abbreviations: C=channel, H=Height, W=Width
  - The default layout of image opened by cv2 or PIL is HWC.
    PaddlePaddle only supports the CHW layout. And CHW is simply
    a transpose of HWC. It must transpose the input image.

- Color format: RGB or BGR

  OpenCV use BGR color format. PIL use RGB color format. Both
  formats can be used for training. Noted that, the format should
  be keep consistent between the training and inference period.
    )print_functionNwin32z
python.exez-cz
import cv2)stdoutstderrc                  C   s$   t d u rdd l} | jd dS dS )Nr   zWarning with paddle image module: opencv-python should be imported,
         or paddle image module could NOT work; please install opencv-python first.FT)cv2sysr   write)r    r	   DD:\Projects\ConvertPro\env\Lib\site-packages\paddle/dataset/image.py
_check_cv2H   s   r      c              	   C   s  | d }d||t  f }d||t  f }t j|r|S t | t| }| }g }	g }
d}|D ]@}|j|v rt|		|
|  |
	||j  t|	|krti }|
|d< |	|d< tj|td||f dd	d
 |d7 }g }	g }
q4t|	dkri }|
|d< |	|d< tj|td||f dd	d
 t|d }t |D ]}|t jd||f d  qW d   |S 1 sw   Y  |S )a  
    Read images from tar file and batch them into batch file.

    :param data_file: path of image tar file
    :type data_file: string
    :param dataset_name: 'train','test' or 'valid'
    :type dataset_name: string
    :param img2label: a dic with image file name as key
                    and image's label as value
    :type img2label: dic
    :param num_per_batch: image number per batch file
    :type num_per_batch: int
    :return: path of list file containing paths of batch file
    :rtype: string
    Z_batchz%s/%s_%sz%s/%s_%s.txtr   labeldataz%s/batch_%dwb   )protocol   az%s/%s
N)osgetpidpathexistsmakedirstarfileopen
getmembersnameappendextractfilereadlenpickledumplistdirr   abspath)Z	data_fileZdataset_nameZ	img2labelZnum_per_batchZ	batch_dirZout_pathZ	meta_filetfZmemsr   labelsZfile_idZmemoutputmetafiler	   r	   r
   batch_images_from_tarT   sV   


 
r+   Tc                 C   s>   t  du sJ |rdnd}tjt| tjd}t||}|S )a  
    Load an color or gray image from bytes array.

    Example usage:

    .. code-block:: python

        with open('cat.jpg') as f:
            im = load_image_bytes(f.read())

    :param bytes: the input image bytes array.
    :type bytes: str
    :param is_color: If set is_color True, it will load and
                     return a color image. Otherwise, it will
                     load and return a gray image.
    :type is_color: bool
    Tr   r   Zdtype)r   npZasarray	bytearrayZuint8r   Zimdecode)bytesis_colorflagZ
file_bytesZimgr	   r	   r
   load_image_bytes   s
   r2   c                 C   s*   t  du sJ |rdnd}t| |}|S )a  
    Load an color or gray image from the file path.

    Example usage:

    .. code-block:: python

        im = load_image('cat.jpg')

    :param file: the input image path.
    :type file: string
    :param is_color: If set is_color True, it will load and
                     return a color image. Otherwise, it will
                     load and return a gray image.
    :type is_color: bool
    Tr   r   )r   r   Zimread)r*   r0   r1   imr	   r	   r
   
load_image   s   r4   c                 C   sf   t  du sJ | jdd \}}||}}||kr || | }n|| | }tj| ||ftjd} | S )aW  
    Resize an image so that the length of shorter edge is size.

    Example usage:

    .. code-block:: python

        im = load_image('cat.jpg')
        im = resize_short(im, 256)

    :param im: the input image with HWC layout.
    :type im: ndarray
    :param size: the shorter edge size of image after resizing.
    :type size: int
    TNr   )interpolation)r   shaper   resizeZINTER_CUBIC)r3   sizehwZh_newZw_newr	   r	   r
   resize_short   s   
r;   r   r   r   c                 C   s$   t | jt |ksJ | |} | S )a  
    Transpose the input image order. The image layout is HWC format
    opened by cv2 or PIL. Transpose the input image to CHW layout
    according the order (2,0,1).

    Example usage:

    .. code-block:: python

        im = load_image('cat.jpg')
        im = resize_short(im, 256)
        im = to_chw(im)

    :param im: the input image with HWC layout.
    :type im: ndarray
    :param order: the transposed order.
    :type order: tuple|list
    )r!   r6   Z	transpose)r3   orderr	   r	   r
   to_chw   s   
r>   c           	      C   sv   | j dd \}}|| d }|| d }|| || }}|r/| ||||ddf } | S | ||||f } | S )aP  
    Crop the center of image with size.

    Example usage:

    .. code-block:: python

        im = center_crop(im, 224)

    :param im: the input image with HWC layout.
    :type im: ndarray
    :param size: the cropping size.
    :type size: int
    :param is_color: whether the image is color or not.
    :type is_color: bool
    Nr   )r6   	r3   r8   r0   r9   r:   Zh_startZw_startZh_endZw_endr	   r	   r
   center_crop   s   r@   c           	      C   s   | j dd \}}tjd|| d }tjd|| d }|| || }}|r9| ||||ddf } | S | ||||f } | S )aQ  
    Randomly crop input image with size.

    Example usage:

    .. code-block:: python

        im = random_crop(im, 224)

    :param im: the input image with HWC layout.
    :type im: ndarray
    :param size: the cropping size.
    :type size: int
    :param is_color: whether the image is color or not.
    :type is_color: bool
    Nr   r   r   )r6   r-   randomrandintr?   r	   r	   r
   random_crop  s   rC   c                 C   sD   t | jdkr|r| dddddddf S | dddddf S )aW  
    Flip an image along the horizontal direction.
    Return the flipped image.

    Example usage:

    .. code-block:: python

        im = left_right_flip(im)

    :param im: input image with HWC layout or HW layout for gray image
    :type im: ndarray
    :param is_color: whether input image is color or not
    :type is_color: bool
       N)r!   r6   )r3   r0   r	   r	   r
   left_right_flip5  s   rF   c                 C   s   t | |} |rt| ||d} tjddkrt| |} nt| ||d} t| jdkr.t	| } | 
d} |duritj|tjd}|jdkrR|rR|ddtjtjf }n|jdkrZ|}nt|jt| kseJ | |8 } | S )	a  
    Simply data argumentation for training. These operations include
    resizing, croping and flipping.

    Example usage:

    .. code-block:: python

        im = simple_transform(im, 256, 224, True)

    :param im: The input image with HWC layout.
    :type im: ndarray
    :param resize_size: The shorter edge length of the resized image.
    :type resize_size: int
    :param crop_size: The cropping size.
    :type crop_size: int
    :param is_train: Whether it is training or not.
    :type is_train: bool
    :param is_color: whether the image is color or not.
    :type is_color: bool
    :param mean: the mean values, which can be element-wise mean values or
                 mean values per channel.
    :type mean: numpy array | list
    )r0   r   r   rD   float32Nr,   r   )r;   rC   r-   rA   rB   rF   r@   r!   r6   r>   ZastypearrayrG   ndimZnewaxis)r3   resize_size	crop_sizeis_trainr0   meanr	   r	   r
   simple_transformK  s&   



rN   c                 C   s    t | |}t||||||}|S )aJ  
    Load image from the input file `filename` and transform image for
    data argumentation. Please refer to the `simple_transform` interface
    for the transform operations.

    Example usage:

    .. code-block:: python

        im = load_and_transform('cat.jpg', 256, 224, True)

    :param filename: The file name of input image.
    :type filename: string
    :param resize_size: The shorter edge length of the resized image.
    :type resize_size: int
    :param crop_size: The cropping size.
    :type crop_size: int
    :param is_train: Whether it is training or not.
    :type is_train: bool
    :param is_color: whether the image is color or not.
    :type is_color: bool
    :param mean: the mean values, which can be element-wise mean values or
                 mean values per channel.
    :type mean: numpy array | list
    )r4   rN   )filenamerJ   rK   rL   r0   rM   r3   r	   r	   r
   load_and_transform  s   
rP   )r   )T)r<   )TN)*__doc__
__future__r   sixnumpyr-   PY3
subprocessr   r   
executableinterpreterplatformexec_prefixsepPopenPIPEZimport_cv2_proccommunicateouterrpollretcoder   ImportErrorr   Zsix.moves.cPicklemovescPickler"   __all__r   r+   r2   r4   r;   r>   r@   rC   rF   rN   rP   r	   r	   r	   r
   <module>   sb   

=





<