【发布时间】:2020-07-22 14:05:50
【问题描述】:
我正在使用 OpenCV/C++ 来计算两个图像之间的相似率。我想告诉用户图片 A 看起来像图片 B 的百分比。
让我们看看下面的代码:
double getSimilarityRate(const cv::Mat A, const cv::Mat B){
double cpt = 0.0;
cv::Mat imgGray1, imgGray2;
cv::cvtColor(A, imgGray1, CV_BGR2GRAY);
cv::cvtColor(B, imgGray2, CV_BGR2GRAY);
imgGray1 = imgGray1 > 128;
imgGray2 = imgGray2 > 128;
double total = imgGray1.cols * imgGray1.rows;
if(imgGray1.rows > 0 && imgGray1.rows == B.rows && imgGray1.cols > 0 && imgGray1.cols == B.cols){
for(int rows = 0; rows < imgGray1.rows; rows++){
for(int cols = 0; cols < imgGray1.cols; cols++){
if(imgGray1.at<int>(rows, cols) == imgGray2.at<int>(rows,cols)) cpt ++;
}
}
}else{
std::cout << "No similartity between the two images ... [EXIT]" << std::endl;
exit(0);
}
double rate = cpt / total;
return rate * 100.0;
}
int main(void)
{
/* ------------------------------------------ # ALGO GETSIMILARITY BETWEEN 2 IMAGES # -------------------------------------- */
double rate;
string fileNameImage1("C:\\Users\\hugoo\\Documents\\Prog\\NexterMU\\Qt\\OpenCV\\DetectionShapeProgram\\mire.jpg");
cv::Mat image1 = imread(fileNameImage1);
string fileNameImage2("C:\\Users\\hugoo\\Documents\\Prog\\NexterMU\\Qt\\OpenCV\\DetectionShapeProgram\\mire.jpg");
cv::Mat image2 = imread(fileNameImage2);
if(image1.empty() || image2.empty()){
std::cout << "Images couldn't be loaded" << std::endl;
exit(-1);
}
rate = getSimilarityRate(image1, image2) ;
首先,我将矩阵从 BGR 转换为 GREY。所以我只剩下一个频道了。 (更容易比较)。
cv::Mat imgGray1, imgGray2;
cv::cvtColor(A, imgGray1, CV_BGR2GRAY);
cv::cvtColor(B, imgGray2, CV_BGR2GRAY);
然后我将它们设为二进制(255 或 0 --> 像素的白色或黑色):
imgGray1 = imgGray1 > 128;
imgGray2 = imgGray2 > 128;
在我的 for 循环中,我遍历每个像素并将他与第二张图像中的其他像素进行比较。 如果匹配,我增加一个变量(cpt ++)。
我计算比率并将其转换为 %,其中:
double rate = cpt / total;
return rate * 100.0;
问题是它似乎没有正确计算,因为它没有在控制台中返回我的速率值......
我认为问题来自 at() 函数,也许我没有正确使用它。
【问题讨论】:
-
我没有看到您在代码中打印相似性的位置。
-
如果图像 B 只是图像 A 的平移/缩放怎么办?你会认为这种情况类似吗?