opencv 找到覆盖图像中框架的区域叶的百分比

doinxwow  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(98)

我必须提取覆盖框架的叶子区域,导致相机被遮挡。
我试过canny threshold,然后找到cv2.contours并用它绘制thickness=cv2.FILLED
原始图像:

并且输出图像:

我想有输出的地方,只有离开边缘只在黑色面具和其他背景可见填充白色面具。

window_name = 'Edge Map'
title_trackbar = 'Min Threshold:'
kernel_size = 3

def CannyThreshold(imagepath):
    print(imagepath)
    image = cv2.imread(imagepath)
    #b,g,r = cv2.split(image)
    #leaf = image[...,0]
    #print(leaf.shape)
    img2 = image.copy()
    img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    img_blur = cv2.blur(img_gray, (3,3))
    #img_blur = cv2.GaussianBlur(img_gray, (5, 5), 0)
    
    detected_edges = cv2.Canny(img_blur, 30,150, kernel_size)
    contours, hierarchy = cv2.findContours(detected_edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    #filtered_contours = [contour for contour in contours if cv2.contourArea(contour) > 100]
    
    mask = np.zeros(img2.shape, np.uint8)
    mask = cv2.drawContours(mask, contours, -1, (255,255,255),thickness=cv2.FILLED)
    
    
    cv2.imshow('thres',mask)
    cv2.imshow('img', image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
f0brbegy

f0brbegy1#

根据您的描述和代码,您似乎想将叶子的边缘提取为黑色蒙版,并将背景填充为白色。下面是您的代码的更新版本,应该可以实现这一点:

def extract_leaf_edges(imagepath):
    image = cv2.imread(imagepath)
    img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    img_blur = cv2.blur(img_gray, (3, 3))

    edges = cv2.Canny(img_blur, 30, 150)

    contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    mask = np.zeros_like(image)
    cv2.drawContours(mask, contours, -1, (255, 255, 255), thickness=cv2.FILLED)

    mask_gray = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
    mask_gray_inv = cv2.bitwise_not(mask_gray)

    result = cv2.bitwise_and(image, image, mask=mask_gray_inv)

    cv2.imshow('Leaf Edges', result)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

image_path = 'path_to_your_image.jpg'
extract_leaf_edges(image_path)

在这个更新的代码中,我修改了draw Contours函数,在黑色蒙版上用白色(255,255,255)填充轮廓。然后,我将蒙版转换为灰度,并应用逐位操作来提取叶子边缘,并将它们显示在黑色背景上。
确保将'path_to_your_image.jpg'替换为输入图像的实际路径。

相关问题