Python 如何变形图像变形坐标
如果我知道图像的坐标是如何变形的,我想看看图像是如何变形的 这里我画了一个圆Python 如何变形图像变形坐标,python,python-2.7,numpy,matplotlib,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)
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()
并绘制扭曲的图像,我该怎么办?您可以使用
plt.pcolormesh()
:
结果是:
通常(不使用专用库),您应该对新图像的坐标应用逆变换。然后,在计算的坐标处对原始图像的值进行插值
例如,如果要应用以下转换:
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)]
如果希望输出为图像,这不是一个很好的解决方案,但确实是一种快速可视化方法。请注意,pcolormesh将像素的角点而不是中心点作为其位置,因此,
image[:,-1]
和image[-1,:]
将被丢弃scipy.ndimage
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)]