Rafael Bartz
Rafael Bartz

Reputation: 328

Android OpenCv HoughCircles

I'm trying to use android-opencv 2.3.1 to recognize circles (coins) in an image. However an error occurs (org.opencv.cvException) by executing the method Imgproc.cvtColor.

File imgFile = new File(Environment.getExternalStorageDirectory() + "/test.jpg");
imageBmp = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

Mat mImg = new Mat();
mImg = Utils.bitmapToMat(imageBmp);        
Mat mGray = new Mat(mImg.rows(), mImg.cols(), CvType.CV_8UC1, new Scalar(0));
Imgproc.cvtColor(mImg , mGray, Imgproc.COLOR_BGRA2GRAY, 4); 
Imgproc.GaussianBlur( mGray , mGray , new Size(9, 9), 2, 2);
Mat circles = new Mat();
Imgproc.HoughCircles(mGray , circles, Imgproc.CV_HOUGH_GRADIENT, 1d, (double)  
                    mGray.height() / 70, 200d, 100d);   

What am I doing wrong? Cellphone: Samsung Galaxy S i9000


Just updating my question with the new code. It is still giving the same error by "Imgproc.cvtColor" method.

File imgFile = new File(Environment.getExternalStorageDirectory() + "/test.jpg");
imageBmp = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
Mat mImg = new Mat();
mImg = Utils.bitmapToMat(imageBmp);
Mat mGray = new Mat(mImg.rows(), mImg.cols(), CvType.CV_8UC1);
Imgproc.cvtColor(mImg, mGray, Imgproc.COLOR_BGRA2GRAY);
Imgproc.GaussianBlur(mGray, mGray, new Size(9, 9), 2, 2);
Mat circleImage = new Mat(mGray.rows(), mGray.cols(), CvType.CV_8UC1);
Imgproc.HoughCircles(mGray, circleImage, Imgproc.CV_HOUGH_GRADIENT, 1d,
         (double) mGray.height() / 70, 200d, 100d);

Upvotes: 1

Views: 3761

Answers (1)

fireant
fireant

Reputation: 14530

I'm not a Java programmer, but can see two problems in your code. First, the value of the last argument in cvtColor() shoudn't be 4. Change this

Imgproc.cvtColor(mImg , mGray, Imgproc.COLOR_BGRA2GRAY, 4);

to this

Imgproc.cvtColor(mImg , mGray, Imgproc.COLOR_BGRA2GRAY);

Since it's converting from BGRA to grayscale, it understands the destination (mGray) is single channel.

Second, why are you passing new Scalar(0) to

Mat mGray = new Mat(mImg.rows(), mImg.cols(), CvType.CV_8UC1, new Scalar(0));

? that probably is messing things up. I would call the constructor that allocates the memory for the image:

Mat mGray = new Mat(mImg.rows(), mImg.cols(), CvType.CV_8UC1);

Edit: now probably the problem is in the way you're reading the image and converting to Mat. I would replace this

imgFile.getAbsolutePath()
mImg = Utils.bitmapToMat(imageBmp);

by this

Mat mImg = Highgui.imread(imgFile.getAbsolutePath());

and then make sure mImg.rows() returns the correct value. Please let me know how it goes.

Upvotes: 2

Related Questions