php实现对相似图片的搜索。
感知哈希算法计算< = 5匹配最相似的
计数> 10个不同的图片
var_dump(imagehash::运行('。 / 1。PNG ','。 / PSB .jpg));
< PHP
类imagehash {
const file_not_found =1;
const file_extname_illegal =2;
私有函数(__construct){ }
公共静态函数运行(SRC1美元,美元SRC2){
静态自$;
如果(!$自我)$ =新静态;
如果(!is_file($ SRC1)| |!is_file($ SRC2))出口(自::file_not_found);
美元自> gethashvalue hASH1 = $($ SRC1);
hash2美元美元=自我> gethashvalue($ SRC2);
如果(strlen($ HASH1)!= = strlen()返回false hash2美元);
$=0;
$ len = strlen($ HASH1);
为($我= 0;美元美元美元我< len;i++)如果($ HASH1 { $我}!= = { })我hash2美元美元美元计数+ +;
返回$ 10真实:假;
}
公共函数的图像(文件){
extname美元=是($文件,pathinfo_extension);
如果(!in_array($ extname,{ 'jpg ','jpeg ','png ','gif ' }))出口(自::file_extname_illegal);
img = call_user_func('imagecreatefrom美元。($ extname = = 'jpg ''jpeg:extname美元),文件);
返回的IMG;
}
公共功能gethashvalue(文件){
$ = 8;
$=8;
$ img =新建一个真彩色图像($ W $ H);
列表(src_w美元,美元src_h)= getimagesize(文件);
SRC =美元美元-> getImage(文件);
imagecopyresampled(IMG SRC美元,美元,0, 0, 0美元,0美元,W,H,src_w美元,美元src_h);
销毁一图像($ SRC);
总计= 0;
数组=();
($ y = 0;$ y $ H;$ + +){
($ x = 0;$ x $ w;$ x + +){
灰色=(imagecolorat美元(约合IMG,X,Y元)> > 8)0xff;
如果(!isset(数组$ { $ Y }))的数组{ Y元} =阵();
$ $;
总金额=灰色;
}
}
销毁一图像($ IMG);
intval美元平均=(总美元/(W×H×2美元美元));
美元=;
($ y = 0;$ y $ H;$ + +){
($ x = 0;$ x $ w;$ x + +){
美元($数组哈希= { } { } $ Y $ X > =美元平均)1:'0';
}
}
var_dump($哈希);
返回$哈希;
}
}
var_dump(imagehash::运行('。 / 1。PNG ','。 / PSB .jpg));
方法二:
散列(f);
}
返回isstring $result { 0 }:$结果;
}
公共功能checkissimilarimg(imghash美元,美元otherimghash){
如果(file_exists($ imghash)file_exists($ otherimghash)){
imghash美元=美元->运行($ imghash);
otherimghash美元=美元->运行($ otherimghash);
}
如果(strlen($ imghash)!= = strlen()返回false otherimghash美元);
$=0;
$ len = strlen($ imghash);
($ i = 0;$ i;
如果($ imghash { $我}!= $ otherimghash { $我}){
数+;
}
}
返回(计算$ = 5 * $ * *率)正确:false;
}
公共函数散列($文件){
如果(!file_exists(文件)){
返回false;
}
高度= 8 * *;
宽度= 8 * *;
img =新建一个真彩色图像(美元美元美元的宽度,高度);
列表($ W $ H)= getimagesize(文件);
$源=美元-> createimg(文件);
imagecopyresampled($ IMG,源0, 0, 0,0美元,美元,美元,宽度,高度,$ W $ H);
价值=美元-> gethashvalue($ IMG);
销毁一图像($ IMG);
返回值;
}
公共功能gethashvalue($ IMG){
宽度= imagesx美元(美元IMG);
高度= imagesy美元(美元IMG);
总计= 0;
数组=();
($ y = 0;$ y高;$ + +){
($ x = 0;$ x宽度;$ x + +){
灰色=(imagecolorat美元(约合IMG,X,Y元)> > 8)0xff;
如果(!is_array(数组$ { $ Y })){
$数组=数组();
}
$ $;
总金额=灰色;
}
}
intval美元平均=(总美元/(64×美元->率*美元->率));
结果=;
($ y = 0;$ y高;$ + +){
($ x = 0;$ x宽度;$ x + +){
如果($数组{ $ $ x } =平均值){
结果1美元=;
其他{ }
结果= 0美元;
}
}
}
返回$结果;
}
公共功能createimg(文件){
Ext =美元美元-> getfileext(文件);
如果($ Ext = 'jpeg ')$分机= 'jpg;
$ img = null;
开关($){
case'png:$ img = imagecreatefrompng(文件);突破;
case'jpg:$ img = imagecreatefromjpeg(文件);突破;
case'gif:$ img = imagecreatefromgif(文件);
}
返回的IMG;
}
公共功能getfileext(文件){
$信息=(爆炸、文件);
Ext = strtolower美元($信息{计数(元信息)1 });
返回$;
}
}
打电话的方式如下:
require_onceimghash。类。PHP ;
例如:imghash美元=:getInstance();
结果=美元美元实例-> checkissimilarimg('chenyin / img_3214。png,'chenyin / img_3212 .jpg);
如果$结果值为真,则表示2张图片相似,否则不相似。