python - matplotlib 轮廓可以匹配像素边缘吗?

标签 python numpy matplotlib

如何在 matplotlib 中绘制像素边界?例如,对于如下所示的半随机数据集,

# the code block that follows is irrelevant
import numpy as np
k = []
for s in [2103, 1936, 2247, 2987]:
    np.random.seed(s)
    k.append(np.random.randint(0, 2, size=(2,6)))
arr = np.hstack([np.vstack(k)[:, :-1], np.vstack(k).T[::-1].T ])
image = np.zeros(shape=(arr.shape[0]+2, arr.shape[1]+2))
image[1:-1, 1:-1] = arr

很明显,与 image 的像素边缘匹配的轮廓优于轮廓函数的默认行为,在默认行为中轮廓线被有效地绘制边缘像素的对角线。

import matplotlib.pyplot as plt
plt.contour(image[::-1], [0.5], colors='r')

binary_invader

如何使轮廓与像素对齐?我正在 numpymatplotlib 库中寻找解决方案。

最佳答案

如果图像的分辨率为每单位 1 个像素,您将如何定义像素的“边缘”? “边缘”的概念仅在与像素本身相比分辨率更高的帧中才有意义,如果 contour 使用与图像本身相同的分辨率,则无法绘制任何边缘。

另一方面,当然可以提高分辨率,这样“边缘”的概念就有意义了。因此,假设我们将分辨率提高 100 倍,我们可以使用 contour 图轻松绘制边缘。

import matplotlib.pyplot as plt
import numpy as np

k = []
for s in [2103, 1936, 2247, 2987]:
    np.random.seed(s)
    k.append(np.random.randint(0, 2, size=(2,6)))
arr = np.hstack([np.vstack(k)[:, :-1], np.vstack(k).T[::-1].T ])
image = np.zeros(shape=(arr.shape[0]+2, arr.shape[1]+2))
image[1:-1, 1:-1] = arr


f = lambda x,y: image[int(y),int(x) ]
g = np.vectorize(f)

x = np.linspace(0,image.shape[1], image.shape[1]*100)
y = np.linspace(0,image.shape[0], image.shape[0]*100)
X, Y= np.meshgrid(x[:-1],y[:-1])
Z = g(X[:-1],Y[:-1])

plt.imshow(image[::-1], origin="lower", interpolation="none", cmap="Blues")

plt.contour(Z[::-1], [0.5], colors='r', linewidths=[3], 
            extent=[0-0.5, x[:-1].max()-0.5,0-0.5, y[:-1].max()-0.5])

plt.show()

enter image description here

为了比较,我们还可以使用 imshow 在同一图中绘制图像本身。

关于python - matplotlib 轮廓可以匹配像素边缘吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40892203/

相关文章:

python - 二维数组的按行 numpy.isin

python - 在python中读取yaml文件时如何跳过行?

python - 使用 pdb 调试 flask

python - Pandas Series.filter.values 返回与 numpy 数组不同的类型

python - 将 NumPy 数组转换为 Python 列表

python - 查找 numpy 数组中值的位置

python - pyplot.scatter : How does one set color of points from low --> high?

python - 如何设置只有整数的 x 轴刻度线?

python - 根据已过滤的 pandas 数据帧绘制定义的 x/y 范围的 pcolormesh,即使该行或列不存在于已过滤的数据帧中

python - Matplotlib - 从 wav 文件绘制波形