首页 > 解决方案 > Matplotlib - 图形和图像坐标之间的转换

问题描述

我有数据我希望对其进行一些操作,如果我将我的数据转换为图像(例如,霍夫变换),这些操作会更容易。为此,我将数据转换为图像(见附图)。但是,我不明白如何在两个坐标系之间正确移动(或者,将轴实例转换为图像而不是图形实例,然后转换将是微不足道的)。

我尝试使用转换框架,但没有成功。

我附上了一个包含两个子图的图,在散点数据的左侧,在右侧是它的图像表示。

(另外,我不知道如何将散点图数据转换为图像可以做得更整洁,如果是这样,我很乐意听到改进建议)。

我使用python 3.6.9;matplotlib 版本 = 3.3.4

提前致谢。

import numpy as np
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt

# --- Study case: generate random data
X = np.random.rand(1000, 2)

# --- Figure configuration
fig = plt.figure(figsize=(25, 25))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)

# --- First subplot
ax1.scatter(X[:, 0], X[:, 1], s=2, c='k')
ax1.set_title('ax.scatter')

# --- Scatter plot to image
Fig = Figure()
canvas = FigureCanvas(Fig)
Ax = Fig.gca()
Ax.axis('off')
Ax.scatter(X[:, 0], X[:, 1], s=2, c='k')
Ax.get_yaxis().set_ticks([])
Ax.get_xaxis().set_ticks([])
canvas.draw()  # draw the canvas, cache the renderer
width, height = Fig.get_size_inches() * Fig.get_dpi()
height = int(height)
width = int(width)
img = np.frombuffer(canvas.tostring_rgb(), dtype='uint8').reshape(height, width, 3)

# --- Display image
ax2.imshow(img)
plt.title('ax.imshow')
plt.show()

在此处输入图像描述

标签: python-3.xmatplotlib

解决方案


推荐阅读