0

I am trying to count the number of objects in this image:

image1

I have a code for that:

import cv2
import numpy as np
image = cv2.imread('d:\obj.jpg')
blurred  = cv2.pyrMeanShiftFiltering(image,31,91) 
gray = cv2.cvtColor(blurred,cv2.COLOR_BGR2GRAY)
ret , threshold = cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
cv2.imshow("Threshold",threshold)
_, contours,_=cv2.findContours(threshold,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
print "Number of contours: %d  "%len(contours)
cv2.drawContours(image,contours,-1,(0,255,255),2)
cv2.namedWindow('Display',cv2.WINDOW_NORMAL)
cv2.imshow('Display',image)
cv2.waitKey()

the number of objects is 9, but the output is 1015.

when I try to show the the objects this is what I get:

processed image

How can I fix that? thanks to all :)

4
  • I think you're mis-interpreting the meaning of countours: it's probably an image (i.e. an array of values) rather than the number of found objects. Commented Aug 9, 2018 at 19:47
  • I’m always baffled at all the problems people try to solve using contours. You don’t need contours in this case. It is cheaper to label the image (see connected component analysis). — Did you display the result of the threshold? Does it actually yield 9 objects? This is one of the nice things about image processing, you can easily examine the result of each step to see if you're headed in the right direction. Commented Aug 9, 2018 at 20:23
  • @CrisLuengo yes I dispayed the result of threshold, it yields the objects in black dots on a white background Commented Aug 9, 2018 at 21:50
  • Does it show each object as a single dot? I presume not. Also, if the background is white, it will consider the background as the object. You should invert the result of the threshold. Commented Aug 9, 2018 at 22:05

1 Answer 1

1

You can easily get the area of contours. I would suggest putting up a threshold on area of contours. I mean to say iterate over all the contours and just keep only those which have area greater than a number specified by you and reject others. This way you can avoid small contours which are there due to noises.

Sign up to request clarification or add additional context in comments.

1 Comment

area = cv.contourArea(cnt)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.