简体   繁体   English

如何在python中扭曲图像?

[英]How to warp an image in python?

How do i transform the image to make warp effect using pull warp like in the below image?我如何转换图像以使用下图所示的拉变形产生变形效果

Left image is the input and right one is the output (warped version)左图是输入,右图是输出(变形版)

I read this article Image warping and found some hint.我阅读了这篇文章图像扭曲并找到了一些提示。 Now my question is that how do i calculate the offset ?现在我的问题是如何计算偏移量?

在此处输入图片说明

It looks like mission for scipy.ndimage.geometric_transform .它看起来像是scipy.ndimage.geometric_transform 的任务。 Consider following example, using考虑以下示例,使用

1 2
3 4

as input 2D array作为输入二维数组

t = np.array([[1,2],[3,4]],dtype='uint8') #our input array
def func(x):
    return (x[1],x[0])
out = scipy.ndimage.geometric_transform(t,func)
print(out)

output:输出:

[[1 3]
 [2 4]]

So what happend?那么发生了什么? For each cell in input, func with that cell position (tuple) as argument is calculated and its output used as new location for cell, remembering that indexes are starting at 0 and they are in y,x manner:对于输入中的每个单元格,计算以该单元格位置(元组)作为参数的func并将其输出用作单元格的新位置,记住索引从 0 开始并且它们以 y,x 方式:

  • 1 position is 0,0 1 个位置是 0,0
  • 2 position is 0,1 2 位置是 0,1
  • 3 position is 1,0 3 位置是 1,0
  • 4 position is 1,1 4 位置是 1,1

My example function simply switch y with x so我的示例函数只是用 x 切换 y 所以

  • 1 new position is 0,0 1 个新位置是 0,0
  • 2 new position is 1,0 2 新位置是 1,0
  • 3 new position is 0,1 3 新位置是 0,1
  • 4 new position is 1,1 4 新位置是 1,1

which indeed you could see in output.您确实可以在输出中看到。

Using cv2.imread function you can easily read image into numpy array, if you want solely transform grayscale image thats make things simpler as you would deal with 2D array rather than 3D array.使用cv2.imread函数,您可以轻松地将图像读入 numpy 数组,如果您只想转换灰度图像,这会使事情变得更简单,因为您将处理 2D 数组而不是 3D 数组。 Remember to use cv2.imread('someimage.bmp',0) (with 0 as second argument) when loading grayscale image.请记住在加载灰度图像时使用cv2.imread('someimage.bmp',0) (以0作为第二个参数)。

Main challenge is creating the function: assuming grayscale its input is 2-tuple - position of "donor" pixel and output is 2-tuple - position of "recipient", note that this function do not have to cover whole output area - in case of output pixel missing "donor" it is interpolated.主要挑战是创建函数:假设灰度的输入是 2 元组 - “供体”像素的位置,输出是 2 元组 - “接收者”的位置,注意这个函数不必覆盖整个输出区域 - 以防万一缺少“供体”的输出像素是内插的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM