拼接最终尺寸和偏移量

时间:2013-07-22 10:06:47

标签: python opencv image-resizing homography image-stitching

我正在使用opencv和Python进行拼接。一切都很好,除了一件事:我无法计算结果图片的确切最终大小。 我的形象总是太大,我有黑色边框。此外,偏移似乎不正确,因为图片已经合并了黑线。

这是我的功能:

    def calculate_size(size_image1, size_image2, homography):

      ## Calculate the size and offset of the stitched panorama.

      offset = abs((homography*(size_image2[0]-1,size_image2[1]-1,1))[0:2,2]) 
      print offset
      size   = (size_image1[1] + int(offset[0]), size_image1[0] + int(offset[1]))
      if (homography*(0,0,1))[0][1] > 0:
        offset[0] = 0
      if (homography*(0,0,1))[1][2] > 0:
        offset[1] = 0

      ## Update the homography to shift by the offset
      homography[0:2,2] +=  offset

      return (size, offset)


## 4. Combine images into a panorama. [4] --------------------------------
def merge_images(image1, image2, homography, size, offset, keypoints):

  ## Combine the two images into one.
  panorama = cv2.warpPerspective(image2,homography,size)
  (h1, w1) = image1.shape[:2]

  for h in range(h1):
    for w in range(w1):
        if image1[h][w][0] != 0 or image1[h][w][3] != 0 or image1[h][w][4] != 0:
            panorama[h+offset[1]][w + offset[0]] = image1[h][w]

  ## TODO: Draw the common feature keypoints.

  return panorama

我的结果:

第一张图片:First image

第二张图片:Second Image

拼接图片:Stitched result

我做错了什么?

3 个答案:

答案 0 :(得分:1)

if (homography*(0,0,1))[0][1] > 0:
    offset[0] = 0
if (homography*(0,0,1))[1][2] > 0:
    offset[1] = 0

您的代码错误。正确如下:

if (homography*(0,0,1))[0][2] > 0:
    offset[0] = 0
if (homography*(0,0,1))[1][2] > 0:
    offset[1] = 0

答案 1 :(得分:0)

嗯,我对Python知之甚少,但基本上我遇到了一些问题。 为解决尺寸问题,我做了以下工作:

perspectiveTransform( obj_original_corners, scene_corners, homography);

之后,我只搜索了smallest_Xsmallest_Ybiggest_Xbiggest_Y这两个图片。

然后我用这些数字:

cv::warpPerspective(img_2,WarpedImage,homography,cv::Size(biggestX-smallestX,biggestY-smallestY));

因此,在这种情况下,即使第二张图像具有负x或负y,新图像本身也会具有适当的大小。

此刻我还在努力解决的问题是如何将转换应用到warpPerspective,因为现在我的部分图像因负数而被截止。

答案 2 :(得分:0)

根据拼接,所有过程都是正确的。结果是因为你的源图片。

for h in range(h1):
  for w in range(w1):
    if image1[h][w][0] != 0 or image1[h][w][3] != 0 or image1[h][w][4] != 0:
        panorama[h+offset[1]][w + offset[0]] = image1[h][w]

该操作仅过滤颜色为零的像素。事实上,某些像素看起来像黑色,但它不是纯黑色,非常接近黑色。所以这些看似黑色的像素不会被您的程序过滤掉。