metsburg
metsburg

Reputation: 2021

Image format mismatch for watershed segmentation in OpenCV

I'm trying to implement a watershed segmentation using Java wrapper for OpenCV.

Here's what I'm doing:

public void watershedSegmentation(Mat image)
    {
        Mat target =  new Mat(image.rows(), image.cols(), CvType.CV_8UC3);
        Imgproc.cvtColor(image, target, Imgproc.COLOR_BGRA2RGB);

        //Conversion to 8UC1 grayscale image
        Mat grayScale = new Mat(image.rows(), image.cols(), CvType.CV_64FC1);
        Imgproc.cvtColor(image, grayScale, Imgproc.COLOR_BGR2GRAY);


        //Otsu's Threshold, applied to the grayscale image
        Imgproc.threshold(grayScale, grayScale, 0, 255, Imgproc.THRESH_OTSU);

        //constructing a 3x3 kernel for morphological opening
        Mat openingKernel = Mat.ones(3,3, CvType.CV_8U);
        Imgproc.morphologyEx(grayScale, grayScale, Imgproc.MORPH_OPEN, openingKernel, new Point(-1,-1), 3);

        //dilation operation for extracting the background
        Imgproc.dilate(grayScale, grayScale, openingKernel, new Point(-1,-1), 1);


        Imgproc.watershed(target, grayScale);

    }

Right at the point where I invoke 'watershed', I see an error which reads:

OpenCV Error: Unsupported format or combination of formats (Only 32-bit, 1-channel output images are supported) in cvWatershed, file ..\..\..\..\opencv\modules\imgproc\src\segmentation.cpp, line 151
Exception in thread "main" CvException [org.opencv.core.CvException: cv::Exception: ..\..\..\..\opencv\modules\imgproc\src\segmentation.cpp:151: error: (-210) Only 32-bit, 1-channel output images are supported in function cvWatershed
]
    at org.opencv.imgproc.Imgproc.watershed_0(Native Method)
    at org.opencv.imgproc.Imgproc.watershed(Imgproc.java:9732)
    at segmentation.Segmentation.watershedSegmentation(Segmentation.java:60)
    at segmentation.Segmentation.main(Segmentation.java:29)

I get it, OpenCV is hunting for a 32-bit 1-channel file as the output.

I have tried every possible combination:

... all of them.

The error is resilient. It refuses to go away.

Please help.

Thanks in advance.

Upvotes: 0

Views: 1498

Answers (1)

remi
remi

Reputation: 3988

Your grayscale matrix is most probably of type CV_8UC1 even if you created it using CV_64F flag, after going through Imgproc.cvtColor(image, grayScale, Imgproc.COLOR_BGR2GRAY);

watershed expects the second matrix parameter to be a CV_32F matrix, filled with initial seeds for the regions, see the doc.

[edit] Following the comments, if you just want watershed to run, you can do something like:

Mat seeds = new Mat(image.rows(), image.cols(), CvType.CV_32FC1);
for (int i = 0; i < 10; ++i) {
  // initialize 10 random seeds
  seeds.at<float>(rand()%image.rows, rand()%image.cols) = i; // translate that into the Java interface
}
Imgproc.watershed(target, seeds);

Upvotes: 3

Related Questions