I would like some help regarding passing a code that is in matlab to opencv c ++. I am trying to do some operations with the RGB channels, however, the value of thresh is not being the same - I am sending the same image. Could someone please help me?
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;
}
First mistake is in the upper values of for loops because you are exceeding the range of image borders.
j <= img.cols
should be j < img.cols
and
i <= img.rows
should be i < img.rows
Second mistake is that you don't make explicit type conversion for your uchar
type pixel values
thresh += double((1.262*b)-(0.884*c)-(0.311*a));
should be
thresh += double((1.262*static_cast<double>(b))
-(0.884*static_cast<double>(c))
-(0.311*static_cast<double>(a)));
Here is the whole code I tried:
#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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.