Pax0r
Pax0r

Reputation: 2473

OpenCV on Android converting to grayscale not working

I am trying to convert some OpenCV Mat to grayscale for Contours detection algorithms. For some reason the image after convertion is all black. Mine code (b is Android Bitmap):

Mat tmp = new Mat (b.getWidth(), b.getHeight(), CvType.CV_8UC1);
Utils.bitmapToMat(b, tmp);
Imgproc.cvtColor(tmp, tmp, Imgproc.COLOR_BGR2GRAY);
//there could be some processing
Imgproc.cvtColor(tmp, tmp, Imgproc.COLOR_GRAY2BGRA, 4);
Utils.matToBitmap(tmp, b);

And now I am drawing this bitmap and it is all black. When I applied contour detection to this bitmap (in place of comment) there were no match, so I assume problem is with convertion. After removing convertion (simply call bitmapToMat and matToBitmap) then bitmap is not all black so convertion to Mat are also working. Bitmap is in ARGB_8888 and there are no errors, just the output bitmap is all black.

Edit: Just to be sure I tried to save a bitmap with ocv imwrite - it's still all black so the problem is for 100% at cvtColor...

Upvotes: 6

Views: 13289

Answers (2)

Gaby Bou Tayeh
Gaby Bou Tayeh

Reputation: 151

I tried this method and it works perfectly, first you must convert it into grey scale, then to Canny, and finally to Bitmap.

this function returns a black and white image.

public static Bitmap edgesim(Mat img1) {

Bitmap image1;

//mat gray img1 holder
Mat imageGray1 = new Mat();

//mat canny image
Mat imageCny1 = new Mat();

//mat canny image
Mat imageCny2 = new Mat();

/////////////////////////////////////////////////////////////////

//Convert img1 into gray image
Imgproc.cvtColor(img1, imageGray1, Imgproc.COLOR_BGR2GRAY);

//Canny Edge Detection
Imgproc.Canny(imageGray1, imageCny1, 10, 100, 3, true);

///////////////////////////////////////////////////////////////////

//////////////////Transform Canny to Bitmap/////////////////////////////////////////
image1= Bitmap.createBitmap(imageCny1.cols(), imageCny1.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(imageCny1, image1);

return image1;

}

Upvotes: 0

Karthik Balakrishnan
Karthik Balakrishnan

Reputation: 4383

If the bitmap b is from the android device, then try using COLOR_RGB2GRAY instead of COLOR_BGR2GRAY because BGR is the default pixel format for OpenCV images, not all images.

Try this code:

Mat tmp = new Mat (b.getWidth(), b.getHeight(), CvType.CV_8UC1);
Utils.bitmapToMat(b, tmp);
Imgproc.cvtColor(tmp, tmp, Imgproc.COLOR_RGB2GRAY);
//there could be some processing
Imgproc.cvtColor(tmp, tmp, Imgproc.COLOR_GRAY2RGB, 4);
Utils.matToBitmap(tmp, b);

Upvotes: 7

Related Questions