OpenCV 中的图像转换

问题描述 投票:0回答:3

这个问题与这个问题相关:

How to remove convexity defects in sudoku square

我试图在nikie's answer

中实现
Mathematica to OpenCV-Python
。但我被困在程序的最后一步。 

即我得到了正方形中的所有交点,如下所示:

enter image description here

现在,我想将其转换为大小为 (450,450) 的完美正方形,如下所示:

enter image description here

(不要介意两个图像的亮度差异)。

问题: 我怎样才能在 OpenCV-Python 中做到这一点?我正在使用

cv2
版本。

python opencv wolfram-mathematica computer-vision
3个回答
40
投票

除了 etarion 的建议之外,您还可以使用 remap 功能。我编写了一个快速脚本来展示如何做到这一点。正如您所见,使用 Python 进行编码非常简单。这是测试图像:

distorted image

这是变形后的结果:

warped image

这是代码:

import cv2
from scipy.interpolate import griddata
import numpy as np

grid_x, grid_y = np.mgrid[0:149:150j, 0:149:150j]
destination = np.array([[0,0], [0,49], [0,99], [0,149],
                  [49,0],[49,49],[49,99],[49,149],
                  [99,0],[99,49],[99,99],[99,149],
                  [149,0],[149,49],[149,99],[149,149]])
source = np.array([[22,22], [24,68], [26,116], [25,162],
                  [64,19],[65,64],[65,114],[64,159],
                  [107,16],[108,62],[108,111],[107,157],
                  [151,11],[151,58],[151,107],[151,156]])
grid_z = griddata(destination, source, (grid_x, grid_y), method='cubic')
map_x = np.append([], [ar[:,1] for ar in grid_z]).reshape(150,150)
map_y = np.append([], [ar[:,0] for ar in grid_z]).reshape(150,150)
map_x_32 = map_x.astype('float32')
map_y_32 = map_y.astype('float32')

orig = cv2.imread("tmp.png")
warped = cv2.remap(orig, map_x_32, map_y_32, cv2.INTER_CUBIC)
cv2.imwrite("warped.png", warped)

我想你可以通过谷歌搜索来找到 griddata 的作用。简而言之,它进行插值,这里我们使用它将稀疏映射转换为稠密映射,因为 cv2.remap 需要稠密映射。我们只需将值转换为 float32,因为 OpenCV 抱怨 float64 类型。请让我知道进展如何。

更新:如果你不想依赖Scipy,一种方法是在你的代码中实现2d插值函数,例如,查看Scipy中griddata的源代码或者像这样的更简单的代码http:// /inasafe.readthedocs.org/en/latest/_modules/engine/interpolation2d.html 仅取决于 numpy。不过,我建议为此使用 Scipy 或其他库,尽管我明白为什么对于这样的情况只需要 CV2 和 numpy 可能会更好。我想听听你的最终代码如何解决数独问题。


1
投票

如果你有源点和终点(你只需要4个),你可以将它们插入cv2.getPerspectiveTransform,并在cv2.warpPerspective中使用该结果。给你一个很好的平坦结果。


0
投票

因此,在这张图片中,您有一个数独,它已经是一个网格。对于没有网格的图像,我们如何复制它?

例如对于像this

这样的图像
© www.soinside.com 2019 - 2024. All rights reserved.