图片相似度度量方法

不羁岁月 提交于 2020-03-04 19:31:18

度量方法参考资料地址
参考资料里面的是python代码,总共有三种方式,下面是参考其中一种写的C++

#include <iostream>
#include <vector>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

vector<int> dhash(Mat imgSrc, int w, int h){
    Mat imgResize;
    resize(imgSrc, imgResize, Size(w, h));
    Mat img;
    cvtColor(imgResize, img, CV_BGR2GRAY);
    vector<int> hash;
    for(int i = 0; i < w; i++){
        for(int j = 0; j < w; j++){
            if(img.at<uchar>(i, j) > img.at<uchar>(i, j + 1)){
                hash.push_back(1);
            }else{
                hash.push_back(0);
            }
        }
    }
    return hash;
}

float getSimilarity(vector<int> hash1, vector<int> hash2){
    int hammDis = 0;
    for(int i = 0; i < hash1.size(); i++){
        if(hash1[i] != hash2[i]){
            hammDis += 1;
        }
    }
    float similarity = 1 - hammDis * 1.0 / hash1.size();
    return similarity;
}




int main_bak(int argc, char const *argv[])
{
    Mat img1 = imread("/home/ly/test/C_CPP/similarity/images/roi_114.jpg");
    // Mat img2 = imread("../images/roi_149.jpg");
    Mat img2 = imread("/home/ly/test/C_CPP/similarity/images/roi_149.jpg");
    vector<int> hash1 = dhash(img1, 9, 8);
    vector<int> hash2 = dhash(img2, 9, 8);
    cout << "hash length: " << hash1.size() << endl;
    float similarity = getSimilarity(hash1, hash2);
    cout << "similarity: " << similarity << endl;

    return 0;
}

float getSimilarity(cv::Mat preImg, cv::Mat curImg){
    if(!preImg.data || !curImg.data) return -1;
    std::vector<int> hashPre = dhash(preImg, 9, 8); 
    std::vector<int> hashInput = dhash(curImg, 9, 8);
    int hammDis = 0;
    for(int i = 0; i < hashPre.size(); i++){
        if(hashPre[i] != hashInput[i]){
            hammDis += 1;
        }
    }
    float similarity = 1 - hammDis * 1.0 / hashPre.size();
    return similarity;
}

cv::Mat getComImg(cv::Mat& preImg, cv::Mat& curImg, int frame_cnt, bool flag){
  cv::Mat comImg;
  if ((flag == false) && frame_cnt % 10 == 0) {
    float similarity = getSimilarity(preImg, curImg);
    cout << similarity << endl;
    if (similarity > 0.95) {
      comImg = preImg;
    }
    preImg = curImg;
  }

  return comImg;
}
int main(int argc, char const *argv[])
{
    Mat img1 = imread("/home/ly/Projects/PersonTrackCaffe/build/roi/roi_1.jpg");
    // Mat img2 = imread("../images/roi_149.jpg");
    Mat img2 = imread("/home/ly/Projects/PersonTrackCaffe/build/roi/roi_10.jpg");
    cv::Mat comImg = getComImg(img1, img2, 10, false);
    if(comImg.data){
        cout << "has data" << endl;
    }
    return 0;
}




易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!