title: Python & OpenCV: Second largest object
body: <p>I'm developing a python script to take isolate the largest and second largest objects that are matched by color in the image. I've managed to get the largest object, draw a contour around it and draw a box. However, I'm stumped to find a solution to find the second largest object. I want the second largest object to be detected separately. </p>
  
  <pre><code>import numpy as np
  import cv2
  
  font = cv2.FONT_HERSHEY_SIMPLEX
  lineType = cv2.LINE_AA
  
  im = cv2.imread('Photos/test.jpg')
  im_ycrcb = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)
  
  ball_ycrcb_mint = np.array([0, 90, 100],np.uint8)
  ball_ycrcb_maxt = np.array([25, 255, 255],np.uint8)
  ball_ycrcb = cv2.inRange(im_ycrcb, ball_ycrcb_mint, ball_ycrcb_maxt)
  #cv2.imwrite('Photos/output2.jpg', ball_ycrcb) # Second image
  areaArray = []
  count = 1
  
  _, contours, _ = cv2.findContours(ball_ycrcb, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  for i, c in enumerate(contours):
      area = cv2.contourArea(c)
      areaArray.append(area)
      areaLargest = np.argmax(areaArray)
      areaLargestMax = max(areaArray)
      areaLargestCnt = contours[areaLargest]
      x, y, w, h = cv2.boundingRect(areaLargestCnt)   
      if area == areaLargestMax and area &gt; 10000:
          cv2.drawContours(im, contours, i, (255, 0, 0), 2)
          cv2.rectangle(im, (x, y), (x+w, y+h), (0,255,0), 2)
  cv2.imwrite('Photos/output3.jpg', im)
  </code></pre>
  
  <p>I'm using the following image for testing purposes: <a href="http://i.walmartimages.com/i/p/00/75/48/06/12/0075480612575_500X500.jpg" rel="nofollow">Image of balls</a></p>
  
  <p>Any help is appreciated!</p>