如何使变形坐标的图像变形

时间:2016-09-22 22:20:32

标签: python python-2.7 numpy matplotlib

如果我知道图像的坐标是如何变形的,我想知道图像是如何变形的。

例如:这里我画了一个圆圈

import numpy as np
import matplotlib.pyplot as plt
from math import *

plane_side = 500.0 #arcsec

y_l, x_l, = np.mgrid[-plane_side:plane_side:1000j, -plane_side:plane_side:1000j]

r = np.sqrt(y_l**2 + x_l**2)

indexes1 = np.where(r<150.0)
indexes2 = np.where(r>160.0)

image = r.copy()
image[:,:] = 1.0
image[indexes1] = 0.0
image[indexes2] = 0.0

imgplot = plt.imshow(image,cmap="rainbow")
plt.colorbar()
plt.show()

如果我想像这样变形坐标:

y_c = y_lense**3
x_c = x_lense**2

并将图像扭曲,我该怎么办?

2 个答案:

答案 0 :(得分:2)

您可以使用plt.pcolormesh()

y_c = (y_l/plane_side)**3
x_c = (x_l/plane_side)**2

ax = plt.gca()
ax.set_aspect("equal")
plt.pcolormesh(x_c, y_c, image, cmap="rainbow")
ax.set_xlim(0, 0.2)
ax.set_ylim(-0.1, 0.1);

结果:

enter image description here

答案 1 :(得分:1)

通常(不使用专用库),您应该对新图像的坐标应用逆变换。然后,在计算的坐标处插入原始图像的值。

例如,如果要应用以下转换:

x_new = x**2
y_new = y**2
你会做那样的事情:

import numpy as np
# some random image
image = np.random.rand(10,10)

# new interpolated image - actually not interpolated yet :p
# TODO: in some cases, this image should be bigger than the original image. You can calculate optimal size from the original image considering the transformation used.
image_new = np.zeros(image.shape)

# get the coordinates
x_new, y_new = np.meshgrid( range(0,image_new.shape[1]), range(0,image_new.shape[0]) )
x_new = np.reshape(x_new, x_new.size) 
y_new = np.reshape(y_new, y_new.size) 

# do the inverse transformation
x = np.sqrt(x_new)
y = np.sqrt(y_new)

# TODO: here you should check that all x, y coordinates fall inside the image borders

# do the interpolation. The simplest one is nearest neighbour interpolation. For better image quality, bilinear interpolation should be used.
image_new[y_new,x_new] = image[np.round(y).astype(np.int) , np.round(x).astype(np.int)]