ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

OpenCV 图像哈希类cv::img_hash::BlockMeanHash

OpenCV 图像哈希类cv::img_hash::BlockMeanHash
  • 操作系统:ubuntu22.04
  • OpenCV版本:OpenCV4.9
  • IDE:Visual Studio Code
  • 编程语言:C++11

算法描述

cv::img_hash::BlockMeanHash 是 OpenCV 中用于图像哈希(Image Hashing)的一个类,属于 opencv_img_hash 模块。它实现了分块均值哈希算法(Block Mean Hash),可以用于判断两幅图像是否相似。

主要成员函数

  1. compute(InputArray image, OutputArray code)

计算输入图像的 Block Mean 哈希值。

void compute(InputArray image, OutputArray code);
  • image: 输入图像(支持 CV_8UC1 或 CV_8UC3)
  • code: 输出的哈希值(类型为 CV_8U 的一维 Mat)
  1. compare(const cv::Mat& code1, const cv::Mat& code2)

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

double compare(const cv::Mat& code1, const cv::Mat& code2);

返回值越小表示图像越相似(0 表示完全相同)

示例代码


#include <iostream>
#include <opencv2/img_hash.hpp>
#include <opencv2/opencv.hpp>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;}// 创建 BlockMeanHash 对象并设置模式Ptr< BlockMeanHash > block_mean_hash = BlockMeanHash::create();block_mean_hash->setMode( BLOCK_MEAN_HASH_MODE_1 );  // 可选// 计算哈希值Mat hash1, hash2;block_mean_hash->compute( img1, hash1 );block_mean_hash->compute( img2, hash2 );// 比较哈希值(返回汉明距离)double distance = block_mean_hash->compare( hash1, hash2 );cout << "汉明距离: " << distance << endl;if ( distance < 10 ){cout << "图像非常相似!" << endl;}else{cout << "图像不相似。" << endl;}return 0;
}

运行结果

汉明距离: 31
图像不相似。
返回列表