我最近也面临着同样的问题,要彻底解决此问题(简单快速的算法来比较两个图像),我将img_hash模块贡献给opencv_contrib,您可以从此链接中找到详细信息。
img_hash模块提供了六种图像哈希算法,非常易于使用。
代码示例
起源莱娜
模糊莱娜
调整莉娜
莱娜班
#include <opencv2/core.hpp>
#include <opencv2/core/ocl.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/img_hash.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>
void compute(cv::Ptr<cv::img_hash::ImgHashBase> algo)
{
auto input = cv::imread("lena.png");
cv::Mat similar_img;
//detect similiar image after blur attack
cv::GaussianBlur(input, similar_img, {7,7}, 2, 2);
cv::imwrite("lena_blur.png", similar_img);
cv::Mat hash_input, hash_similar;
algo->compute(input, hash_input);
algo->compute(similar_img, hash_similar);
std::cout<<"gaussian blur attack : "<<
algo->compare(hash_input, hash_similar)<<std::endl;
//detect similar image after shift attack
similar_img.setTo(0);
input(cv::Rect(0,10, input.cols,input.rows-10)).
copyTo(similar_img(cv::Rect(0,0,input.cols,input.rows-10)));
cv::imwrite("lena_shift.png", similar_img);
algo->compute(similar_img, hash_similar);
std::cout<<"shift attack : "<<
algo->compare(hash_input, hash_similar)<<std::endl;
//detect similar image after resize
cv::resize(input, similar_img, {120, 40});
cv::imwrite("lena_resize.png", similar_img);
algo->compute(similar_img, hash_similar);
std::cout<<"resize attack : "<<
algo->compare(hash_input, hash_similar)<<std::endl;
}
int main()
{
using namespace cv::img_hash;
//disable opencl acceleration may(or may not) boost up speed of img_hash
cv::ocl::setUseOpenCL(false);
//if the value after compare <= 8, that means the images
//very similar to each other
compute(ColorMomentHash::create());
//there are other algorithms you can try out
//every algorithms have their pros and cons
compute(AverageHash::create());
compute(PHash::create());
compute(MarrHildrethHash::create());
compute(RadialVarianceHash::create());
//BlockMeanHash support mode 0 and mode 1, they associate to
//mode 1 and mode 2 of PHash library
compute(BlockMeanHash::create(0));
compute(BlockMeanHash::create(1));
}
在这种情况下,ColorMomentHash给我们最好的结果
- 高斯模糊攻击:0.567521
- 转移攻击:0.229728
- 调整攻击强度:0.229358
每种算法的优缺点
img_hash的性能也不错
与PHash库进行速度比较(来自ukbench的100张图像)
如果您想了解这些算法的建议阈值,请查看此帖子(http://qtandopencv.blogspot.my/2016/06/introduction-to-image-hash-module-of.html)。如果您对我如何测量img_hash模块的性能(包括速度和其他攻击)感兴趣,请检查此链接(http://qtandopencv.blogspot.my/2016/06/speed-up-image-hashing-of -opencvimghash.html)。