7.2 二维数组找数组最边上的不为0的坐标

如下图的二维数组,要获得所有的最外围的值不为0的坐标。

其代码如下:

python 复制代码
import cv2
import numpy as np


#2.找矩阵save_list边界的位置
 #输入为save_list,输出为剩下边界坐标的save_list
def boundary(s):

    print(s)
    list1={}#按照横坐标从小到大的顺序的坐标位置
    list2=[]
    for i in range(len(s)):
        list1[str(i)]=[]
        for j in range(len(s[0])):
            if s[i][j]!=0:
                list1[str(i)].append((i,j))
                list2.append((i,j))

    list2=sorted(list2,key=lambda x:x[1])
    list_over={}#按照纵坐标从小到大的顺序的坐标位置
    for item in list2:
        if str(item[1]) not in list_over:
            list_over[str(item[1])]=[]
            list_over[str(item[1])].append(item)
        else:
            list_over[str(item[1])].append(item)

    print(list1)
    print(list_over)

    #以上代码获得了两个字典
    #下面获得该矩阵最外围的坐标
    save_list=[]
    for item in list1:
        #print(item)
        if len(list1[item])==1:
            save_list.append(list1[item][0])
        else:
            save_list.append(list1[item][0])
            save_list.append(list1[item][-1])

    for item in list_over:
        if list_over[item][-1] not in save_list:
            save_list.append(list_over[item][-1])

    save_list=sorted(save_list)

    return save_list

if __name__ == '__main__':

    data1 = [
        [0, 0, 0, 1, 0, 0, 0],
        [0, 1, 1, 1, 1, 1, 0],
        [0, 1, 1, 1, 1, 1, 0],
        [1, 1, 1, 1, 1, 1, 1],
        [0, 1, 1, 1, 1, 1, 0],
        [0, 1, 1, 1, 1, 1, 0],
        [0, 0, 0, 1, 0, 0, 0]
    ]
    save_list=boundary(data1)
    print(save_list)
相关推荐
zhangfeng11331 天前
国家超算中心 scnet.cn 跨用户文件分享流程总结 多个用户之间 文件共享 不需要反复下载上传
人工智能·语言模型·大模型
ting94520001 天前
Tornado 全栈技术深度指南:从原理到实战
人工智能·python·架构·tornado
果汁华1 天前
Browserbase Skills:让 Claude Agent 真正“看见“网页世界
人工智能·python
ZhengEnCi1 天前
04-缩放点积注意力代码实现 💻
人工智能·python
2zcode1 天前
基于LSTM神经网络的金属材料机器学习本构模型研究(硕士级别)
神经网络·机器学习·lstm·金属材料
HackTwoHub1 天前
AI大模型网关存在SQL注入、附 POC 复现、影响版本LiteLLM 1.81.16~1.83.7(CVE-2026-42208)
数据库·人工智能·sql·网络安全·系统安全·网络攻击模型·安全架构
段一凡-华北理工大学1 天前
【高炉炼铁领域炉温监测、预警、调控智能体设计与应用】~系列文章08:多模态数据融合:让数据更聪明
人工智能·python·高炉炼铁·ai赋能·工业智能体·高炉炉温
网络工程小王1 天前
【LangChain 大模型6大调用指南】调用大模型篇
linux·运维·服务器·人工智能·学习
HIT_Weston1 天前
63、【Agent】【OpenCode】用户对话提示词(示例)
人工智能·agent·opencode
phoenix@Capricornus1 天前
从贝叶斯决策到最小距离判别法再到Fisher判别分析
机器学习