Home > Backend Development > PHP Tutorial > Simple version of image similarity comparison implemented in PHP, _PHP tutorial

Simple version of image similarity comparison implemented in PHP, _PHP tutorial

WBOY
Release: 2016-07-13 10:09:55
Original
1396 people have browsed it

Simple version of image similarity comparison implemented in PHP,

Since the API implemented in PHP for similar image search is not very suitable for my purpose, I redefined the API structure and rewritten it into a relatively simple function method, although it was still packaged in the form of objects.

Copy code The code is as follows:

/**  
* 图像图像上度上下载  
*  
* @version $Id: ImageHash.php 4429 2012-04-17 13:20:31Z jax $
* @author jax.hu
*  
*    <br> *  //Sample_1   <br> *  $aHash = ImageHash::hashImageFile('wsz.11.jpg');   <br> *  $bHash = ImageHash::hashImageFile('wsz.12.jpg');   <br> *  var_dump(ImageHash::isHashSimilar($aHash, $bHash));   <br> *   <br> *  //Sample_2   <br> *  var_dump(ImageHash::isImageFileSimilar('wsz.11.jpg', 'wsz.12.jpg'));   <br> *   
*/   
   
class ImageHash {   
   
   /**Sampling rate 1~10
* @access public
* @staticvar int
**/   
   public static $rate = 2;   
   
   /**Similarity allowed value 0~64
* @access public
* @staticvar int
**/   
   public static $similarity = 80;   
   
   /**The opening function corresponding to the image type
* @access private
* @staticvar string
**/   
   private static $_createFunc = array(   
       IMAGETYPE_GIF   =>'imageCreateFromGIF',   
       IMAGETYPE_JPEG  =>'imageCreateFromJPEG',   
       IMAGETYPE_PNG   =>'imageCreateFromPNG',   
       IMAGETYPE_BMP   =>'imageCreateFromBMP',   
       IMAGETYPE_WBMP  =>'imageCreateFromWBMP',   
       IMAGETYPE_XBM   =>'imageCreateFromXBM',   
   );   
   
   
   /**Create image from file
* @param string $filePath file address path
* @return resource When the image is successfully opened, the image resource ID is passed, if it fails, it is false
**/   
   public static function createImage($filePath){   
       if(!file_exists($filePath)){ return false; }   
   
       /*判断文件类型是否可以开启*/   
       $type = exif_imagetype($filePath);   
       if(!array_key_exists($type,self::$_createFunc)){ return false; }   
   
       $func = self::$_createFunc[$type];   
       if(!function_exists($func)){ return false; }   
   
       return $func($filePath);   
   }   
   
   
   /**hash image
* @param resource $src image resource ID
* @return string image hash value, false if failed
**/   
   public static function hashImage($src){   
       if(!$src){ return false; }   
   
       /*缩小图片尺寸*/   
       $delta = 8 * self::$rate;   
       $img = imageCreateTrueColor($delta,$delta);   
       imageCopyResized($img,$src, 0,0,0,0, $delta,$delta,imagesX($src),imagesY($src));   
   
​ ​ ​ /*Calculate the grayscale value of the image*/  
            $grayArray = array();                                           for ($y=0; $y<$delta; $y++){
for ($x=0; $x<$delta; $x++){
                     $rgb = imagecolorat($img,$x,$y);                                                                          $col = imagecolorsforindex($img, $rgb);                                                                         $gray = intval(($col['red']+$col['green']+$col['blue'])/3)& 0xFF;  
$grayArray[] = $gray;
                                                                                                                                               Imagedestroy($img);
 
​ ​ ​ /*Calculate the grayscale average of all pixels*/  
          $average = array_sum($grayArray)/count($grayArray);                                                  
            /*Calculate hash value*/                                                                           $hashStr = '';                                               foreach ($grayArray as $gray){
               $hashStr .= ($gray>=$average) ? '1' : '0';                                                                         
         return $hashStr;                                       }  
 
 
/**hash image file
* @param string $filePath file address path
* @return string image hash value, false if failed
**/ 
Public static function hashImageFile($filePath){
            $src = self::createImage($filePath);                                                             $hashStr = self::hashImage($src);                                                     Imagedestroy($src);
 
         return $hashStr;                                       }  
 
 
/**Compare two hash values ​​to see if they are similar
* @param string $aHash The hash value of A picture
* @param string $bHash The hash value of the B picture
* @return bool Pass true when the pictures are similar, otherwise false
**/ 
Public static function isHashSimilar($aHash, $bHash){
$aL = strlen($aHash); $bL = strlen($bHash);
If ($aL !== $bL){ return false; }
 
​ ​ ​ /*Calculate the amount of allowable gap*/  
          $allowGap = $aL*(100-self::$similarity)/100;                                                
​ ​ ​ /*Calculate the Hamming distance of two hash values*/  
          $distance = 0;                                               for($i=0; $i<$aL; $i++){
If ($aHash{$i} !== $bHash{$i}){ $distance++; }
                                                                        
            return ($distance<=$allowGap) ? true : false;                                         }  
 
 
/**Compare two image files to see if they are similar
* @param string $aHash A picture path
* @param string $bHash B picture path
* @return bool Pass true when the pictures are similar, otherwise false
* */
Public static function isImageFileSimilar($aPath, $bPath){
        $aHash = ImageHash::hashImageFile($aPath);                                                           $bHash = ImageHash::hashImageFile($bPath);                                                             return ImageHash::isHashSimilar($aHash, $bHash);                                           }  
 
}



http://www.bkjia.com/PHPjc/939420.html

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/939420.htmlTechArticleComparison of the simple version of image similarity implemented by PHP, because the API implemented by PHP for similar image search does not quite match mine. purpose, so I redefined the API structure and rewritten it into a simpler one...
Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template