使用Python进行图像变形

2 投票
1 回答
6305 浏览
提问于 2025-04-18 16:18

我需要在Python中对一张比较大的图片(1679x1475)进行变形。我已经有了变形后的坐标。请问我该如何高效地将这张图片变形到新的坐标系统呢?我试过使用scipy.interpolate.griddata这个方法,但很快我的电脑就内存不够用了。

1 个回答

6

你需要用到 scipy.ndimage.map_coordinates 这个工具。它可以让你设置插值的方法,以及如何处理那些在原始图像之外的点。

举个例子:

import numpy as np
from scipy import misc
#create a 2D array that has a grayscale image of a raccoon
face = misc.face(gray=True)

import matplotlib.pyplot as plt
plt.imshow(face,cmap=plt.cm.gray)

未变形的图像看起来是这样的

#set up our new coordinate system
rows,cols = np.mgrid[0:768, 0:1024]
rows = rows**(1/2) * 767**(1/2)
cols = cols**(2) / 1023
rows = np.roll(rows,150,0)

from scipy import ndimage
#warp the image using a 3rd order (cubic) spline interpolation
new_img = ndimage.map_coordinates(face,[rows,cols], order=3)
plt.figure()
plt.imshow(new_img,cmap=plt.cm.gray)

变形后的图像是这样的

撰写回答