title: Calculating perimeter of an organic shape
body: <p>I have used Python to calculate areas or irregular shapes on black and white images by multiplying the number of white pixels by the area of an individual pixel.</p>
  
  <p>However, now I also need to calculate the perimeter of this irregular shape. The shape may have holes in it. Here is an example image:</p>
  
  <p><a href="https://i.stack.imgur.com/guarz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/guarz.png" alt="Sample Image"></a></p>
  
  <p>Any ideas how I can go about solving this problem?
  I am not a complete newbie but I am not a coder either. Experienced beginner I guess.</p>
  
  <p>Thanks in advance.</p>
  
  <p>EDIT:
  There are some things I still don't understand but this worked for me:</p>
  
  <pre><code>import cv2
  import numpy as np
  
  
  
  def import_image(filename):
      original_image = cv2.imread(filename, cv2.IMREAD_UNCHANGED)
      return original_image
  
  #getting original file
  img = import_image('PerimeterImage.jpg')
  
  #converting to gray
  img_grey = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
  
  #set a thresh
  thresh = 1
  
  #get threshold image
  ret,thresh_img = cv2.threshold(img_grey, thresh, 255, cv2.THRESH_BINARY)
  
  #find contours
  image, contours, hierarchy = cv2.findContours(thresh_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  
  #create an empty image for contours
  img_contours = np.zeros(img.shape)
  
  perimeter = 0
  
  for c in contours:
      peri = cv2.arcLength(c, True)
      approx = cv2.approxPolyDP(c, 0.0001 * peri, True)
      cv2.drawContours(img_contours, [approx], -1, (0, 0, 255), 1)
      perimeter = perimeter + peri
  
  print(f'Perimeter = {int(round(perimeter,0))} pixels')
  
  #show image
  cv2.imshow('Output', img_contours)
  cv2.waitKey(0)
  
  #save image
  cv2.imwrite('contours.jpg', img_contours) 
  </code></pre>