如何使用matplotlib在图像上绘制线?

2024-10-03 15:35:46 发布

您现在位置:Python中文网/ 问答频道 /正文

当我试图在一个图像上绘制多条直线时,我遇到了一个问题。这是我的代码:

fig=plt.figure()
final = cv2.imread('frame9.jpg')
for p in polar:
    plt.plot([0,1],[p[0],p[0]],c='red')
plt.imshow(final,cmap=plt.cm.gray)
plt.show()

Mypolarndarray:

[[ 7.28073704e+01 -1.60300574e-02  3.00000000e+00]
 [ 1.68751118e+02 -2.28065027e-02  4.00000000e+00]
 [ 2.10662349e+02 -3.40033470e-02  6.00000000e+00]
 [ 1.20656915e+02 -1.65935831e-02  5.00000000e+00]
 [ 2.28887705e+01 -8.43417664e-04  5.00000000e+00]
 [ 1.27472877e+01 -7.25424861e-03  2.00000000e+00]
 [ 1.09924214e+02 -1.81133209e-02  3.00000000e+00]
 [ 5.85000000e+01  0.00000000e+00  4.00000000e+00]
 [ 1.57589902e+02 -1.70840018e-02  3.00000000e+00]]

结果仅显示原始图像,上面没有任何线条。
这是因为极性ndarray吗?还是别的什么?谁能帮帮我吗


Tags: 代码in图像forfig绘制pltcv2
2条回答

由于默认情况下在图像顶部绘制线条,因此调用draw函数的顺序在这里并不重要

要在图像上画东西,知道图像的坐标很重要。为此,^{}有一个extent=参数,其限制在x和y方向。从这个问题上看,图像的精确坐标并不清楚,因此我在示例中使用了一些任意值

imshow强制纵横比等于范围。这样,照片和地图就不会变形。但对于计算值,您通常不需要这样固定的纵横比。你可以用aspect='auto'来改变它

还请注意,默认图像是以原点在顶部绘制的,因为这是大多数图像格式的标准。有时,在顶部绘制时,可能需要将原点置于底部(origin='lower'vsorigin='upper'

from matplotlib import pyplot as plt
import numpy as np

polar = np.array([[7.28073704e+01, -1.60300574e-02, 3.00000000e+00],
                  [1.68751118e+02, -2.28065027e-02, 4.00000000e+00],
                  [2.10662349e+02, -3.40033470e-02, 6.00000000e+00],
                  [1.20656915e+02, -1.65935831e-02, 5.00000000e+00],
                  [2.28887705e+01, -8.43417664e-04, 5.00000000e+00],
                  [1.27472877e+01, -7.25424861e-03, 2.00000000e+00],
                  [1.09924214e+02, -1.81133209e-02, 3.00000000e+00],
                  [5.85000000e+01, 0.00000000e+00, 4.00000000e+00],
                  [1.57589902e+02, -1.70840018e-02, 3.00000000e+00]])
fig, ax = plt.subplots()
final = 10-np.random.rand(500,500).cumsum(axis=0).cumsum(axis=1)
# final = cv2.imread('frame9.jpg')
plt.imshow(final, cmap=plt.cm.gray, extent=[0, 10, 0,  polar[:,0].max()], aspect='auto', origin='lower')
for p in polar:
    plt.plot([0, 1], [p[0], p[0]], c='red')
plt.show()

example plot

问题是,您首先绘制线条,然后显示图像,因此图像会覆盖绘制的线条

只需按以下方式更改顺序即可:

fig=plt.figure()
final = cv2.imread('frame9.jpg')
plt.imshow(final,cmap=plt.cm.gray)
for p in polar:
    plt.plot([0,1],[p[0],p[0]],c='red')
plt.show()

相关问题 更多 >