OpenCV实现感知哈希(Perceptual Hash)算法的类cv::img_hash::PHash

发布于:2025-07-15 ⋅ 阅读:(18) ⋅ 点赞:(0)
  • 操作系统:ubuntu22.04
  • OpenCV版本:OpenCV4.9
  • IDE:Visual Studio Code
  • 编程语言:C++11

算法描述

PHash是OpenCV中实现感知哈希(Perceptual Hash)算法的类。该算法用于快速比较图像的视觉相似性。它将图像压缩为一个简短的哈希值(通常为64位),可用于图像去重、版权识别、内容匹配等场景。

PHash 基于图像的低频信息(通过 DCT 变换提取)来生成哈希值,对轻微的噪声、缩放和旋转具有一定的鲁棒性。

成员函数

virtual void compute (InputArray input, OutputArray output)

参数说明:

  • input:输入图像(支持灰度图或彩色图,建议先转换为灰度图以提高一致性)。
  • output:输出哈希值,类型为 CV_8U,长度通常是 8 字节(64 位)。

功能:
计算输入图像的 PHash 哈希值,并保存到 output 中。

virtual double compare (InputArray hash1, InputArray hash2)

参数说明:

  • hash1, hash2:两个哈希值(必须是相同格式的 8 字节数组)。

返回值:两个哈希之间的汉明距离(Hamming Distance),表示差异程度。数值越小表示图像越相似。

功能:

比较两个哈希值的相似性,常用于判断两幅图像是否“看起来一样”。

代码示例

#include <opencv2/img_hash.hpp>
#include <opencv2/opencv.hpp>

int main()
{
    // 加载图像
    cv::Mat img1 = cv::imread( "/media/dingxin/data/study/OpenCV/sources/images/img1.jpg", cv::IMREAD_GRAYSCALE );
    cv::Mat img2 = cv::imread( "/media/dingxin/data/study/OpenCV/sources/images/img2.jpg", cv::IMREAD_GRAYSCALE );

    if ( img1.empty() || img2.empty() )
    {
        std::cerr << "无法加载图像" << std::endl;
        return -1;
    }

    // 创建 PHash 算法对象
    cv::Ptr< cv::img_hash::PHash > phash = cv::img_hash::PHash::create();

    // 计算哈希值
    cv::Mat hash1, hash2;
    phash->compute( img1, hash1 );
    phash->compute( img2, hash2 );

    // 比较哈希值
    double distance = phash->compare( hash1, hash2 );
    std::cout << "汉明距离: " << distance << std::endl;

    return 0;
}

运行结果

汉明距离: 1

网站公告

今日签到

点亮在社区的每一天
去签到