python 二次遍历求连通域

def Two_Pass(binary_img:np.array,neighbor_hoods):
    """
    两次遍历计算连通域
    :param binary_img:
    :param neighbor_hoods:
    :return:
    """
    if neighbor_hoods == NEIGHBOR_HOODS_4:
        offsets = OFFSETS_4
    elif neighbor_hoods == NEIGHBOR_HOODS_8:
        offsets = OFFSETS_8
    else:
        raise ValueError

    binary_img = neighbor_value(binary_img,offsets)
    binary_img = neighbor_value_2(binary_img,offsets)

    return binary_img

def neighbor_value(binary_img:np.array,offsets):
    """
    遍历计算连通域
    :param binary_img:
    :param offsets:
    :param reverse:
    :return:
    """
    Rows = binary_img.shape[0]
    Cols = binary_img.shape[1]
    binary_img = np.array(binary_img,dtype=np.int)
    label_idx = 0
    Location = np.where(binary_img>0.5)
    if len(Location)>0:
        for i in range(len(Location[0])):
            row = Location[0][i]
            col = Location[1][i]
            neighbor = binary_img[max(0,row-2):min(row+2,Rows),max(0,col-2):min(col+2,Cols)]
            l_d = np.where(neighbor!=0)
            neighbor_ = reduce(operator.add,[neighbor[l_d[0],l_d[1]]])
            set_res = sorted(set(neighbor_))
            if len(set_res) == 1:
                label_idx += 1
                if label_idx == 255:
                    label_idx += 1
                binary_img[row][col] = label_idx
            else:
                if len(set_res) == 0:
                    print("")
                if set_res[0] == 255:
                    binary_img[row][col] = set_res[1]
                else:
                    binary_img[row][col] = set_res[0]

    return binary_img

def neighbor_value_2(binary_img:np.array,offsets):
    Rows = binary_img.shape[0]
    Cols = binary_img.shape[1]
    binary_img = np.array(binary_img,dtype=np.int)
    Location = np.where(binary_img > 0.5)
    if len(Location[0])>0:
        for i in range(len(Location[0])-1,0,-1):
            row = Location[0][i]
            col = Location[1][i]
            neighbor = binary_img[max(0,row-2):min(row+2,Rows),max(0,col-2):min(col+2,Cols)]
            l_d = np.where(neighbor != 0)
            if len(l_d[0]) == 1:
                binary_img[row][col] = 0
                continue
            neighbor_ = reduce(operator.add, [neighbor[l_d[0], l_d[1]]])
            set_res = sorted(set(neighbor_))
            if len(set_res)>1:
                binary_img[row][col] = set_res[0]

    return binary_img

说明:输入的是二值图像0和255,用的是8邻域进行分析的。

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值