使用 OpenCV 组合两个图像

Combining Two Images with OpenCV(使用 OpenCV 组合两个图像)
本文介绍了使用 OpenCV 组合两个图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试使用 OpenCV 2.1 将两个图像合二为一,两个图像彼此相邻放置.在 Python 中,我正在做:

I'm trying to use OpenCV 2.1 to combine two images into one, with the two images placed adjacent to each other. In Python, I'm doing:

import numpy as np, cv

img1 = cv.LoadImage(fn1, 0)
img2 = cv.LoadImage(fn2, 0)

h1, w1 = img1.height,img1.width
h2, w2 = img2.height,img2.width

# Create an array big enough to hold both images next to each other.
vis = np.zeros((max(h1, h2), w1+w2), np.float32)

mat1 = cv.CreateMat(img1.height,img1.width, cv.CV_32FC1)
cv.Convert( img1, mat1 )

mat2 = cv.CreateMat(img2.height, img2.width, cv.CV_32FC1)
cv.Convert( img2, mat2 )

# Copy both images into the composite image.
vis[:h1, :w1] = mat1
vis[:h2, w1:w1+w2] = mat2

h,w = vis.shape
vis2 = cv.CreateMat(h, w, cv.CV_32FC3)
vis0 = cv.fromarray(vis)
cv.CvtColor(vis0, vis2, cv.CV_GRAY2BGR)
cv.ShowImage('test', vis2)
cv.WaitKey()

两个输入图像是:

https://code.ros.org/trac/opencv/browser/trunk/opencv/samples/c/box.png?rev=2270

https://code.ros.org/trac/opencv/browser/trunk/opencv/samples/c/box_in_scene.png?rev=2270

生成的图像是:

可能很难与网站的其他部分区分开来,但大部分图像都是白色的,对应于单个图像应该在的位置.黑色区域是没有写入图像数据的地方.

It may be hard to distinguish from the rest of the site, but most of the image is white, corresponding to where the individual images should be. The black area is where no image data was written.

为什么我的所有图像数据都被转换为白色?

Why is all my image data being converted to white?

推荐答案

对于你的图片恰好大小相同的情况(这是显示图片处理结果的常见情况),你可以使用 numpy 的 concatenate 来简化你的代码.

For cases where your images happen to be the same size (which is a common case for displaying image processing results), you can use numpy's concatenate to simplify your code.

垂直堆叠(img1 over img2):

To stack vertically (img1 over img2):

vis = np.concatenate((img1, img2), axis=0)

水平堆叠(img1在img2的左边):

To stack horizontally (img1 to the left of img2):

vis = np.concatenate((img1, img2), axis=1)

验证:

import cv2
import numpy as np
img1 = cv2.imread('img1.png')
img2 = cv2.imread('img2.png')
vis = np.concatenate((img1, img2), axis=1)
cv2.imwrite('out.png', vis)

out.png 图像将在左侧包含 img1,在右侧包含 img2.

The out.png image will contain img1 on the left and img2 on the right.

这篇关于使用 OpenCV 组合两个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Reading *.mhd/*.raw format in python(在 python 中读取 *.mhd/*.raw 格式)
Count number of cells in the image(计算图像中的单元格数)
How to detect paragraphs in a text document image for a non-consistent text structure in Python OpenCV(如何在 Python OpenCV 中检测文本文档图像中的段落是否存在不一致的文本结构)
How to get the coordinates of the bounding box in YOLO object detection?(YOLO物体检测中如何获取边界框的坐标?)
Divide an image into 5x5 blocks in python and compute histogram for each block(在 python 中将图像划分为 5x5 块并计算每个块的直方图)
Extract cow number from image(从图像中提取奶牛编号)