图像的仿射变换

将仿射变换(Affine2D)预先添加到图像的数据变换允许操纵图像的形状和方向。这是变换链的概念的一个例子。

对于支持具有可选仿射变换的draw_image的后端(例如,agg,ps后端),输出的图像应该使其边界与虚线黄色矩形匹配。

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import matplotlib.transforms as mtransforms
  4. def get_image():
  5. delta = 0.25
  6. x = y = np.arange(-3.0, 3.0, delta)
  7. X, Y = np.meshgrid(x, y)
  8. Z1 = np.exp(-X**2 - Y**2)
  9. Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
  10. Z = (Z1 - Z2)
  11. return Z
  12. def do_plot(ax, Z, transform):
  13. im = ax.imshow(Z, interpolation='none',
  14. origin='lower',
  15. extent=[-2, 4, -3, 2], clip_on=True)
  16. trans_data = transform + ax.transData
  17. im.set_transform(trans_data)
  18. # display intended extent of the image
  19. x1, x2, y1, y2 = im.get_extent()
  20. ax.plot([x1, x2, x2, x1, x1], [y1, y1, y2, y2, y1], "y--",
  21. transform=trans_data)
  22. ax.set_xlim(-5, 5)
  23. ax.set_ylim(-4, 4)
  24. # prepare image and figure
  25. fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
  26. Z = get_image()
  27. # image rotation
  28. do_plot(ax1, Z, mtransforms.Affine2D().rotate_deg(30))
  29. # image skew
  30. do_plot(ax2, Z, mtransforms.Affine2D().skew_deg(30, 15))
  31. # scale and reflection
  32. do_plot(ax3, Z, mtransforms.Affine2D().scale(-1, .5))
  33. # everything and a translation
  34. do_plot(ax4, Z, mtransforms.Affine2D().
  35. rotate_deg(30).skew_deg(30, 15).scale(-1, .5).translate(.5, -1))
  36. plt.show()

图像的仿射变换图示

参考

此示例中显示了以下函数,方法和类的使用:

  1. import matplotlib
  2. matplotlib.axes.Axes.imshow
  3. matplotlib.pyplot.imshow
  4. matplotlib.transforms.Affine2D

下载这个示例