python - python中图像的几何扭曲

标签 python image-processing numpy scikit-image

我想使用 python 对图像执行几何变换,以沿着给定曲线“拉直”或校正图像。似乎 scikit-image ProjectiveTransform()warp() 对此非常有用,但文档很少。我遵循了文档 here ,但我无法让它在示例案例中正常工作。

举个例子:我将创建一个包含两个同心圆的图像,目标是校正这些圆的四分之一,以便生成的图像是两条平行线。这是示例数据:

import numpy as np
a = np.zeros((500, 500))

# create two concentric circles with a thickness of a few pixels:
for i in range(500):
    for j in range(500):
        r = np.sqrt((i - 250)**2 + (j - 250)**2) 
        if r > 50 and r < 52:
            a[i, j] = 10
        if r > 100 and r < 102:
            a[i, j] = 10
# now create the coordinates of the control points in the original image:
(x0, y0) = (250, 250)
r = 30   # inner circle
x = np.linspace(250 - r, 250, 50)
y = np.sqrt(r ** 2 - (x - x0) ** 2) + x0
r2 = 120   # outer circle
x2 = np.linspace(250 - r2, 250, 50)
y2 = np.sqrt(r2 ** 2 - (x2 - x0) ** 2) + x0
dst = np.concatenate((np.array([x, y]).T, np.array([x2, y2]).T))

这可以被绘制出来,例如:

imshow(a, cmap='gist_gray_r')
plot(x, y, 'r.')
plot(x2, y2, 'r.')

enter image description here

所以我的目标是对红色控制点给出的象限内的图像进行校正。 (在这种情况下,这与笛卡尔到极坐标的变换相同。)使用文档示例中的 scikit 图像,我完成了:

# create corresponding coordinates for control points in final image:
xi = np.linspace(0, 100, 50)
yi = np.zeros(50)
xi2 = xi
yi2 = yi + (r2 - r)
src = np.concatenate((np.array([xi, yi]).T, np.array([xi2, yi2]).T))

# transform image
from skimage import transform, data
tform3 = transform.ProjectiveTransform()
tform3.estimate(src, dst)
warped = transform.warp(a, tform3)

我原以为这张 warped 图像会显示两条平行线,但我却得到: enter image description here

我在这里做错了什么?

请注意,虽然在这种情况下它是笛卡尔坐标到极坐标的变换,但在最一般的情况下,我正在寻找从某个任意曲线进行的变换。如果有人知道使用其他软件包的更好方法,请告诉我。我可以通过对一堆径向线使用 ndimage.map_coordinates 来解决这个问题,但我一直在寻找更优雅的东西。

最佳答案

ProjectiveTransform 是线性变换,无法匹配您的变形方案。可能有更好的选择,但对于任意曲线,您可以使其与 PiecewiseAffineTransform 一起使用,它将通过镶嵌线性变换来匹配您抛给它的任何东西。如果您只是更改代码中转换的名称,这就是我得到的输出:

enter image description here

因此您可能需要稍微调整一下以获得您想要的结果,但至少它会在您的转换明确定义的区域产生您期望的两条平行线。

关于python - python中图像的几何扭曲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19660582/

相关文章:

python - 分布式任务队列(例如 Celery)与 crontab 脚本

python getattr 内置方法执行默认参数

python - PyInstaller:单文件可执行文件不运行

ios - Photoshop 的选择性滤色器背后的数学/算法是什么?

python - Numpy uint8_t 数组到 vtkImageData

python - 最快的获取方式

Python - 项目列表中的多个替换组合

java - 使用 OpenCV 计算两幅图像的相似度百分比

python - 如何根据内容裁剪图像(Python和OpenCV)?

python-3.x - 检查 numpy 数组中的类型