Warm tip: This article is reproduced from stackoverflow.com, please click
image-processing python

Calculating perimeter of an organic shape

发布于 2020-03-27 10:28:39

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.

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:

Sample Image

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.

Thanks in advance.

EDIT: There are some things I still don't understand but this worked for me:

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) 
Questioner
Carlos
Viewed
57
33.8k 2019-07-04 13:48

Just use cv.findContours to find the contours of the white area, generally, you will have to do threshold before findContours, but since your image is black and white maybe you can ignore it.

For perimeter just use cv.arcLength for the contour you want.