I try to subtract using bitwise_and and BackgroundSubtractor but I have this error:
OpenCV Error: Assertion failed ((mtype == CV_8U || mtype == CV_8S) && _mask.sameSize(*psrc1)) in cv::binary_op, file C:\build\master_winpack-build-win64-vc14\opencv\modules\core\src\arithm.cpp, line 241
code:
Mat frame1;
Mat frame_mask;
bool bSuccess = cap.read(frame1);
if (!bSuccess) //if not success, break loop
{
cout << "Cannot read a frame from video stream" << endl;
break;
}
pMOG2->apply(frame1, frame_mask);
Mat kernel = Mat::ones(frame1.size(), CV_8UC1);
erode(frame1, frame_mask, kernel);
bitwise_and(frame1, frame1, frame, frame_mask);
Error occurs when I use bitwise_and(...) after erode. Separately they work fine.
I used OpenCV 3.2.0 and VS15. I'm pretty new at the OpenCV, so could you please say, what I do wrong? Thank you.
The error is raised because your frame_mask
is not of type CV_8U or CV_8S.
Indeed, with this line : erode(frame1, frame_mask, kernel)
frame_mask
is transformed into a CV_8UC3 Mat
because the input Mat
(frame1
) is of type CV_8UC3.
Anyways, I don't really understand what you are trying to do with the bitwise_and
operation so I did a minimal example to show the proper way to do what you want:
int main(int argc, char** argv)
{
Ptr<BackgroundSubtractor> pMOG2 = createBackgroundSubtractorMOG2();
VideoCapture cap = VideoCapture(0);
Mat frame1, frame_mask;
while (cap.isOpened())
{
cap.read(frame1);
pMOG2->apply(frame1, frame_mask);
Mat kernel = getStructuringElement(MORPH_ELLIPSE, Size(3, 3)); // erode filter's kernel
erode(frame_mask, frame_mask, kernel);
Mat movingAreas;
frame1.copyTo(movingAreas, frame_mask);
imshow("movingParts", movingAreas);
keyCode = waitKey(1);
if (keyCode == 27 || keyCode == 'q' || keyCode == 'Q')
break;
}
return 0;
}
Hope it helps!