图像物体的边界 python版本

给定一个二维数组M行N列,二维数组里的数字代表图片的像素,为了简化问题,仅包含像素1和5两种像素,每种像素代表一个物体,2个物体相邻的格子为边界,求像素1代表的物体的边界个数。
像素1代表的物体的边界指与像素5相邻的像素1的格子,边界相邻的属于同一个边界,相邻需要考虑8个方向(上,下,左,右,左上,左下,右上,右下)。
其他约束:
地图规格约束为:
0<M<100
0<N<100
1)如下图,与像素5的格子相邻的像素1的格子(0,0)、(0,1)、(0,2)、(1,0)、(1,2)、(2,0)、(2,1)、(2,2)、(4,4)、(4,5)、(5,4)为边界,另(0,0)、(0,1)、(0,2)、(1,0)、(1,2)、(2,0)、(2,1)、(2,2)相邻,为1个边界,(4,4)、(4,5)、(5,4)相邻,为1个边界,所以下图边界个数为2。
在这里插入图片描述
2)如下图,与像素5的格子相邻的像素1的格子(0,0)、(0,1)、(0,2)、(1,0)、(1,2)、(2,0)、(2,1)、(2,2)、(3,3)、(3,4)、(3,5)、(4,3)、(4,5)、(5,3)、(5,4)、(5,5)为边界,另这些边界相邻,所以下图边界个数为1。注:(2,2)、(3,3)相邻。

在这里插入图片描述

输入描述:

  • 第一行,行数M,列数N 第二行开始,是M行N列的像素的二维数组,仅包含像素1和5

输出描述:

  • 像素1代表的物体的边界个数。如果没有边界输出0(比如只存在像素1,或者只存在像素5)。
def count_border(i, j):
    if i > 0:
        if nums[i-1][j] == 0:
            nums[i-1][j] = -1
            count_border(i-1, j)
        if j > 0 and nums[i-1][j-1] == 0:
            nums[i-1][j-1] = -1
            count_border(i-1, j-1)
        if j < col - 1 and nums[i-1][j+1] == 0:
            nums[i-1][j+1] = -1
            count_border(i-1, j+1)
    if j > 0 and nums[i][j-1] == 0:
        nums[i][j-1] = -1
        count_border(i, j-1)
    if i < row - 1:
        if nums[i+1][j] == 0:
            nums[i+1][j] = -1
            count_border(i+1, j)
        if j > 0 and nums[i+1][j-1] == 0:
            nums[i+1][j-1] = -1
            count_border(i+1, j-1)
        if j < col - 1 and nums[i+1][j+1] == 0:
            nums[i+1][j+1] = -1
            count_border(i+1, j+1)
    if j < col - 1 and nums[i][j+1] == 0:
        nums[i][j+1] = -1
        count_border(i, j+1)

def find_border():
    count = 0
    for i in range(row):
        for j in range(col):
            if nums[i][j] == 0:
                count += 1
                nums[i][j] = -1
                count_border(i, j)
    return count

# 读取输入
row, col = map(int, input().split())
nums = [list(map(int, input().split())) for _ in range(row)]

# 遍历出5的位置并将其边界记录为0
for i in range(row):
    for j in range(col):
        if nums[i][j] == 5:
            if i > 0 and j > 0:
                nums[i-1][j-1] = 0
            if i > 0:
                nums[i-1][j] = 0
            if i > 0 and j < col-1:
                nums[i-1][j+1] = 0
            if j > 0:
                nums[i][j-1] = 0
            if i > 0 and j < col-1:
                nums[i][j+1] = 0
            if i < row-1 and j > 0:
                nums[i+1][j-1] = 0
            if i < row-1 and j > 0:
                nums[i+1][j] = 0
            if i < row-1 and j < col-1:
                nums[i+1][j+1] = 0

result = find_border()
print(result)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值