
    Q/Phc                        d Z ddlmZmZmZ ddlZddlZddlmZm	Z	 	 ej
        j        Zn# e$ r
 ej        ZY nw xY wdZ	 d Z G d d          Z	 dd	lmZ ed
         Zn# e$ r eZY nw xY w	 ddlZej        j        ej                 Zn# eef$ r eZY nw xY wej        dk    rOej        dk    rej        dk    rddlmZ nddlmZ 	 eegef         Zeej        gef         Zn# e $ r eZeZY nw xY wd Z!d Z"d Z#d'dZ$dej%        fdZ&d(dZ'd(dZ(d'dZ)d'dZ*d)dZ+d*dZ, G d d           Z-d! Z.d" Z/	 	 	 	 	 d+d&Z0dS ),a  
Perceptual image hashing library

Example:

>>> from PIL import Image
>>> import imagehash
>>> hash = imagehash.average_hash(Image.open('test.png'))
>>> print(hash)
d879f8f89b1bbf
>>> otherhash = imagehash.average_hash(Image.open('other.bmp'))
>>> print(otherhash)
ffff3720200ffff
>>> print(hash == otherhash)
False
>>> print(hash - otherhash)
36
>>> for r in range(1, 30, 5):
...	rothash = imagehash.average_hash(Image.open('test.png').rotate(r))
...	print('Rotation by %d: %d Hamming difference' % (r, hash - rothash))
...
Rotation by 1: 2 Hamming difference
Rotation by 6: 11 Hamming difference
Rotation by 11: 13 Hamming difference
Rotation by 16: 17 Hamming difference
Rotation by 21: 19 Hamming difference
Rotation by 26: 21 Hamming difference
>>>
    )absolute_importdivisionprint_functionN)ImageImageFilterz4.3.1c                    d                     d d|                                 z  D                       }t          t          j        t          |          dz                      }d                    t          |d          |          S )zA
	internal function to make a hex string out of a binary array.
	 c              3   4   K   | ]}t          |          V  d S Nstr).0bs     R/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/imagehash/__init__.py	<genexpr>z'_binary_array_to_hex.<locals>.<genexpr>U   s(      88c!ff888888          z{:0>{width}x}   width)joinflattenintnumpyceillenformat)arr
bit_stringr   s      r   _binary_array_to_hexr!   Q   sv     gg88a#++--&788888	UZJ!+,,	-	-s:q11???r   c                   B    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
S )	ImageHashzH
	Hash encapsulation. Can be used for dictionary keys and comparisons.
	c                     || _         d S r   hash)selfbinary_arrays     r   __init__zImageHash.__init___   s    $)))r   c                 N    t          | j                                                  S r   )r!   r&   r   r'   s    r   __str__zImageHash.__str__c   s    	di//11	2	22r   c                 *    t          | j                  S r   )reprr&   r+   s    r   __repr__zImageHash.__repr__f   s    	dir   c                 .   |t          d          | j        j        |j        j        k    r%t          d| j        j        |j        j                  t	          j        | j                                        |j                                        k              S )NzOther hash must not be None.z&ImageHashes must be of the same shape.)	TypeErrorr&   sizeshaper   count_nonzeror   r'   others     r   __sub__zImageHash.__sub__i   sw    
]	1	2	22	Y^uz&&	;TY_ejN^	_	__		TY..00EJ4F4F4H4HH	I	IIr   c                     |dS t          j        | j                                        |j                                                  S NFr   array_equalr&   r   r5   s     r   __eq__zImageHash.__eq__q   s;    
]
%		49,,..
0B0B0D0D	E	EEr   c                     |dS t          j        | j                                        |j                                                   S r9   r:   r5   s     r   __ne__zImageHash.__ne__w   s>    
]
%ty0022EJ4F4F4H4HII	IIr   c                 |    t          d t          | j                                                  D                       S )Nc                 (    g | ]\  }}|d |dz  z  S )r       r   ivs      r   
<listcomp>z&ImageHash.__hash__.<locals>.<listcomp>   s)    IIITQqIa!a%jIIIr   )sum	enumerater&   r   r+   s    r   __hash__zImageHash.__hash__}   s5    	IIYty/@/@/B/B%C%CIII	J	JJr   c                     | j         j        S r   )r&   r2   r+   s    r   __len__zImageHash.__len__   s    	r   N)__name__
__module____qualname____doc__r)   r,   r/   r7   r<   r>   rI   rK   rB   r   r   r#   r#   Z   s           3 3 3  J J JF F FJ J JK K K    r   r#   )Literal)haardb4)   rS   )rS   	   r   )rS   rT   r   )Callablec                 h   t          t          j        t          |           dz                      d                    t          | d          z            fdt          dt                              D             }t          j        d |D                       }t          |          S )aE  
	Convert a stored hash (hex, as retrieved from str(Imagehash))
	back to a Imagehash object.

	Notes:
	1. This algorithm assumes all hashes are either
			bidimensional arrays with dimensions hash_size * hash_size,
			or onedimensional arrays with dimensions binbits * 14.
	2. This algorithm does not work for hash_size < 2.
	r   {:0>{width}b}   r   c                 *    g | ]}||z            S rB   rB   )r   rD   r(   	hash_sizes     r   rF   zhex_to_hash.<locals>.<listcomp>   s&    [[[q\!A	M/*[[[r   r   c                 &    g | ]}d  |D             S )c                 F    g | ]}t          t          |                    S rB   boolr   r   ds     r   rF   z*hex_to_hash.<locals>.<listcomp>.<listcomp>   s$    666QDQLL666r   rB   )r   rows     r   rF   zhex_to_hash.<locals>.<listcomp>   s'    KKK366#666KKKr   )r   r   sqrtr   r   rangearrayr#   )hexstrbit_rows
hash_arrayr(   rZ   s      @@r   hex_to_hashrh      s     CKK!O,,--&&s62i)>S&TT[[[[[E!S=N=NPY4Z4Z[[[kKK(KKKLL*r   c                 
   t          t          |           dz  |z            }d                    t          | d          ||z            }t          j        d |D             g          | |z  d          }t          |          S )Nr   rW   rX   r   c                 F    g | ]}t          t          |                    S rB   r]   r_   s     r   rF   z#hex_to_flathash.<locals>.<listcomp>   s$    ???QDQLL???r   )r   r   r   r   rd   r#   )re   hashsizerZ   r(   rg   s        r   hex_to_flathashrl      s    VqH-..&&s62i(>R&SSk??,???@AA9*xBWBXBXY*r   c                 b    |                      d          }d |D             }t          |          S )a  
	Convert a stored multihash (hex, as retrieved from str(ImageMultiHash))
	back to an ImageMultiHash object.

	This function is based on hex_to_hash so the same caveats apply. Namely:

	1. This algorithm assumes all hashes are either
			bidimensional arrays with dimensions hash_size * hash_size,
			or onedimensional arrays with dimensions binbits * 14.
	2. This algorithm does not work for hash_size < 2.
	,c                 ,    g | ]}t          |          S rB   )rh   r   xs     r   rF   z$hex_to_multihash.<locals>.<listcomp>   s    
)
)
)a;q>>
)
)
)r   )splitImageMultiHash)re   rr   hashess      r   hex_to_multihashru      s6     
c		
)
)5
)
)
)vr   rA   c                    g }||dz  z  }t          |           |k    r$d}t          |                    |                    t          |dz            D ]V}| |dz  |dz  dz            }t	          d|z   d          |                    fdt          d          D                        Wt          t          j        |                    S )a
  
	Convert a stored hash (hex, as retrieved from str(Imagehash))
	back to a Imagehash object. This method should be used for
	hashes generated by ImageHash up to version 3.7. For hashes
	generated by newer versions of ImageHash, hex_to_hash should
	be used instead.
	r   zExpected hex string size of {}.r   0xrX   c                 (    g | ]}d |z  z  dk    S )r   r   rB   rC   s     r   rF   z#old_hex_to_hash.<locals>.<listcomp>   s%    ---qa!Q$hl---r   rA   )	r   
ValueErrorr   rc   r   appendr#   r   rd   )re   rZ   r   countemsgrD   hrE   s          @r   old_hex_to_hashr~      s     
	i1n	%KK5	*$4;;u%%&&&



 / /QQU1q519_!	$(B!**----E!HH---....%+c""###r   c                     |dk     rt          d          |                     d                              ||ft                    } t	          j        |           } ||          }||k    }t          |          S )a  
	Average Hash computation

	Implementation follows http://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html

	Step by step explanation: https://web.archive.org/web/20171112054354/https://www.safaribooksonline.com/blog/2013/11/26/image-hashing-with-python/ # noqa: E501

	@image must be a PIL instance.
	@mean how to determine the average luminescence. can try numpy.median instead.
	r   ,Hash size must be greater than or equal to 2Lry   convertresize	ANTIALIASr   asarrayr#   )imagerZ   meanpixelsavgdiffs         r   average_hashr      sy     MMABBB 
s			"	"Iy#99	E	E -

tF|| 	$r   r   c                    |dk     rt          d          ddl}||z  }|                     d                              ||ft                    } t          j        |           }|j                            |j                            |d          d          }|d|d|f         }t          j	        |          }||k    }	t          |	          S )
	Perceptual Hash computation.

	Implementation follows http://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html

	@image must be a PIL instance.
	r   r   r   Nr   )axisr   )ry   scipy.fftpackr   r   r   r   r   fftpackdctmedianr#   )
r   rZ   highfreq_factorscipyimg_sizer   r   
dctlowfreqmedr   s
             r   phashr     s     MMABBB'	s			"	"Hh#7	C	C
-

}**6*::CC*9*jyj()|JS$r   c                 D   ddl }||z  }|                     d                              ||ft                    } t	          j        |           }|j                            |          }|d|d|dz   f         }|                                }||k    }	t          |	          S )r   r   Nr   r   )
r   r   r   r   r   r   r   r   r   r#   )
r   rZ   r   r   r   r   r   r   r   r   s
             r   phash_simpler     s     '	s			"	"Hh#7	C	C
-

}  *9*a	Ao-.S$r   c                    |dk     rt          d          |                     d                              |dz   |ft                    } t	          j        |           }|ddddf         |ddddf         k    }t          |          S )z
	Difference Hash computation.

	following http://www.hackerfactor.com/blog/index.php?/archives/529-Kind-of-Like-That.html

	computes differences horizontally

	@image must be a PIL instance.
	r   r   r   r   Nr   r   rZ   r   r   s       r   dhashr   /  s     MMABBB	s			"	"IM9#=y	I	I
-

qqq!""uqqq#2#v&$r   c                     |                      d                              ||dz   ft                    } t          j        |           }|ddddf         |ddddf         k    }t          |          S )z
	Difference Hash computation.

	following http://www.hackerfactor.com/blog/index.php?/archives/529-Kind-of-Like-That.html

	computes differences vertically

	@image must be a PIL instance.
	r   r   Nr   )r   r   r   r   r   r#   r   s       r   dhash_verticalr   E  ss     
s			"	"Iy1}#=y	I	I
-

qrr111ussAAAv&$r   rQ   Tc                 `   ddl }|||dz
  z  dk    s
J d            nFdt          t          j        t	          | j                                      z  }t          ||          }t          t          j        |                    }t          t          j        |                    }||dz
  z  dk    s
J d            ||k    s
J d            ||z
  }	|                     d                              ||ft                    } t          j
        |           d	z  }
|rM|                    |
d
|          }t          |          }|dxx         dz  cc<   |                    |d
          }
|                    |
||	          }|d         }t          j        |          }||k    }t          |          S )a  
	Wavelet Hash computation.

	based on https://www.kaggle.com/c/avito-duplicate-ads-detection/

	@image must be a PIL instance.
	@hash_size must be a power of 2 and less than @image_scale.
	@image_scale must be power of 2 and less than image size. By default is equal to max
					power of 2 for an input image.
	@mode (see modes in pywt library):
					'haar' - Haar wavelets, by default
					'db4' - Daubechies wavelets
	@remove_max_haar_ll - remove the lowest low level (LL) frequency using Haar wavelet.
	r   Nr   zimage_scale is not power of 2r   zhash_size is not power of 2zhash_size in a wrong ranger   g     o@rQ   )level)pywtr   r   log2minr2   maxr   r   r   r   wavedec2listwaverec2r   r#   )r   rZ   image_scalemoderemove_max_haar_llr   image_natural_scalell_max_levelr   	dwt_levelr   coeffsdwt_lowr   r   s                  r   whashr   X  s     	a	(A	-	-	-/N	-	-	-	-3uz#ej//::;;;'33+EJ{++,,	UZ	""	#	#Y]#q(((*G(((;E!	s			"	"K#=y	I	I
-


%  )==|=<<&<<&)))q.)))==((& --I-
6
6!9 |G#$r   rS   c           
         t          j        |                     d                                                    }d |                     d                                          D             \  }}|dk     }|                                }|dk     }t          j        | |                                          }t          j        | |           }	t          j        |	|dk               }
t          j        |	|dk              }t          d|	                                          }t          j	        dd	d
          }|

                                r t          j        ||
         |          \  }}n$t          j        t          |          dz
            }|
                                r t          j        ||         |          \  }}n$t          j        t          |          dz
            }dz  }t          |dz
  t          ||z                      t          |dz
  t          ||z                      g}t!          |          t!          |          z   D ]>}|                    t          |dz
  t          ||z  dz  |z                                 ?g }|D ]!|fdt%                    D             z  }"t'          t          j        |                              df                    S )a  
	Color Hash computation.

	Computes fractions of image in intensity, hue and saturation bins:

	* the first binbits encode the black fraction of the image
	* the next binbits encode the gray fraction of the remaining image (low saturation)
	* the next 6*binbits encode the fraction in 6 bins of saturation, for highly saturated parts of the remaining image
	* the next 6*binbits encode the fraction in 6 bins of saturation, for mildly saturated parts of the remaining image

	@binbits number of bits to use to encode each pixel fractions
	r   c                 Z    g | ](}t          j        |                                          )S rB   )r   r   r   )r   rE   s     r   rF   zcolorhash.<locals>.<listcomp>  s.    MMM1EM!$$&&MMMr   HSV    U      r   r         )binsr   g      ?c                 F    g | ]}d |z
  dz
  z  z  d |z
  z  z  dk    S )r   r   r   rB   )r   rD   binbitsrE   s     r   rF   zcolorhash.<locals>.<listcomp>  s>    ZZZaqQ1q)*Q1-==AZZZr   r   )r   r   r   r   rr   r   logical_andr   rG   linspaceany	histogramzerosr   r   r   r   rz   rc   r#   reshape)r   r   	intensityr}   s
mask_black
frac_black	mask_gray	frac_graymask_colorsmask_faint_colorsmask_bright_colorschue_binsh_faint_counts_h_bright_countsmaxvaluevaluescountsbitarrayrE   s    `                   @r   	colorhashr     s     ]5==--..6688MMe0D0D0J0J0L0LMMMAq("oo\
{I66;;== *yj99&{A4DEE'Q5EFFKOON1c5)) 2oa(9&:JJJ.!!;s8}}q011. 3q);'<8LLL/11KH 122/ wJx!|Sh!67788#hlCPY\dPdLeLe:f:f
gN##d?&;&;; D DV--HqL#fx&7"&<q&@"A"ABBCCCC
 [ [Q
ZZZZZ5QX>>ZZZZ((%-))112w-@@AAAr   c                   V    e Zd ZdZd Zd Zd ZddZd Zd Z	d	 Z
dd
ZddZddZdS )rs   z
	This is an image hash containing a list of individual hashes for segments of the image.
	The matching logic is implemented as described in Efficient Cropping-Resistant Robust Image Hashing
	c                     || _         d S r   )segment_hashes)r'   rt   s     r   r)   zImageMultiHash.__init__  s    $r   c                 4    |dS |                      |          S r9   matchesr5   s     r   r<   zImageMultiHash.__eq__  s    
]
%	e		r   c                 .    |                      |           S r   r   r5   s     r   r>   zImageMultiHash.__ne__  s    \\%  	  r   Nc                     |                      |||          \  }}t          | j                  }|dk    r|S |t          | j        d                   z  }dt          |          |z  z
  }||z   }	||	z
  S )Nr   )	hash_diffr   r   float)
r'   r6   hamming_cutoffbit_error_rater   sum_distancemax_differencemax_distancetie_breakermatch_scores
             r   r7   zImageMultiHash.__sub__  s    ..OO'<t*++.\\
3t215666,U<((<78++%+	+	%%r   c                 X    t          t          d | j        D                                 S )Nc              3   4   K   | ]}t          |          V  d S r   r%   )r   segments     r   r   z*ImageMultiHash.__hash__.<locals>.<genexpr>  s(      EEgDMMEEEEEEr   )r&   tupler   r+   s    r   rI   zImageMultiHash.__hash__  s*    	eEE1DEEEEE	F	FFr   c                 J    d                     d | j        D                       S )Nrn   c              3   4   K   | ]}t          |          V  d S r   r   rp   s     r   r   z)ImageMultiHash.__str__.<locals>.<genexpr>  s(      66Q#a&&666666r   )r   r   r+   s    r   r,   zImageMultiHash.__str__  s&    	66$"5666	6	66r   c                 *    t          | j                  S r   )r.   r   r+   s    r   r/   zImageMultiHash.__repr__  s    	d!	"	""r   c                    |!|d}t          | j        d                   |z  }g }| j        D ]>t          fd|j        D                       }||k    r)|                    |           ?t          |          t	          |          fS )a  
		Gets the difference between two multi-hashes, as a tuple. The first element of the tuple is the number of
		matching segments, and the second element is the sum of the hamming distances of matching hashes.
		NOTE: Do not order directly by this tuple, as higher is better for matches, and worse for hamming cutoff.
		:param other_hash: The image multi hash to compare against
		:param hamming_cutoff: The maximum hamming distance to a region hash in the target hash
		:param bit_error_rate: Percentage of bits which can be incorrect, an alternative to the hamming cutoff. The
		default of 0.25 means that the segment hashes can be up to 25% different
		Ng      ?r   c              3   "   K   | ]	}|z
  V  
d S r   rB   )r   other_segment_hashsegment_hashs     r   r   z+ImageMultiHash.hash_diff.<locals>.<genexpr>  s=         %%     r   )r   r   r   rz   rG   )r'   
other_hashr   r   	distanceslowest_distancer   s         @r   r   zImageMultiHash.hash_diff  s     N+A.//.@>)) % %l    (7    ? &&O$$$$	YY	''r   r   c                 B    |                      |||          \  }}||k    S )a  
		Checks whether this hash matches another crop resistant hash, `other_hash`.
		:param other_hash: The image multi hash to compare against
		:param region_cutoff: The minimum number of regions which must have a matching hash
		:param hamming_cutoff: The maximum hamming distance to a region hash in the target hash
		:param bit_error_rate: Percentage of bits which can be incorrect, an alternative to the hamming cutoff. The
		default of 0.25 means that the segment hashes can be up to 25% different
		)r   )r'   r   region_cutoffr   r   r   r   s          r   r   zImageMultiHash.matches  s(     ~~j..II*'1	M	!!r   c                 4     t          | fd          S )a  
		Returns the hash in a list which is the best match to the current hash
		:param other_hashes: A list of image multi hashes to compare against
		:param hamming_cutoff: The maximum hamming distance to a region hash in the target hash
		:param bit_error_rate: Percentage of bits which can be incorrect, an alternative to the hamming cutoff.
		Defaults to 0.25 if unset, which means the hash can be 25% different
		c                 2                         |           S r   )r7   )r   r   r   r'   s    r   <lambda>z+ImageMultiHash.best_match.<locals>.<lambda>  s    $,,z>>RR r   )key)r   )r'   other_hashesr   r   s   ` ``r   
best_matchzImageMultiHash.best_match  s3     
RRRRRR
 
 
 r   )NN)r   NN)rL   rM   rN   rO   r)   r<   r>   r7   rI   r,   r/   r   r   r   rB   r   r   rs   rs     s         
    ! ! !	& 	& 	& 	&G G G7 7 7# # #( ( ( (8" " " "     r   rs   c                    t                      }t                      }t          j        t          j        |                     }t	          |d                   }|                    |           |                                }	 t                      }|D ]6}|\  }	}
|	dz
  |
f|	dz   |
f|	|
dz
  f|	|
dz   fg}|                    |           7|                    ||           |snqt                      }|D ]_}| |         r@|                    |           |                    |           |                    |           J|                    |           `|S )aP  
	Finds a region and returns a set of pixel coordinates for it.
	:param remaining_pixels: A numpy bool array, with True meaning the pixels are remaining to segment
	:param segmented_pixels: A set of pixel coordinates which have already been assigned to segment. This will be
	updated with the new pixels added to the returned segment.
	r   Tr   )	setr   	transposenonzeror   addcopyupdatedifference_update)remaining_pixelssegmented_pixels	in_regionnot_in_regionavailable_pixelsstart
new_pixelstry_nextpixelrq   y
neighbourss               r   _find_regionr     s{    UUOEM2B$C$CDD	"	#	#
unnUU(  e
41aUAJUAJAJAJ	: ??:
-}===	 	uu*  eu MM%NN5e56 	r   c                 l   | j         \  | |k    }t          j        | j         dt                    }g }t	                      }|                    d t                    D                        |                    d t                    D                        |                    fdt                    D                        |                    fdt                    D                        t          j        ||                                          r~t          j        ||          }t          ||          }t          |          |k    r|                    |           |D ]}	d||	<   t          j        ||                                          ~t          j        |          }
t          |          z  k     rmt          j        |
|          }t          ||          }t          |          |k    r|                    |           |D ]}	d||	<   t          |          z  k     m|S )a  
	Finds all the regions within an image pixel array, and returns a list of the regions.

	Note: Slightly different segmentations are produced when using pillow version 6 vs. >=7, due to a change in
	rounding in the greyscale conversion.
	:param pixels: A numpy array of the pixel brightnesses.
	:param segment_threshold: The brightness threshold to use when differentiating between hills and valleys.
	:param min_segment_size: The minimum number of pixels for a segment.
	T)dtypec                     g | ]}d |fS r   rB   r   zs     r   rF   z&_find_all_segments.<locals>.<listcomp>_  s    >>>qB7>>>r   c                     g | ]}|d fS r  rB   r  s     r   rF   z&_find_all_segments.<locals>.<listcomp>`  s    ===qAr7===r   c                     g | ]}|fS rB   rB   )r   r  	img_widths     r   rF   z&_find_all_segments.<locals>.<listcomp>a  s    EEEaIq>EEEr   c                     g | ]}|fS rB   rB   )r   r  
img_heights     r   rF   z&_find_all_segments.<locals>.<listcomp>b  s    EEEqAz?EEEr   F)r3   r   fullr^   r   r  rc   bitwise_andr   r  r   rz   invert)r   segment_thresholdmin_segment_sizethreshold_pixelsunassigned_pixelssegmentsalready_segmentedr  r   pixthreshold_pixels_ir  r  s              @@r   _find_all_segmentsr)  L  sf     J..Zd$???UU >>E*,=,=>>>???==E),<,<===>>>EEEE53D3DEEEFFFEEEEE)4D4DEEEFFF )+<==AACC "&'79JKK)+<=='\\$$$??7 " "c!S )+<==AACC " l#344
	J 666&'9;LMM)+<=='\\$$$??7 " "c!S 	J 666 	r        ,  c                    |t           }|                                 }|                     d                              ||ft                    } |                     t          j                                                  t          j                              } t          j
        |                               t          j                  }t          |||          }|s!d|dz
  |dz
  fh}	|                    |	           |rt          |d d          d|         }g }
|D ]}|j        \  }}t#          |          |z  }t#          |          |z  }t%          d |D                       |z  }t%          d	 |D                       |z  }t'          d
 |D                       dz   |z  }t'          d |D                       dz   |z  }|                    ||||f          }|
                     ||                     t+          |
          S )a  
	Creates a CropResistantHash object, by the algorithm described in the paper "Efficient Cropping-Resistant Robust
	Image Hashing". DOI 10.1109/ARES.2014.85
	This algorithm partitions the image into bright and dark segments, using a watershed-like algorithm, and then does
	an image hash on each segment. This makes the image much more resistant to cropping than other algorithms, with
	the paper claiming resistance to up to 50% cropping, while most other algorithms stop at about 5% cropping.

	Note: Slightly different segmentations are produced when using pillow version 6 vs. >=7, due to a change in
	rounding in the greyscale conversion. This leads to a slightly different result.
	:param image: The image to hash
	:param hash_func: The hashing function to use
	:param limit_segments: If you have storage requirements, you can limit to hashing only the M largest segments
	:param segment_threshold: Brightness threshold between hills and valleys. This should be static, putting it between
	peak and trough dynamically breaks the matching
	:param min_segment_size: Minimum number of pixels for a hashable segment
	:param segmentation_image_size: Size which the image is resized to before segmentation
	Nr   )r   r   r   c                      t          |           S r   )r   )r   s    r   r   z%crop_resistant_hash.<locals>.<lambda>  s    CFF r   T)r   reversec              3   &   K   | ]}|d          V  dS r   NrB   r   coords     r   r   z&crop_resistant_hash.<locals>.<genexpr>  &      ,,5eAh,,,,,,r   c              3   &   K   | ]}|d          V  dS r   NrB   r2  s     r   r   z&crop_resistant_hash.<locals>.<genexpr>  r4  r   c              3   &   K   | ]}|d          V  dS r1  rB   r2  s     r   r   z&crop_resistant_hash.<locals>.<genexpr>  &      --EuQx------r   c              3   &   K   | ]}|d          V  dS r6  rB   r2  s     r   r   z&crop_resistant_hash.<locals>.<genexpr>  r8  r   )r   r  r   r   r   filterr   GaussianBlurMedianFilterr   rd   astypefloat32r)  rz   sortedr2   r   r   r   croprs   )r   	hash_funclimit_segmentsr!  r"  segmentation_image_size
orig_imager   r%  full_image_segmentrt   r   orig_worig_hscale_wscale_hmin_ymin_xmax_ymax_xbounding_boxs                        r   crop_resistant_hashrO  |  s(   4 )jjll	s			"	"$;=T#UW`	a	a	k.00	1	1	8	89Q9S9S	T	T
+e


#
#EM
2
2v'8:JKK 	 &!81!<>UXY>Y Z[
//$%%%  SH"2"2DAAA/>/R(  
) 
)W?.&&&MM33'&MM33'
,,G,,,
,
,w
6%
,,G,,,
,
,w
6%--W-----1W
<%--W-----1W
<%%u!=>>,--		,''(((( 	vr   )rA   )rA   r   )rA   NrQ   T)rS   )NNr*  r+  r,  )1rO   
__future__r   r   r   sysr   PILr   r   
ResamplingLANCZOSr   AttributeError__version__r!   r#   typingrP   	WhashModeImportErrorr   numpy.typingNDArraybool_r   version_inforU   collections.abcr   MeanFuncHashFuncr1   rh   rl   ru   r~   r   r   r   r   r   r   r   r   rs   r  r)  rO  rB   r   r   <module>ra     sx   < A @ @ @ @ @ @ @ @ @ 



  " " " " " " " "%    _
  F@ @ @) ) ) ) ) ) ) )Z]#   <,$    v	!!c&6)&C&C&&&&&&wi&'(u{mY./((   ((((  (    $$ $ $ $* #$%*    8   .   (   ,   &/ / / /d3B 3B 3B 3Bl] ] ] ] ] ] ] ]@) ) )X- - -d C C C C C CsB   + ::A   A*)A*.B
 
	BBC$ $	C0/C0