- 操作系統:ubuntu22.04
- OpenCV版本:OpenCV4.9
- IDE:Visual Studio Code
- 編程語言:C++11
算法描述
該類實現了 Marr-Hildreth 邊緣檢測哈希算法(Marr-Hildreth Hash),用于圖像相似性比較。它基于 Marr-Hildreth 邊緣檢測器(也稱為 Laplacian of Gaussian, LoG)提取圖像邊緣信息,并生成二進制哈希值。
這種哈希方法對圖像中的邊緣結構非常敏感,適合用于:
- 圖像檢索
- 圖像去重
- 檢測圖像是否經過裁剪、旋轉或輕微變形
公共成員函數
- compute(InputArray inputArr, OutputArray outputArr)
計算輸入圖像的 Marr-Hildreth 哈希值。
參數說明:
參數 | 類型 | 描述 |
---|---|---|
inputArr | InputArray | 輸入圖像,支持灰度圖 (CV_8UC1) 或彩色圖 (CV_8UC3) |
outputArr | OutputArray | 輸出的哈希值,類型為 CV_8U 的一維 Mat |
示例: |
Mat hash;
marr_hash->compute(image, hash);
- compare(const Mat& hashOne, const Mat& hashTwo)
比較兩個哈希值之間的差異,返回 漢明距離(Hamming Distance)。
參數說明:
參數 | 類型 | 描述 |
---|---|---|
hashOne | const Mat& | 第一個哈希值 |
hashTwo | const Mat& | 第二個哈希值 |
返回值: |
- 返回兩個哈希之間的 漢明距離
- 值越小表示圖像越相似
示例:
double distance = marr_hash->compare(hash1, hash2);
if (distance < threshold) {std::cout << "圖像相似" << std::endl;
}
代碼示例
#include <opencv2/opencv.hpp>
#include <opencv2/img_hash.hpp>
#include <iostream>using namespace cv;
using namespace cv::img_hash;
using namespace std;int main()
{// 加載圖像(支持彩色圖或灰度圖)Mat img1 = imread("/media/dingxin/data/study/OpenCV/sources/images/img1.jpg", IMREAD_COLOR);Mat img2 = imread("/media/dingxin/data/study/OpenCV/sources/images/img2.jpg", IMREAD_COLOR);if (img1.empty() || img2.empty()) {cerr << "無法加載圖像!" << endl;return -1;}// 創建 MarrHildrethHash 對象(可選參數 sigma)Ptr<MarrHildrethHash> marr_hash = MarrHildrethHash::create(1.2); // sigma = 1.2// 計算哈希值Mat hash1, hash2;marr_hash->compute(img1, hash1);marr_hash->compute(img2, hash2);// 比較哈希值(返回漢明距離)double distance = marr_hash->compare(hash1, hash2);cout << "漢明距離: " << distance << endl;if (distance < 10) { // 可根據實際調整閾值cout << "圖像非常相似!" << endl;} else {cout << "圖像不相似。" << endl;}return 0;
}
運行結果
漢明距離: 9
圖像非常相似!