将四边形图像提取为矩形

时间:2010-06-07 18:57:56

标签: graphics pixel interpolation

A photo

BOUNTY UPDATE

关注Denis's链接,这是使用threeblindmiceandamonkey代码的方式:

// the destination rect is our 'in' quad
int dw = 300, dh = 250;
double in[4][4] = {{0,0},{dw,0},{dw,dh},{0,dh}};
    // the quad in the source image is our 'out'
double out[4][5] = {{171,72},{331,93},{333,188},{177,210}};
double homo[3][6];
const int ret = mapQuadToQuad(in,out,homo);
    // homo can be used for calculating the x,y of any destination point
// in the source, e.g.
for(int i=0; i<4; i++) {
    double p1[3] = {out[i][0],out[i][7],1};
    double p2[3];
    transformMatrix(p1,p2,homo);
    p2[0] /= p2[2]; // x
    p2[1] /= p2[2]; // y
    printf("\t%2.2f\t%2.2f\n",p2[0],p2[1]);
}

这提供了一个转换,用于将目的地中的点转换为源 - 您当然可以反过来这样做,但是能够为混合执行此操作是很整洁的:

for(int y=0; y<dh; y++) {
    for(int x=0; x<dw; x++) {
        // calc the four corners in source for this
        // destination pixel, and mix

对于混音,我使用super-sampling随机点;即使在源和目的地区域存在很大差异,它也能很好地运作


背景问题

在顶部的图像中,面包车侧面的标志不是面向相机的。我想用我所拥有的像素来计算它看起来像面对的东西。

我知道图像中四边形的角坐标,以及目标矩形的大小。

我想这是通过x和y轴的某种循环,在两个维度上同时进行Bresenham线,并且在源图像和目标图像中的像素重叠时进行某种混合 - 某些子像素混合的某种类型?

有哪些方法,以及如何混合像素?

是否有标准方法?

4 个答案:

答案 0 :(得分:14)

你想要的是平面矫正,我担心的并不是那么简单。你需要做的是恢复将这个侧面倾斜视图映射到前向视图的homography。 Photoshop /等有一些工具可以为你提供一些控制点;如果你想为自己实现它,你将不得不开始深入研究计算机视觉。

编辑 - 好的,这里你去:使用OpenCV库进行变形的Python脚本,它具有方便的函数来计算单应性并为你扭曲图像:< / p>

import cv

def warpImage(image, corners, target):
    mat = cv.CreateMat(3, 3, cv.CV_32F)
    cv.GetPerspectiveTransform(corners, target, mat)
    out = cv.CreateMat(height, width, cv.CV_8UC3)
    cv.WarpPerspective(image, out, mat, cv.CV_INTER_CUBIC)
    return out

if __name__ == '__main__':
    width, height = 400, 250
    corners = [(171,72),(331,93),(333,188),(177,210)]
    target = [(0,0),(width,0),(width,height),(0,height)]
    image = cv.LoadImageM('fries.jpg')
    out = warpImage(image, corners, target)
    cv.SaveImage('fries_warped.jpg', out)

输出:
Warped image

OpenCV也有C和C ++绑定,或者你可以使用EmguCV作为.NET包装器; API在所有语言中都相当一致,因此您可以使用适合您喜欢的任何语言复制它。

答案 1 :(得分:5)

查找"quad to quad" transform,例如 threeblindmiceandamonkey
2d齐次坐标上的3x3变换可以变换任意4个点(四边形) 到任何其他四边形; 相反,任何fromquad和toquad,例如卡车的角落和目标矩形, 给出3 x 3变换。

Qt有quadToQuad 并且可以用它转换pixmaps,但我猜你没有Qt?
添加10Jun: 来自labs.trolltech.com/page/Graphics/Examples 有一个很好的演示,当你移动角落时,它会四边形到一个像素图:

alt text

添加了11Jun:@Will,这是用Python编写的translate.h(你知道一点吗? “”“”“”“”是多行评论。)
perstrans()是关键;希望有意义,如果不问。

Bytheway,你可以逐个映射像素mapQuadToQuad(target rect,orig quad), 但没有像素插值,它看起来很糟糕; OpenCV可以做到这一切。

#!/usr/bin/env python
""" square <-> quad maps
    from http://threeblindmiceandamonkey.com/?p=16 matrix.h
"""

from __future__ import division
import numpy as np

__date__ = "2010-06-11 jun denis"

def det2(a, b, c, d):
    return a*d - b*c

def mapSquareToQuad( quad ):  # [4][2]
    SQ = np.zeros((3,3))
    px = quad[0,0] - quad[1,0] + quad[2,0] - quad[3,0]
    py = quad[0,1] - quad[1,1] + quad[2,1] - quad[3,1]
    if abs(px) < 1e-10 and abs(py) < 1e-10:
        SQ[0,0] = quad[1,0] - quad[0,0]
        SQ[1,0] = quad[2,0] - quad[1,0]
        SQ[2,0] = quad[0,0]
        SQ[0,1] = quad[1,1] - quad[0,1]
        SQ[1,1] = quad[2,1] - quad[1,1]
        SQ[2,1] = quad[0,1]
        SQ[0,2] = 0.
        SQ[1,2] = 0.
        SQ[2,2] = 1.
        return SQ
    else:
        dx1 = quad[1,0] - quad[2,0]
        dx2 = quad[3,0] - quad[2,0]
        dy1 = quad[1,1] - quad[2,1]
        dy2 = quad[3,1] - quad[2,1]
        det = det2(dx1,dx2, dy1,dy2)
        if det == 0.:
            return None
        SQ[0,2] = det2(px,dx2, py,dy2) / det
        SQ[1,2] = det2(dx1,px, dy1,py) / det
        SQ[2,2] = 1.
        SQ[0,0] = quad[1,0] - quad[0,0] + SQ[0,2]*quad[1,0]
        SQ[1,0] = quad[3,0] - quad[0,0] + SQ[1,2]*quad[3,0]
        SQ[2,0] = quad[0,0]
        SQ[0,1] = quad[1,1] - quad[0,1] + SQ[0,2]*quad[1,1]
        SQ[1,1] = quad[3,1] - quad[0,1] + SQ[1,2]*quad[3,1]
        SQ[2,1] = quad[0,1]
        return SQ

#...............................................................................
def mapQuadToSquare( quad ):
    return np.linalg.inv( mapSquareToQuad( quad ))

def mapQuadToQuad( a, b ):
    return np.dot( mapQuadToSquare(a), mapSquareToQuad(b) )

def perstrans( X, t ):
    """ perspective transform X Nx2, t 3x3:
        [x0 y0 1] t = [a0 b0 w0] -> [a0/w0 b0/w0]
        [x1 y1 1] t = [a1 b1 w1] -> [a1/w1 b1/w1]
        ...
    """
    x1 = np.vstack(( X.T, np.ones(len(X)) ))
    y = np.dot( t.T, x1 )
    return (y[:-1] / y[-1]) .T

#...............................................................................
if __name__ == "__main__":
    np.set_printoptions( 2, threshold=100, suppress=True )  # .2f

    sq = np.array([[0,0], [1,0], [1,1], [0,1]])
    quad = np.array([[171, 72], [331, 93], [333, 188], [177, 210]])
    print "quad:", quad
    print "square to quad:", perstrans( sq, mapSquareToQuad(quad) )
    print "quad to square:", perstrans( quad, mapQuadToSquare(quad) )

    dw, dh = 300, 250
    rect = np.array([[0, 0], [dw, 0], [dw, dh], [0, dh]])
    quadquad = mapQuadToQuad( quad, rect )
    print "quad to quad transform:", quadquad
    print "quad to rect:", perstrans( quad, quadquad )
"""
quad: [[171  72]
 [331  93]
 [333 188]
 [177 210]]
square to quad: [[ 171.   72.]
 [ 331.   93.]
 [ 333.  188.]
 [ 177.  210.]]
quad to square: [[-0.  0.]
 [ 1.  0.]
 [ 1.  1.]
 [ 0.  1.]]
quad to quad transform: [[   1.29   -0.23   -0.  ]
 [  -0.06    1.79   -0.  ]
 [-217.24  -88.54    1.34]]
quad to rect: [[   0.    0.]
 [ 300.    0.]
 [ 300.  250.]
 [   0.  250.]]
"""

答案 2 :(得分:0)

我认为您需要的是affine transformation,可以使用矩阵数学来完成。

答案 3 :(得分:0)

在现代,在 python 中使用 cv2。

import cv2
import numpy as np

source_image = cv2.imread('french fries in Europe.jpeg')

source_corners = np.array([(171, 72), (331, 93), (333, 188), (177, 210)])

width, height = 400, 250
target_corners = np.array([(0, 0), (width, 0), (width, height), (0, height)])

# Get matrix H that maps source_corners to target_corners
H, _ = cv2.findHomography(source_corners, target_corners, params=None)

# Apply matrix H to source image.
transformed_image = cv2.warpPerspective(
    source_image, H, (source_image.shape[1], source_image.shape[0]))

cv2.imwrite('tranformed_image.jpg', transformed_image)