您好,登錄后才能下訂單哦!
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算法圖像檢索詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。