counting the number of objects in an image using python

Clash Royale CLAN TAG#URR8PPP
counting the number of objects in an image using python
I am trying to count the number of objects in this image:

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:

How can I fix that?
thanks to all :)
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.
– Cris Luengo
Aug 9 at 20:23
@CrisLuengo yes I dispayed the result of threshold, it yields the objects in black dots on a white background
– Shlomi Elhaiani
Aug 9 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.
– Cris Luengo
Aug 9 at 22:05
1 Answer
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.
number
thanks :) please see my answer below
– Shlomi Elhaiani
Aug 9 at 19:53
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
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.
– toti08
Aug 9 at 19:47