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

Isadora ·
更新时间:2024-11-15
· 578 次阅读

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<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值匹配

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的汉明距离,以此衡量两图之间的额相似度。

#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算法图像检索详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持软件开发网。

您可能感兴趣的文章:C++利用opencv实现人脸检测opencv3/C++图像像素操作详解opencv3/C++图像边缘提取方式opencv3/C++ 直方图反向投影实例opencv3/C++关于移动对象的轮廓的跟踪详解opencv3/C++实现霍夫圆/直线检测opencv3/C++图像滤波实现方式opencv3/C++ 平面对象识别&透视变换方式基于C++实现kinect+opencv 获取深度及彩色数据opencv3/C++视频中叠加透明图片的实现C++使用OpenCV实现证件照蓝底换成白底功能(或其他颜色如红色)详解



图像检索 c+ C++ opencv

需要 登录 后方可回复, 如果你还没有账号请 注册新账号