opencv3/C++ PHash算法图像检索

PHash算法即感知哈希算法/Perceptual Hash algorithm,计算基于低频的均值哈希.对每张图像生成一个指纹字符串,通过对该字符串比较可以判断图像间的相似度.

PHash算法原理

将图像转为灰度图,然后将图片大小调整为32*32像素并通过DCT变换,取左上角的8*8像素区域。然后计算这64个像素的灰度值的均值。将每个像素的灰度值与均值对比,大于均值记为1,小于均值记为0,得到64位哈希值。

PHash算法实现

  • 将图片转为灰度值
  • 将图片尺寸缩小为32*32
resize(src, src, Size(32, 32));
  • DCT变换
    Mat srcDCT; 
    dct(src, srcDCT);
  • 计算DCT左上角8*8像素区域均值,求hash值
    double sum = 0;
    for (int i = 0; i < 8; i++)
        for (int j = 0; j < 8; j++)
            sum += srcDCT.at(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(i,j) = srcDCT.at(i,j) > average ? 1:0;
  • hash值匹配
        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的汉明距离,以此衡量两图之间的额相似度。

opencv3/C++ PHash算法图像检索_第1张图片

#include   
#include 
#include 
#include 
#include 
#include   
#include 
#include 
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(0,n) != dsthash.at(0,n)) d++;  

        cout <<"person" << i <<"  distance=  " <"\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;
}

输出汉明距离:
opencv3/C++ PHash算法图像检索_第2张图片

可以看出若将阈值设置为20则可将后三张其他图片筛选掉。

你可能感兴趣的:(OpenCV)