如何获取matplotlib imshow绘制图像的边界并在同图中叠加绘制
解决方案
方法1:直接叠加绘制边界(无需额外安装依赖)
直接在你现有代码的基础上添加plt.contour调用即可实现边界叠加,不需要引入其他第三方库:
import pandas as pd import matplotlib.pyplot as plt # 你的原有代码 df = pd.read_csv('data.txt', sep='\t') plt.imshow(df, origin='lower') # 新增边界绘制代码 # levels参数填写你要提取的边界对应的数值阈值,可根据你的数据调整 plt.contour(df, levels=[127], colors='red', linewidths=2, origin='lower') plt.show()
参数说明:
levels:填写需要提取的边界对应的数值阈值,如果你不清楚合适的阈值,可以先执行print(df.describe())查看数据的数值分布,取前景和背景的中间值即可,也可以传入多个数值同时绘制多层边界colors、linewidths可根据你的显示需求调整边界的颜色和粗细
方法2:提取边界坐标后绘制(适合需要复用边界坐标的场景)
如果你需要先获取边界的具体坐标值做后续处理,可以用scikit-image的轮廓提取工具实现:
- 先安装依赖:
pip install scikit-image
- 完整实现代码:
import pandas as pd import matplotlib.pyplot as plt from skimage.measure import find_contours from skimage.filters import threshold_otsu df = pd.read_csv('data.txt', sep='\t') img = df.values plt.imshow(img, origin='lower') # 自动计算适配数据的阈值,也可以手动替换为固定数值,比如thresh = 50 thresh = threshold_otsu(img) # 提取所有符合阈值的边界坐标 contours = find_contours(img, level=thresh) # 遍历边界叠加绘制 for contour in contours: # 过滤掉长度过短的细碎小轮廓,阈值可根据需求调整 if len(contour) < 100: continue # contour返回的每一组点为[y坐标, x坐标],绘制时需要交换顺序 plt.plot(contour[:, 1], contour[:, 0], c='red', linewidth=2) # 如需保存边界坐标可执行以下代码,后续可直接加载使用 # import numpy as np # np.save('boundary_coords.npy', contours) plt.show()
内容的提问来源于stack exchange,提问作者Carefree
相关产品推荐
相关产品推荐

