You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于OpenCV/scikit-image计算地图岛屿数量与地面邻居数

使用OpenCV和scikit-image解决岛屿统计与邻居计数问题

先给出示例地图的numpy数组(避免使用Python内置关键字map,改用map_arr):

import numpy as np

map_arr = np.array([
  [0., 0., 0., 0., 0., 0.],
  [0., 0., 0., 0., 0., 0.],
  [0., 1., 1., 1., 0., 0.],
  [0., 0., 1., 0., 1., 0.],
  [0., 0., 0., 0., 1., 0.],
  [0., 0., 0., 0., 0., 0.]], dtype=np.uint8)

任务1:基于4邻域规则统计岛屿数量

OpenCV实现

利用cv2.connectedComponents函数,设置connectivity=4指定4邻域规则,返回的组件数需减去背景(标签0)的数量:

import cv2

num_labels, _ = cv2.connectedComponents(map_arr, connectivity=4)
island_count = num_labels - 1
print(f"岛屿数量:{island_count}")  # 输出:2

scikit-image实现

使用skimage.measure.label函数,设置connectivity=1对应4邻域(connectivity=2为8邻域),统计唯一标签数后减去背景标签:

from skimage import measure

label_img = measure.label(map_arr, connectivity=1)
island_count = len(np.unique(label_img)) - 1
print(f"岛屿数量:{island_count}")  # 输出:2

任务2:给定坐标(i,j),返回该位置的陆地邻居数量

基础遍历实现

直接检查目标坐标的上下左右四个邻域,统计其中值为1的数量(自动处理边界情况):

def count_land_neighbors(arr, i, j):
    count = 0
    # 检查上方邻居
    if i > 0 and arr[i-1][j] == 1:
        count += 1
    # 检查下方邻居
    if i < arr.shape[0] - 1 and arr[i+1][j] == 1:
        count += 1
    # 检查左方邻居
    if j > 0 and arr[i][j-1] == 1:
        count += 1
    # 检查右方邻居
    if j < arr.shape[1] - 1 and arr[i][j+1] == 1:
        count += 1
    return count

# 示例:坐标(2,2)的邻居数量
print(f"坐标(2,2)的陆地邻居数量:{count_land_neighbors(map_arr, 2, 2)}")  # 输出:4

OpenCV卷积实现

构造4邻域的卷积核,通过卷积操作直接得到每个位置的邻居数量:

kernel = np.array([[0, 1, 0],
                   [1, 0, 1],
                   [0, 1, 0]], dtype=np.uint8)
neighbor_count_map = cv2.filter2D(map_arr, -1, kernel)
print(f"坐标(2,2)的陆地邻居数量:{neighbor_count_map[2][2]}")  # 输出:4

scikit-image卷积实现

使用skimage.filters.rank.convolution完成卷积计算:

from skimage.filters.rank import convolution

neighbor_count_map = convolution(map_arr, kernel)
print(f"坐标(2,2)的陆地邻居数量:{neighbor_count_map[2][2]}")  # 输出:4

内容的提问来源于stack exchange,提问作者thecreator13

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 14:15:34