title: Counting special elements on image with OpenCV and Python
body: <p>I want to count number of trees on this picture from above.</p>
  
  <p>I know how to count elements, but till now I used images with white background, so counting is much easier. But on image like this i do not know what to do:</p>
  
  <p><a href="https://i.stack.imgur.com/grbGH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/grbGH.jpg" alt="enter image description here"></a></p>
  
  <p>I converted the image to gray, and then done the threshold *(threshold value is done by hand, is there a way to find it automaticly?), my next idea is to find the 'centers' of black dots, or to 'group' them.</p>
  
  <p>I also tried to change brightness  and contrast but it didnt work. </p>
  
  <p>What should I do? 
  This is the code that I wrote:</p>
  
  <pre><code>import cv2
  import numpy as np
  
  # Read image
  img = cv2.imread('slika.jpg')
  
  # Convert image to grayscale
  gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  
  # Show grayscale image
  cv2.imshow('gray image', gray)
  cv2.waitKey(0)
  
  #BIG PROBLEM: IM FINDING VALUE OF `40` IN THE LINE BELOW MANUALLY
  
  # Inverse binary threshold image with threshold at 40,
  _, threshold_one = cv2.threshold(gray, 40 , 255, cv2.THRESH_BINARY_INV)
  
  # Show thresholded image
  cv2.imshow('threshold image', threshold_one)
  cv2.waitKey(0)
  
  # Find contours
  contours, h = cv2.findContours(threshold_one, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
  
  print('Number of trees found:', len(contours))  #GIVES WRONG RESULT
  
  # Iterate all found contours
  for cnt in contours:
  
      # Draw contour in original/final image
      cv2.drawContours(img, [cnt], 0, (0, 0, 255), 1)
  
  # Show final image
  cv2.imshow('result image', img)
  cv2.waitKey(0)
  </code></pre>
  
  <p>This is the image with treshold, I have tried to blur it (in order to connect black dots), but the final output is the same:</p>
  
  <p><a href="https://i.stack.imgur.com/pCaKe.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pCaKe.jpg" alt="enter image description here"></a></p>
  
  <p>This is the result image:</p>
  
  <p><a href="https://i.stack.imgur.com/szaCM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/szaCM.jpg" alt="enter image description here"></a></p>