- 操作系统: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
图像非常相似!