【问题标题】:different value of thresh - converting Matlab code to OpenCV code阈值的不同值 - 将 Matlab 代码转换为 OpenCV 代码
【发布时间】:2021-02-15 13:08:19
【问题描述】:

我想要一些关于将 matlab 中的代码传递给 opencv c ++ 的帮助。我正在尝试对 RGB 通道进行一些操作,但是 thresh 的值不一样 - 我正在发送相同的图像。有人可以帮我吗?

MATLAB

im = imread('1.png');

[m,n,p] = size(im);

R=im(:, :, 1);
G=im(:, :, 2);
B=im(:, :, 3);

thresh=0;

for j=1:n
    for i=1:m
        thresh = thresh + double((1.262*G(i,j))-(0.884*R(i,j))-(0.311*B(i,j)));
    end
end

C++

#include <opencv2/opencv.hpp>
#include "opencv2/highgui.hpp"
#include <opencv2/core/mat.hpp>
#include <iostream>
using namespace std;
using namespace cv;


int main(){
    Mat img = imread("1.png", IMREAD_COLOR); 
    int thresh = 0;

    for(int j = 0; j <= img.cols; j++){
        for(int i = 0; i <= img.rows; i++){
            Vec3b color = img.at<Vec3b>(i,j);
            uchar a = color.val[0], b = color.val[1], c = color.val[2];
            thresh += double((1.262*b)-(0.884*c)-(0.311*a));
        }
    }
    
    cout << thresh;
    return 0;
}

【问题讨论】:

  • 也许不是您的问题,但您正在阅读img.cols + 1 列和img.rows + 1 行。

标签: c++ matlab opencv


【解决方案1】:

第一个错误在于 for 循环的上限值,因为您超出了图像边框的范围。

j &lt;= img.cols 应该是 j &lt; img.cols

i &lt;= img.rows 应该是i &lt; img.rows

第二个错误是您没有为您的uchar 类型像素值进行显式类型转换

thresh += double((1.262*b)-(0.884*c)-(0.311*a));

应该是

thresh += double((1.262*static_cast<double>(b))
          -(0.884*static_cast<double>(c))
          -(0.311*static_cast<double>(a)));

这是我尝试过的全部代码:

#include <opencv2/opencv.hpp>
#include "opencv2/highgui.hpp"
#include <opencv2/core/mat.hpp>
#include <iostream>

using namespace std;
using namespace cv;


int main()
{
    Mat img = imread("img.jpg", IMREAD_COLOR);
    double thresh = 0.0;

    resize(img,img,Size(100,100));

    for(int j = 0; j < img.cols; j++){
        for(int i = 0; i < img.rows; i++){
            
            
            // 1ST WAY 
            Vec3b color = img.at<Vec3b>(i,j);
            uchar a = color.val[0], b = color.val[1], c = color.val[2];

            thresh += double((1.262*static_cast<double>(b))
                             -(0.884*static_cast<double>(c))
                             -(0.311*static_cast<double>(a)));
            
//            2ND WAY

//            thresh += double((1.262 * (double)img.at<Vec3b>(Point(i,j))[1])
//                    - (0.884*(double)img.at<Vec3b>(Point(i,j))[2])
//                    - (0.311 * (double)img.at<Vec3b>(Point(i,j))[0]));
        }
    }

    cout << thresh << endl;
    return 0;
}

【讨论】:

  • 感谢帮助,但仍然给出与 thresh 相同的值差异
  • 我不完全知道matlab是如何计算的,但是在方法上没有问题
猜你喜欢
  • 2014-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多