Python获取区域面积

时间:2023-03-08 23:19:05
Python获取区域面积

import cv2
import numpy as np

def get_leave_areas(image):

    img = cv2.imread(image)
    GrayImage = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret, threshed_img = cv2.threshold(GrayImage, 160, 255,cv2.THRESH_BINARY)    # 二值化, 阈值偏高
    image, contours, hierarchy = cv2.findContours(threshed_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)    # 注意OpenCV3中, findContours的返回参数成了三个
    small_areas = [i for i in contours if cv2.contourArea(i) < 200]    # 去除小面积的(通常为干扰)
    cv2.fillPoly(threshed_img, small_areas, 255)

    # 统计
    area_pixel = 0
    for i in np.array(threshed_img).flatten():
        if i == 0:
            area_pixel += 1
    area_inch = area_pixel / (96 * 96)    # 除以dpi, 算出实际生活中的面积
    return area_inch

本文版权归郑鹏(默盒)和博客园共有,原创文章,未经允许不得转载,否则保留追究法律责任的权利。