代码之家  ›  专栏  ›  技术社区  ›  YQ.Wang

单应投影不起作用

  •  0
  • YQ.Wang  · 技术社区  · 8 年前

    我正在尝试用浅黄色多边形替换下图中的右侧道路:

    起源 以下内容: enter image description here

    渴望的 (手动创建): enter image description here

    所以我想用 单应 让它发生 (我知道添加一个填充多边形也可以,但我可能希望将来使用一些其他的源图像,而不是简单的黄色多边形,例如广告图片)。 这是一个 tutorial 关于它,我只是复制了其中的代码,并对pixles做了一些更改。我使用的源图像如下:

    enter image description here

    这篇文章的第一张图片是我的目的地图片。

    这是我做这项工作的准则:

    import cv2
    import numpy as np
    
    # source image
    source_img = cv2.imread('lightyellow.jpg')
    # get four corners of the source (clock wise)
    pts_source = np.array([[0,0], [20,0], [20,30],[0,30]])
    
    # destination image
    dst_img = cv2.imread('0.png')
    # four corners in destination image (also clock wise):
    pts_dst = np.array([[292,0], [415,0], [578,120],[415,189]])
    
    # calculate homography
    h, status = cv2.findHomography(pts_source, pts_dst)
    
    # warp source image to destination based on homography
    img_out = cv2.warpPerspective(source_img, h, (dst_img.shape[1], dst_img.shape[0]))
    
    cv2.imshow('warped', img_out)
    cv2.waitKey(0)
    

    然而,我得到的是这样的东西:

    enter image description here

    完全错了,但我不知道为什么。有人能给我点指示吗?

    1 回复  |  直到 8 年前
        1
  •  0
  •   YQ.Wang    8 年前

    我终于用下面的代码做到了:

    import cv2
    import numpy as np
    
    # source image
    source_img = cv2.imread('lightyellow.jpg')
    size = source_img.shape
    # get four corners of the source (clock wise)
    pts_source = np.array(
                        [
                        [0,0],
                        [size[1] - 1, 0],
                        [size[1] - 1, size[0] -1],
                        [0, size[0] - 1 ]
                        ],dtype=float
                        )
    #pts_source = np.array([[310,0], [440,0], [589,151],[383,151]])
    
    # destination image
    dst_img = cv2.imread('0.png')
    # four corners in destination image (also clock wise):
    pts_dst = np.array([[292,0], [409,0], [577,191],[421,193]])
    
    # calculate homography
    h, status = cv2.findHomography(pts_source, pts_dst)
    
    # warp source image to destination based on homography
    temp = cv2.warpPerspective(source_img, h, (dst_img.shape[1], dst_img.shape[0]))
    
    # Black out polygonal area in destination image.
    cv2.fillConvexPoly(dst_img, pts_dst.astype(int), 0, 16)
    
    # Add warped source image to destination image.
    dst_img = dst_img + temp
    
    cv2.imshow('warpped', dst_img)
    cv2.waitKey(0)