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

如何使用matplotlib的plt.plot将二维二值矩阵边缘点绘制成虚线

实现方法

你可以按以下步骤实现用plt.plot()绘制虚线轮廓:

  1. 先从边缘二值矩阵中提取所有值为1的坐标点
  2. 对坐标点按轮廓顺序排序(避免直接绘制出现线条混乱的问题)
  3. 调用plt.plot()时指定虚线样式即可

针对你示例的矩形轮廓,可直接用如下代码实现:

import numpy as np
import matplotlib.pyplot as plt

# 定义已提取的边缘二值矩阵
edge_matrix = np.array([
    [0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,1,1,1,1,1,0,0,0],
    [0,0,0,1,0,0,0,1,0,0,0],
    [0,0,0,1,0,0,0,1,0,0,0],
    [0,0,0,1,1,1,1,1,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0]
])

# 提取所有边缘点的坐标
y, x = np.where(edge_matrix == 1)

# 按顺时针顺序整理轮廓点,保证连线逻辑正确
min_y, max_y = y.min(), y.max()
min_x, max_x = x.min(), x.max()

# 顺时针拼接四条边的坐标,最后补充起点完成闭合
x_seq = [*range(min_x, max_x+1), *[max_x]*(max_y - min_y -1), *range(max_x, min_x-1, -1), *[min_x]*(max_y - min_y -1), min_x]
y_seq = [*[min_y]*(max_x - min_x +1), *range(min_y+1, max_y+1), *[max_y]*(max_x - min_x +1), *range(max_y-1, min_y, -1), min_y]

# 绘制虚线轮廓
plt.figure(figsize=(6,3))
plt.plot(x_seq, y_seq, linestyle='--', c='blue', linewidth=2)

# 翻转y轴,和imshow的显示坐标系保持一致
plt.gca().invert_yaxis()
plt.axis('equal')
plt.show()

针对不规则轮廓的通用方案:

如果你的二值轮廓是不规则形状,推荐直接调用opencv的findContours接口提取有序轮廓点,无需手动排序:

import numpy as np
import matplotlib.pyplot as plt
import cv2

edge_matrix = np.array([
    [0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,1,1,1,1,1,0,0,0],
    [0,0,0,1,0,0,0,1,0,0,0],
    [0,0,0,1,0,0,0,1,0,0,0],
    [0,0,0,1,1,1,1,1,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0]
]).astype(np.uint8)

# 提取有序轮廓
contours, _ = cv2.findContours(edge_matrix, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# 取第一个轮廓(单轮廓场景)
contour = contours[0].squeeze()
# 拼接闭合轮廓的坐标
x_seq = np.append(contour[:, 0], contour[0, 0])
y_seq = np.append(contour[:, 1], contour[0, 1])

# 绘制虚线
plt.plot(x_seq, y_seq, linestyle='--', c='red', linewidth=2)
plt.gca().invert_yaxis()
plt.axis('equal')
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 09:45:00