首页 > 解决方案 > 在 Canny 边缘检测中应用自适应阈值

问题描述

我想在我的项目数据集中删除图像的模糊背景,我已经在这里使用 Canny 边缘检测获得了一个非常好的解决方案。我想对 Canny 的双阈值要求应用自适应阈值。我很感激这方面的任何帮助。

imageNames = glob.glob(r"C:\Users\Bikir\Pictures\rTest\*.jpg")
count=0
for i in imageNames:        
 
    img = Image.open(i)
    img = np.array(img)    

    # grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # canny - I want this two values (0 and 150) to be adaptive in this case      
    canned = cv2.Canny(gray, 0, 150)

    # dilate to close holes in lines
    kernel = np.ones((3,3),np.uint8)
    mask = cv2.dilate(canned, kernel, iterations = 1);

    # find contours
    # Opencv 3.4, if using a different major version (4.0 or 2.0), remove the first underscore
    _, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE);

    # find the biggest contour
    biggest_cntr = None;
    biggest_area = 0;
    for contour in contours:
        area = cv2.contourArea(contour);
        if area > biggest_area:
            biggest_area = area;
            biggest_cntr = contour;

    # draw contours
    crop_mask = np.zeros_like(mask);
    cv2.drawContours(crop_mask, [biggest_cntr], -1, (255), -1);

    # opening + median blur to smooth jaggies
    crop_mask = cv2.erode(crop_mask, kernel, iterations = 5);
    crop_mask = cv2.dilate(crop_mask, kernel, iterations = 5);
    crop_mask = cv2.medianBlur(crop_mask, 21);

    # crop image
    crop = np.zeros_like(img);
    crop[crop_mask == 255] = img[crop_mask == 255];    

    img = im.fromarray(crop)
    img.save(r"C:\Users\Bikir\Pictures\removed\\"+str(count)+".jpg") 

    count+=1

标签: image-segmentationedge-detectioncanny-operatorimage-thresholding

解决方案


推荐阅读