Home > Net >  Calculating perimeter of contours (OpenCV, Python)
Calculating perimeter of contours (OpenCV, Python)

Time:12-10

I have this image here with lots of small printer dots in the color cyan, magenta and yellow.

After separating the color channel (CMYK) I applied a threshold on the image.

Here for the color channel cyan.

enter image description here

Now I want to find a way to calculate the perimeter for each of these dots. So in the end I want to have a mean and standard deviation for the perimeter.

I already found a way (with the help from someone here on stackoverflow) to compute the mean and std dev for the sizes of the dots with:

def compute_mean_stddev(contours_of_images):
    for contours_of_image in contours_of_images:
        count = len(contours_of_image)

        sum_list = []
        for cntr in contours_of_image:
            area = cv2.contourArea(cntr) 
            sum_list.append(area) 
            
        average = np.mean(sum_list)
        standard_deviation = np.std(sum_list)    

Instead now for the area, is there a way to get the perimeter?

CodePudding user response:

Nice case, according to the OpenCV documentation once you have the contours you should be able to calculate what you want using cv.arcLength() method.

It is also called arc length. It can be found out using cv.arcLength() function. Second argument specify whether shape is a closed contour (if passed True), or just a curve.

Exampe from official docs:

    import numpy as np
    import cv2 as cv
    img = cv.imread('star.jpg',0)
    ret, thresh = cv.threshold(img,127,255,0)
    contours, hierarchy = cv.findContours(thresh, 1, 2)
    
    cnt = contours[0]
    area = cv.contourArea()  # Area of first contour
    perimeter = cv.arcLength(cnt, True)  # Perimeter of first contour 

So in your case you should be update your code as follows:

    def compute_mean_stddev(contours_of_images):
        for contours_of_image in contours_of_images:
            count = len(contours_of_image)

            sum_list = []
            for cntr in contours_of_image:
                area = cv2.contourArea(cntr)
                perimeter = cv.arcLength(cntr, True)  
            
            average = np.mean(sum_list)
            standard_deviation = np.std(sum_list) 

I hope this works!

  • Related