title: How can i count segments in an image in python?
body: <p>I am new to image processing and python. You might've seen my amateur codes on this site in the last couple of days.</p>
  <p>I am trying to count the number of trees using aerial images. This is my code:</p>
  <pre><code>from PIL import Image
  import cv2
  import numpy as np
  from skimage import io, filters, measure
  from scipy import ndimage
  
  img = Image.open(&quot;D:\\Texture analysis\\K-2.jpg&quot;)
  row, col = img.size
  
  hsvimg = img.convert('HSV')
  hsvimg.mode = 'RGB'
  hsvimg.save('newImage2.jpg')
  
  npHSI = np.asarray(hsvimg)                  #Convert HSI Image to np image
  
  blur = cv2.GaussianBlur(npHSI, (45, 45), 5)
  
  assert isinstance(blur, np.ndarray)         ##############################
  assert len(blur.shape) == 3                 #Convert np Image to HSI Image
  assert blur.shape[2] == 3                   ##############################
  
  hsiBlur = Image.fromarray(blur, 'RGB')
  hsiBlur.save('hsiBlur.jpg')                 #Save the blurred image
  
  ## Read
  img = cv2.imread(&quot;D:\\Texture analysis\\hsiBlur.jpg&quot;)
  
  ## convert to hsv
  hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
  
  #Threshold the image and segment the trees
  mask = cv2.inRange(hsv, (36, 25, 25), (70, 255,255))
  imask = mask&gt;0
  green = np.zeros_like(img, np.uint8)
  green[imask] = img[imask]
  
  ## save 
  cv2.imwrite(&quot;green.png&quot;, green)
  
  #Count the number of trees
  im = io.imread('green.png', as_grey=True)
  val = filters.threshold_otsu(im)
  drops = ndimage.binary_fill_holes(im &lt; val)
  labels = measure.label(drops)
  print(labels.max())
  </code></pre>
  <p>Original image:
  <a href="https://i.stack.imgur.com/vm7Tt.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vm7Tt.jpg" alt="K-2.jpg" /></a></p>
  <p>HSI  image with gaussian filter:
  <a href="https://i.stack.imgur.com/yAzhA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yAzhA.jpg" alt="hsiBlur.jpg" /></a></p>
  <p>Segmented image:
  <a href="https://i.stack.imgur.com/04uX3.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/04uX3.jpg" alt="green.png" /></a></p>
  <p>The last part of the code returns <code>7</code>, which is a wrong output. The value should be above 50. How can I properly count the number of green segments in the final segmented image?</p>
  <p><strong>EDIT</strong></p>
  <p>I converted <code>green.png</code> to binary and applied erosion with a <code>3x3 filter</code> and <code>iterated it 7 times</code> to remove the noise.
  This is what I did at the end. I followed this <a href="https://stackoverflow.com/questions/38619382/how-to-count-objects-in-image-using-python">stackoverflow link</a></p>
  <pre><code>##save
  cv2.imwrite(&quot;green.png&quot;, green)
  
  #Convert to grayscale
  gray = np.dot(green[...,:3], [0.299, 0.587, 0.114])
  cv2.imwrite(&quot;grayScale.jpg&quot;, gray)
  
  #Binarize the grayscale image
  ret,bin_img = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
  cv2.imwrite(&quot;bin_img.jpg&quot;, bin_img)
  
  #Erosion to remove the noise
  kernel = np.ones((3, 3),np.uint8)
  erosion = cv2.erode(gray, kernel, iterations = 7)
  cv2.imwrite(&quot;erosion.jpg&quot;, erosion)
  
  #Count the number of trees
  finalImage = cv2.imread('erosion.jpg')
  finalImage = cv2.cvtColor(finalImage, cv2.COLOR_BGR2GRAY)
  ret, thresh = cv2.threshold(finalImage, 127, 255, 1)
  im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  for cnt in contours:
      cv2.drawContours(finalImage,[cnt],0,(0,0,255),1)
  </code></pre>
  <p><strong>Saurav</strong> mentioned in his answer <strong><em>... size of &quot;contours&quot; will give you the count</em></strong>. This <code>print(contour.size())</code>gives an error and <code>print(contour)</code> just prints a long 2D array. How can i get the size of contour?</p>
  <p>PS. I didn't upload the grayscale, binary and eroded image because i felt that the images were already taking too much space, I can still upload them if anyone wants to.</p>