为什么我的全景图会缝合黑色图像而不是实际图像?

2024-10-01 02:31:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用openCV(不使用Stitcher类)将一些图像(相同分辨率)缝合到全景图中。我尝试了described here算法,但是我得到的不是所需的全景图,而是由最后一张要缝合的图像和一个大的黑色区域组成的图像。每次迭代我都输出am图像,结果是一样的:当前图像+每次都有一个较大的黑色区域

import numpy
import cv2

# images is an array of images that i need to stitch

matcher = cv2.DescriptorMatcher_create(cv2.DescriptorMatcher_BRUTEFORCE_HAMMING)
ORB = cv2.ORB_create()
homography = 0
panorama = 0

for image in range(0, len(images) -1):
    key1, desc1 = ORB.detectAndCompute(images[image], None)
    key2, desc2 = ORB.detectAndCompute(images[image + 1], None)

    matches = matcher.match(desc1, desc2, None)
    matches = sorted(matches, key=lambda x: x.distance, reverse=True)
    numGoodMatches = int(len(matches) * 0.15)
    matches2 = matches[-numGoodMatches:]

    points1 = numpy.zeros((len(matches2), 2), dtype=numpy.float32)
    points2 = numpy.zeros((len(matches2), 2), dtype=numpy.float32)

    for i, match in enumerate(matches2):
        points1[i, :] = key1[match.queryIdx].pt
        points2[i, :] = key2[match.trainIdx].pt

    h, mask = cv2.findHomography(points2, points1, cv2.RANSAC)

    if isinstance(homography, int):
        homography = h
        img1H, img1W = images[image].shape
        img2H, img2W = images[image + 1].shape
        aligned = cv2.warpPerspective(images[image + 1], h, (img1W + img2W, img2H))
        stitchedImage = numpy.copy(aligned)
        stitchedImage[0:img1H, 0:img2W] = images[image]
        panorama = stitchedImage
    else:
        h *= homography
        homography = h
        img1H, img1W = panorama.shape
        img2H, img2W = images[image + 1].shape
        aligned = cv2.warpPerspective(images[image + 1], h, (img1W + img2W, img2H))
        stitchedImage = numpy.copy(aligned)
        stitchedImage[0:img1H, 0:img2W] = images[image + 1]
        panorama = stitchedImage

我获得的图像示例:

第一个图像是正确的

The first stitched iteration works properly

最后一幅图像具有正确的宽度(n*原始宽度),但只有一幅图像,其余为黑色区域

Example of wrong output


Tags: 图像imagenumpylenmatchcv2imagesmatches
1条回答
网友
1楼 · 发布于 2024-10-01 02:31:40

这个

stitchedImage[0:img1H, 0:img2W] = images[image + 1]

将图像放置在“缝合图像”的左上角

无论如何,必须为全景图的每个部分计算图像x偏移:

stitchedImage[0:img1H, x_offset:x_offset+img2W] = images[image + 1]

相关问题 更多 >