OpenCV颜色矩哈希算法------cv::img_hash::ColorMomentHash
- 操作系统:ubuntu22.04
- OpenCV版本:OpenCV4.9
- IDE:Visual Studio Code
- 编程语言:C++11
算法描述
该类实现了颜色矩哈希算法(Color Moment Hash),用于图像相似性比较。它基于图像在HSV颜色空间中的颜色矩统计特征来生成哈希值,对颜色分布的变化具有较好的鲁棒性。
适用于以下场景:
- 图像检索
- 图像去重
- 水印检测
- 色彩变化较大的图像匹配
公共成员函数
- compute(InputArray inputArr, OutputArray outputArr)
计算输入图像的颜色矩哈希值。
参数说明:
参数 | 类型 | 描述 |
---|---|---|
inputArr | InputArray | 输入图像,必须是三通道彩色图像 (CV_8UC3) |
outputArr | OutputArray | 输出的哈希值,类型为 CV_64F 的一维 Mat |
示例: |
Mat hash;
color_moment_hash->compute(image, hash);
- compare(const Mat& hashOne, const Mat& hashTwo)
比较两个哈希值之间的差异,返回欧几里得距离。
参数说明:
参数 | 类型 | 描述 |
---|---|---|
hashOne | const Mat& | 第一个哈希值 |
hashTwo | const Mat& | 第二个哈希值 |
返回值: |
- 返回两个哈希之间的欧几里得距离。
- 值越小表示图像越相似。
示例:
double distance = color_moment_hash->compare(hash1, hash2);
if (distance < threshold) {std::cout << "图像相似" << std::endl;
}
哈希值格式说明
- 长度:18 个双精度浮点数(共 144 bits)
- 数据内容:
- 每个像素转换为 HSV 颜色空间
- 对 Hue、Saturation、Value 三个通道分别计算前 3 阶颜色矩(均值、标准差、偏度)
- 总共 3 通道 × 3 矩 = 9 个特征,每个特征用 2 个 double 表示(共 18 个)
示例代码
#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;}// 创建 ColorMomentHash 对象Ptr< ColorMomentHash > color_moment_hash = ColorMomentHash::create();// 计算哈希值Mat hash1, hash2;color_moment_hash->compute( img1, hash1 );color_moment_hash->compute( img2, hash2 );// 比较哈希值(返回欧几里得距离)double distance = color_moment_hash->compare( hash1, hash2 );cout << "欧几里得距离: " << distance << endl;if ( distance < 0.1 ){ // 这里的阈值可以根据实际情况调整cout << "图像非常相似!" << endl;}else{cout << "图像不相似。" << endl;}return 0;
}
运行结果
欧几里得距离: 7.22988
图像不相似。