首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >OpenCV和Python-如何通过指定坐标来叠加图像?

OpenCV和Python-如何通过指定坐标来叠加图像?
EN

Stack Overflow用户
提问于 2017-07-11 22:38:50
回答 1查看 2.9K关注 0票数 1

简而言之,我的问题是如何通过为添加的图像指定特定的坐标,将图像放在另一个图像的上面?我需要根据需要扩展基本图像的“画布”,这样添加的图像就不会被裁剪。

以下是扩展版本:

我的项目是从无人驾驶飞机的视频中提取图片,并用它们绘制一张粗略的地图,将一张照片与最后一张照片对齐。我知道有一些软件我可以使用,比如Agisoft Photoscan,但我的目标是创建一个更轻量级、更粗糙的解决方案。

这是我的计划,我打算用每一帧来做:

  1. 使用estimateRigidTransform生成转换矩阵,以使curr_photo与最后一张照片base对齐
  2. 计算包围结果图像所需的包围矩形(使用四个角的转换)
  3. 修改转换矩阵,使包围框的左上角位于原点。
  4. 将转换应用于当前照片,使用边框的宽度和高度来确保没有裁剪生成的图像
  5. 通过在适当的坐标下将curr_image添加到base中,将当前图像与最后一个图像(确保这两个图像不发生剪切)一起添加到当前图像。这就是我要问的问题。

下面是执行步骤1到步骤4的代码。

代码语言:javascript
运行
AI代码解释
复制
import numpy as np
import cv2


base = cv2.imread("images/frame_03563.jpg")
curr_photo = cv2.imread("images/frame_03564.jpg")

height, width = curr_photo.shape[:2]

# Step 1
# which transformation is required to go from curr_photo to base?
transformation = cv2.estimateRigidTransform(curr_photo, base, True)

# Step 2
# add a line to the affine transformation matrix so it can be used by
# perspectiveTransform
three_by_three = np.array([
    transformation[0],
    transformation[1],
    [0, 0, 1]], dtype="float32")

# get corners of curr_photo (to be transformed)
corners = np.array([
    [0, 0],
    [width - 1, 0],
    [width - 1, height - 1],
    [0, height - 1]
])

# where do the corners of the image go
trans_corners = cv2.perspectiveTransform(np.float32([corners]), three_by_three)

# get the bounding rectangle for the four corner points (and thus, the transformed image)
bx, by, bwidth, bheight = cv2.boundingRect(trans_corners)

# Step 3
# modify transformation matrix so that the top left of the bounding box is at the origin
transformation[0][2] = transformation[0][2] - bx
transformation[1][2] = transformation[1][2] - by

# Step 4
# transform the image in a window the size of its bounding rectangle (so no cropping)
mod_curr_photo = cv2.warpAffine(curr_photo, transformation, (bwidth, bheight))

# for viewing
cv2.imshow("base", base)
cv2.imshow("current photo", curr_photo)
cv2.imshow("image2 transformed to image 1", mod_curr_photo)

cv2.waitKey()

我还附上了两个样本图像。我用第一个作为基础,但不管用哪种方式都行。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-12 00:04:21

编辑:我现在已经将下面链接的答案转换为一个GitHub模块,您现在可以从GitHub 这里获取这个模块。

我回答了这个问题,几周前。答案应该包含完成您所追求的目标所需的一切;我唯一不讨论的是alpha混合或其他将图像边界混合在一起的技术,就像用全景图或类似的方法一样。

为了不裁剪扭曲的照片,您需要事先计算所需的填充,因为图像翘曲本身可以引用负指数,在这种情况下,它不会绘制them...so --您需要先计算翘曲位置,将图像填充到图像边界之外的索引,然后修改翘曲矩阵,将这些转换添加到正值。

这允许您创建这样的图像:

来自牛津VGG的图像。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45050190

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文