OpenCV哈希算法------Marr-Hildreth 边缘检测哈希算法

  • 操作系统:ubuntu22.04
  • OpenCV版本:OpenCV4.9
  • IDE:Visual Studio Code
  • 编程语言:C++11

算法描述

该类实现了 Marr-Hildreth 边缘检测哈希算法(Marr-Hildreth Hash),用于图像相似性比较。它基于 Marr-Hildreth 边缘检测器(也称为 Laplacian of Gaussian, LoG)提取图像边缘信息,并生成二进制哈希值。

这种哈希方法对图像中的边缘结构非常敏感,适合用于:

  • 图像检索
  • 图像去重
  • 检测图像是否经过裁剪、旋转或轻微变形

公共成员函数

  1. compute(InputArray inputArr, OutputArray outputArr)

计算输入图像的 Marr-Hildreth 哈希值。

参数说明:

参数 类型 描述
inputArr InputArray 输入图像,支持灰度图 (CV_8UC1) 或彩色图 (CV_8UC3)
outputArr OutputArray 输出的哈希值,类型为 CV_8U 的一维 Mat
示例:
cpp 复制代码
Mat hash;
marr_hash->compute(image, hash);
  1. compare(const Mat& hashOne, const Mat& hashTwo)

比较两个哈希值之间的差异,返回 汉明距离(Hamming Distance)。

参数说明:

参数 类型 描述
hashOne const Mat& 第一个哈希值
hashTwo const Mat& 第二个哈希值
返回值:
  • 返回两个哈希之间的 汉明距离
  • 值越小表示图像越相似

示例:

cpp 复制代码
double distance = marr_hash->compare(hash1, hash2);
if (distance < threshold) {
    std::cout << "图像相似" << std::endl;
}

代码示例

cpp 复制代码
#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;
}

运行结果

bash 复制代码
汉明距离: 9
图像非常相似!
相关推荐
GuWenyue7 小时前
写Agent还要重复封装工具?一套MCP多服务方案,3个能力让AI自动查地图、读写文件、操控浏览器
人工智能·机器学习·开源
GuWenyue7 小时前
90%AI新手不会调参!LangChain双模型流水线实战,一套代码兼顾严谨+创意
人工智能
光锥智能9 小时前
WAIC亮点|兼具泛化能力与作业效率的极智嘉机器人天团
人工智能·机器人
阳光是sunny9 小时前
LangGraph中的Reducer是什么
前端·人工智能·后端
甲维斯9 小时前
Kimi K3 重构10000行单文件屎山代码!
人工智能
阳光是sunny9 小时前
从链到图:LangGraph 入门基础全解析
前端·人工智能·后端
新知图书9 小时前
11.3 详细实现与核心配置(作业批改智能体开发)
人工智能·agent·ai agent·智能体·扣子
深度研习笔记10 小时前
OpenCV工业视觉实战11|多线程解耦+视频流稳流+推理加速,彻底解决卡顿阻塞,实现毫秒级工业实时检测
人工智能·opencv·计算机视觉
delishcomcn10 小时前
AI视觉识别+分切算法:电化铝缺陷检测与裁切一体化解锁
人工智能·算法
触底反弹10 小时前
深入理解大模型采样:Temperature、Top-K、Top-P 的原理与实战
人工智能·算法·面试