I want to split an image into h,s and v channels. But an error occured every time and the reason seems to be that opencv split
function does not work properly.
My code:
Mat src, srcHSV;
Mat srcH;
vector<Mat> channels;
VideoCapture cap(0);
for(int frame = 0; ; frame++)
{
cap >> src;
imshow("camera image", src);
cvWaitKey(1);
cvtColor(src, srcHSV, CV_BGR2HSV);
imshow("hsv image", srcHSV);
cvWaitKey(1);
split(srcHSV, channels);
srcH = channels[0];
... //do something with srcH
}
Camera image and hsv image are OK. But when it executes srcH = channels[0]
, an error message says:
Unhandled exception at 0x012d1602 in xxx.exe: 0xC0000005: Access violation reading location 0x00000014.
I set a breakpoint here and checked the value of channels
. It comprises of many elements, but each element is an unknown object.
I saw a post talking about the similar problem but there was no answer. split image to 3 channels opencv error.
[solved]
According to @nowaqq 's comments and @Andrey Smorodov 's answer, my code now looks like this:
for(int frame =0 ; ; frame ++)
{
vector<Mat> channels; //put the channels declaration inside the for-loop
cap >> src;
imshow("camera image", src);
cvWaitKey(1);
srcHSV = Mat::zeros(Size(src.rows, src.cols), CV_8UC3);
cvtColor(src, srcHSV, CV_BGR2HSV);
imshow("hsv image", srcHSV);
cvWaitKey(1);
channels.clear();
channels.resize(srcHSV.channels()); //resize channels
cv::split(srcHSV, &channels[0]); //&channels[0] instead of channels as the second parameter to split function
srcH = channels[0];
...//do something with srcH
}
[updated]
I struggled to solve another problem, this problem was also solved as a side-effect. See my answer below.