计算等高线的周长(OpenCV,Python)

Calculating perimeter of contours (OpenCV, Python)

我这里有这张图片,上面有很多青色、品红色和黄色的小打印机点。

分离颜色通道 (CMYK) 后,我在图像上应用了阈值。

此处为青色通道。

现在我想找到一种方法来计算每个点的周长。 所以最后我想得到周长的均值和标准差。

我已经找到了一种方法(在 Whosebug 上某人的帮助下)计算点大小的均值和标准偏差:

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)    

现在换成面积,有没有办法得到周长?

很好的案例,根据 OpenCV documentation 一旦你有了轮廓,你应该能够使用 cv.arcLength() 方法计算出你想要的东西。

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.

来自官方文档的示例:

    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 

所以在你的情况下,你应该更新你的代码如下:

    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) 

我希望这有效!