find contours miss some objects
I use the following code to read through all objects that I segmented from my image which should be ordered in row and columns as semi-circle (because of segmentation and morphological processing for reducing noise):
Imgproc.Canny(srcImg, srcImg, 50, 150);
Imgcodecs.imwrite("/mnt/sdcard/DCIM/cannyImg.jpg", srcImg);//check
List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Mat hierarchy = new Mat();
Imgproc.findContours(srcImg, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE, new Point(0,0));
//int index = 0;
//double maximc = Imgproc.contourArea(contours.get(0));
for (int contourIdx = 1; contourIdx < contours.size(); contourIdx++) {
double temp;
temp = Imgproc.contourArea(contours.get(contourIdx));
if (temp > 100) {
// condition to differentiate between noise and objects
Mat drawing = Mat.zeros(srcImg.size(), CvType.CV_8UC1);
Imgproc.drawContours(drawing, contours, contourIdx, new Scalar(255), -1);
Mat resultMat = new Mat();
maskImg.copyTo(resultMat, drawing);
Imgcodecs.imwrite("/mnt/sdcard/DCIM/resultImg" + contourIdx + ".jpg", resultMat);//check
}
}
however, the loop can not read important objects in my image even canny image is correct and can identify all the objects. My questions are: in which order find contours read objects? and also is there another way in Opencv to read through all objects in the image other than find contours? last question i used the size of contours to differentiate between the objects and the noise, so is this Ok or you can suggest other methods.
Attached is the result image and the one with red circles correctly identified while the others which I need not being identified.
Any help is appreciated
int contourIdx = 0;
(you're already missing the 1st object here)if (temp > 100)
(maybe you need a better "filter" ?)I changed the contourIdx to start at 0 and the problem is still on. I thought it may be due to objects become open (not closed objects) after morphological processing; Is that could be the reason?
sounds likely. but can you try to add the canny image, and somehow highlight, where it goes wrong ?
(reduce the speculation )
@berak how to add image in here
edit your question, it has an image button.
or use markup :
![description](img_url)
Thanks @berak I added the result image.
@berak, do you know how I can find the objects myself by using the findnonezero() or countnonezero() functions to read all the objects and how to calculate the black distance between white objects.
Please help.
If I change the retrieval mode to RETR_LIST or RETR_CCOMP, I can get all the objects but with redundancy then how to get rid of redundant objects is my question.