本文介绍了matplotlib轮廓可以匹配像素边缘吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何勾画matplotlib中的像素边界?例如,对于像下面这样的半随机数据集,

How to outline pixel boundaries in matplotlib? For instance, for a semi-random dataset like the one below,

# 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的像素边缘匹配的轮廓 优于轮廓函数的默认行为,在轮廓函数中,轮廓线有效地绘制在边缘像素的对角线上

it is quite clear that a contour matching the pixel edges of image would be preferred to the default behavior of the contour function, where the contour lines are effectively drawn across the diagonals of edge pixels.

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

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

How to make the contours align with the pixels? I'm looking for a solution within numpy and matplotlib libraries.

推荐答案

如果图像的分辨率为每单位1像素,您将如何定义像素的边缘"?与像素本身相比,边缘"的概念仅在分辨率提高的帧中才有意义,并且contour如果与图像本身具有相同的分辨率,则无法绘制任何边缘.

If the image has a resolution of 1 pixel per unit, how would you define the "edge" of a pixel? The notion of "edge" only makes sense in a frame of increased resolution compared to the pixel itself and contour cannot draw any edges if it is working with the same resoltion as the image itself.

另一方面,当然可以增加分辨率,以使"edge"概念具有含义.假设我们将分辨率提高了100倍,就可以使用contour图轻松绘制边缘.

On the other hand, it is of course possible to increase the resolution such that the notion "edge" carries a meaning. So let's say we increase the resolution by a factor of 100 we can easily draw the edges using a contour plot.

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()

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

For comparison, we can also draw the image itself in the same plot using imshow.

这篇关于matplotlib轮廓可以匹配像素边缘吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 11:37