简体   繁体   中英

OpenCV Error: Assertion failed (scn == 3 || scn == 4) while using Watershed in OpenCV android sdk

I am working on an Android application that used the OpenCV-2.4.8 android sdk . The following sample code tries to detect an object using the Watershed segmenter algorithm of the OpenCV library.

//bmp is the source bitmap that I am reading from a Drawable resource.
Mat mBackgroundMat = new Mat(new Size(bmp.getWidth(), bmp.getHeight()), CvType.CV_8UC3);
Utils.bitmapToMat(bmp, mBackgroundMat);

//Initialize the Mat Objects
Mat backgroundMat = new Mat();
Mat greyMatImg = new Mat();
Mat thresholdImg = new Mat();
Mat markerImg = new Mat();

//Erode and dillate
Imgproc.erode(mBackgroundMat, backgroundMat, new Mat(), new Point(-1, -1), 12);
Imgproc.dilate(backgroundMat, backgroundMat, new Mat(), new Point(-1, -1), 12);
//      Imgproc.cvtColor(backgroundMat, backgroundMat, Imgproc.COLOR_RGB2BGR);
Imgproc.cvtColor(backgroundMat, greyMatImg, Imgproc.COLOR_BGR2GRAY);
Imgproc.threshold(greyMatImg, thresholdImg, 0, 255, Imgproc.THRESH_BINARY_INV);
Imgproc.distanceTransform(thresholdImg, markerImg, Imgproc.CV_DIST_L2, Imgproc.CV_DIST_MASK_5);
Imgproc.cvtColor(thresholdImg, thresholdImg, Imgproc.COLOR_GRAY2BGR, 3);

Mat tempMat = new Mat(markerImg.rows(), markerImg.cols(), CvType.CV_32SC1);
Imgproc.cvtColor(markerImg, tempMat, CvType.CV_32SC1, 0);
Imgproc.watershed(thresholdImg, tempMat);

//Release unused mats.
tempMat.release();
backgroundMat.release();
greyMatImg.release();
markerImg.release();

//Output thresholdImg

I am getting the following error:

cv::error()(2566): OpenCV Error: Assertion failed (scn == 3 || scn == 4) in void cv::cvtColor(InputArray, OutputArray, int, int), file /home/reports/ci/slave_desktop/50-SDK/opencv/modules/imgproc/src/color.cpp, line 3648

Please help me in figuring out what I am doing wrong here.

Imgproc.cvtColor(markerImg, tempMat, CvType.CV_32SC1, 0);

I think it is this line - opencv is complaining about markerImg not being a 3 or 4 channel image. It looks like the Mats in this call have the same number of channels so perhaps you just need to convert between data types; the result of distanceTransform seems to give a CV_32FC1 so you could try just converting like this:

    markerImg.convertTo(tempMat, CvType.CV_32SC1);

I had a similar error...

In my case, the error was because the Mat didn't have data.

Try to do this validation:

`if(!src.data) //where src is the Mat with the image
{
Log.d("Error","Adios");
    exit(0);
}`

If you don't have data in src, then you won't convert this to Bitmap

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM