o
    Wi                     @   sd   d dl mZ d dlmZmZmZ d dlZd dlZdZ	dd Z
dd Zd	d
 Zdedd fddZdS )    )Path)ImageImageOpsImageFilterNi  c                 C   sX   t | ttfrtt| d}|S t | tr%tt| d}|S | d}|S )NRGB)	
isinstancestrr   r   openconvertbytesioBytesIO)img_or_pathimg r   1/var/www/html/id_ocr_project_final/ocr/preproc.py_ensure_pil   s   

r   c                 C   sP   | j \}}t||}|tk r&t| }t|| t|| f}| |tjjS | S )N)sizemaxMIN_SIDEintresizer   
ResamplingLANCZOS)pil_imgwhmax_sidescalenew_sizer   r   r   _resize_if_small   s   

r    c                 C   s  t | }|tjdd}t |}t|tj	}tj
| ddd\}}|j}td|  }d}d}d}	d}
tdD ];}||| 7 }|dkrMq@|| }|dkrW n%||||  7 }|| }|| | }|| || d  }||	kr{|}	|}
q@||
ktj	d	 }t|}|S )
N   )r      )r   r"   )binsranger            )r   	grayscalefilterr   
ModeFilterautocontrastnparrayastypeuint8	histogramflattenr   arangesumr$   r   	fromarray)r   grayarrhist_total	sum_totalsumBwBmax_var	thresholdiwFmBmFvar_betweenbwpil_bwr   r   r   _to_bw   s6   



rF   Fzdata/output/debug_imagesc           	      C   sd   t | }t|}t|}t|}t|}|r,|jddd ||dd }|| ||||fS )NT)parentsexist_ok05dz.png)r   r    rF   r,   r-   mkdirsave)	path_or_pil
save_debug	debug_diridxpil_rgbrE   np_rgbnp_gray
debug_pathr   r   r   
preprocess6   s   


rT   )pathlibr   PILr   r   r   numpyr,   r   r   r   r    rF   rT   r   r   r   r   <module>   s    		