不同阈值-将Matlab代码转换为OpenCV代码



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

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;
}

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

j <= img.cols应为j < img.cols

i <= img.rows应为i < 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;
}

最新更新