PHash算法即感知哈希算法/Perceptual Hash algorithm,计算基于低频的均值哈希.对每张图像生成一个指纹字符串,通过对该字符串比较可以判断图像间的相似度.
PHash算法原理
将图像转为灰度图,然后将图片大小调整为32*32像素并通过DCT变换,取左上角的8*8像素区域。然后计算这64个像素的灰度值的均值。将每个像素的灰度值与均值对比,大于均值记为1,小于均值记为0,得到64位哈希值。
PHash算法实现
将图片转为灰度值
将图片尺寸缩小为32*32
1
|
resize(src, src, Size(32, 32));
|
DCT变换
1
2
|
Mat srcDCT;
dct(src, srcDCT);
|
计算DCT左上角8*8像素区域均值,求hash值
1
2
3
4
5
6
7
8
9
10
|
double sum = 0;
for ( int i = 0; i < 8; i++)
for ( int j = 0; j < 8; j++)
sum += srcDCT.at< float >(i,j);
double average = sum/64;
Mat phashcode= Mat::zeros(Size(8, 8), CV_8U);
for ( int i = 0; i < 8; i++)
for ( int j = 0; j < 8; j++)
phashcode.at< char >(i,j) = srcDCT.at< float >(i,j) > average ? 1:0;
|
hash值匹配
1
2
3
|
int d = 0;
for ( int n = 0; n < srchash.size[1]; n++)
if (srchash.at<uchar>(0,n) != dsthash.at<uchar>(0,n)) d++;
|
即,计算两幅图哈希值之间的汉明距离,汉明距离越大,两图片越不相似。
OpenCV实现
如图在下图中对比各个图像与图person.jpg的汉明距离,以此衡量两图之间的额相似度。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <io.h>
#include <string>
#include <opencv2\opencv.hpp>
#include <opencv2\core\core.hpp>
#include <opencv2\core\mat.hpp>
using namespace std;
using namespace cv;
int fingerprint(Mat src, Mat* hash);
int main()
{
Mat src = imread( "E:\\image\\image\\image\\person.jpg" , 0);
if (src.empty())
{
cout << "the image is not exist" << endl;
return -1;
}
Mat srchash, dsthash;
fingerprint(src, &srchash);
for ( int i = 1; i <= 8; i++)
{
string path0 = "E:\\image\\image\\image\\person" ;
string number;
stringstream ss;
ss << i;
ss >> number;
string path = "E:\\image\\image\\image\\person" + number + ".jpg" ;
Mat dst = imread(path, 0);
if (dst.empty())
{
cout << "the image is not exist" << endl;
return -1;
}
fingerprint(dst, &dsthash);
int d = 0;
for ( int n = 0; n < srchash.size[1]; n++)
if (srchash.at<uchar>(0,n) != dsthash.at<uchar>(0,n)) d++;
cout << "person" << i << " distance= " <<d<< "\n" ;
}
system ( "pause" );
return 0;
}
int fingerprint(Mat src, Mat* hash)
{
resize(src, src, Size(32, 32));
src.convertTo(src, CV_32F);
Mat srcDCT;
dct(src, srcDCT);
srcDCT = abs (srcDCT);
double sum = 0;
for ( int i = 0; i < 8; i++)
for ( int j = 0; j < 8; j++)
sum += srcDCT.at< float >(i,j);
double average = sum/64;
Mat phashcode= Mat::zeros(Size(8, 8), CV_8U);
for ( int i = 0; i < 8; i++)
for ( int j = 0; j < 8; j++)
phashcode.at< char >(i,j) = srcDCT.at< float >(i,j) > average ? 1:0;
*hash = phashcode.reshape(0,1).clone();
return 0;
}
|
输出汉明距离:
可以看出若将阈值设置为20则可将后三张其他图片筛选掉。
以上这篇opencv3/C++ PHash算法图像检索详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/akadiao/article/details/79779634