Reputation: 21
I'm looking to change the below Matlab code to OpenCV. How can I use 'Split' to perform this?
Can I just cut and paste the 'for' loop as is?
L = lab(:,:,1);
a = lab(:,:,2);
b = lab(:,:,3);
[a1, b1] = size(a);
for row=1:a1
for col=1:b1
if ((a(row,col) <-0.196) && (a(row,col)>-0.3529) && (b(row,col)>0.1568) && (b(row,col)<0.392))
II(row,col) = 1 ;
else
II(row,col) = 0 ;
end
end
end
Upvotes: 2
Views: 5815
Reputation: 808
you can use the split function
cv::Mat bgrImage = imread("C:/temp/cool_cat.jpg");
cv::Mat labImage;
cvtColor(bgrImage, labImage, CV_BGR2Lab);
//split the channels
vector<cv::Mat> lab_channels;
cv::split(labImage, lab_channels);
//verbose indexes for split LAB channels
const int L = 0;
const int A = 1;
const int B = 2;
//nicer than for loop IMHO
cv::Mat_<bool> t1a,t2a,t1b, t2b;
t1a = lab_channels[A] < 200;
t2a = lab_channels[A] > 100;
t1b = lab_channels[B] < 200;
t2b = lab_channels[B] > 100;
cv:Mat_<bool> II = t1a & t2a & t1b & t2b;
Upvotes: 4
Reputation: 5995
The snippet below should get you close:
vector<Mat> channels;
split(lab, channels);
Mat II(lab.size(), CV_8UC1);
Mat a(channels[1]);
Mat b(channels[2]);
for (int r=0;r<lab.rows;r++)
for (int c=0;c<lab.cols;c++)
{
if ((a.at<float>(r,c) < -0.196f) &&
(a.at<float>(r,c)> -0.3529f) &&
(b.at<float>(r,c) > 0.1568f) &&
(b.at<float>(r,c) < 0.392f) ) {
II.at<uchar>(r,c) = 255;
} else {
II.at<uchar>(r,c) = 0 ;
}
}
Note there are lots of assumptions that accompany this snippet:
Your Lab image appears to be stored in a floating point format, we'll assume CV_32FC3 for this exercise. But take a look at the cvtColor reference because you may run into issues with scale (note that the converted Lab format may have an offset of 128, depending on how you obtained your Lab image).
You might want to review the basics of channel splitting. This link demonstrates an RGB channel split, but the same process holds true for an Lab split.
There are also a number of build environment assumptions: the above snippet compiles/runs under GCC 4.7.2 and OpenCV 2.4.8. Some conveniences have been taken with namespace inclusions to simplify the snippet.
Upvotes: 0