#include#include using namespace cv; using namespace std; uint64_t phash(const Mat& img) { Mat gray, small; cvtColor(img, gray, COLOR_BGR2GRAY); resize(gray, small, Size(8,8), 0,0, INTER_CUBIC); Scalar mean = cv::mean(small); uint64_t hash = 0; for (int i=0; i<8; ++i) { uchar* row = small.ptr (i); for (int j=0; j<8; ++j) { hash = (hash<<1) | (row[j] >= mean[0]); } } return hash; } int hammingDist(uint64_t a, uint64_t b) { return __builtin_popcountll(a ^ b); } int main() { Mat img1 = imread("1.jpg"), img2 = imread("2.jpg"); uint64_t h1 = phash(img1), h2 = phash(img2); int dist = hammingDist(h1, h2); cout << "Hash1: " << hex << h1 << "\nHash2: " << h2 << "\nDistance: " << dec << dist << endl; if (dist <= 5) cout << "Very similar\n"; else if (dist <= 10) cout << "Somewhat similar\n"; else cout << "Different images\n"; return 0; }
INTER_CUBIC 三次插值縮放質量較好計算相鄰像素差值而非與均值比較,對平移更魯棒。實現類似,只需將比較邏輯改為 `row[j] > row[j+1]`。
感知哈希是圖像去重、版權檢測、內容檢索的基礎工具,理解其原理與實現細節,可快速構建圖像相似度系統。