首页 > 解决方案 > 图像未正确标记:如何仅返回一个连接组件?

问题描述

我想预处理图像

原始图像

以便只保留内部矩形段(即删除周围的背景)。但我没有得到正确的结果,显示为

裁剪图像.

为了我。

代码很简单:

def labelim(img):
    #labeling image
    gray = rgb2gray(img) #translate rgb to gray
    val = filters.threshold_local(gray,5)
    mask = gray > val
    clean_border = segmentation.clear_border(mask)
    labeled = label(clean_border)
    signle_labeled = np.where(labeled == 0,labeled, 1)#ensure all assigned label return as 1.
    return single_labeled
def crop_img(img, labeled):    
    cropped_images = []
    pad = 20
    for region in regionprops(labeled):
        if region.area < 2000:
            continue
        minr,minc,maxr,maxc = region.bbox
        cropped_images.append(gray[minr-pad:maxr+pad, minc-pad:maxc+pad])
    for c, cropped_image in enumerate(cropped_images):
        cropim = cropped_image
    return cropim

labeled = labelim(img)
cropped_image = crop_img(img, labeled)

测试代码适用于我的另一张图像,但不适用于大多数图像。感谢您的任何帮助/建议。

标签: pythonimage-processingimage-segmentationlabeling

解决方案


问题解决了:

这里有一个小错误:

cropped_images.append(gray[minr-pad:maxr+pad, minc-pad:maxc+pad])

应该:

cropped_images.append(img[minr-pad:maxr+pad, minc-pad:maxc+pad])

推荐阅读