我试图使用OpenCV 2.1将两个图像合并为一个,两个图像相邻放置。在Python中,我正在做:
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
结果图像是:
可能很难与网站的其他部分区分开来,但大部分图像是白色的,与单个图像应该在的位置相对应。黑色区域是没有写入图像数据的区域。
为什么我所有的图像数据都被转换成白色?
对于图像大小相同的情况(这是显示图像处理结果的常见情况),可以使用numpy的concatenate来简化代码。
垂直堆叠(img1在img2之上):
水平堆叠(img1在img2的左侧):
要验证:
或者如果您喜欢传统方式:
对于那些希望将2个彩色图像合并为一个图像的人, 这是对安德烈回答的一个小小的修改,它对我起了作用:
相关问题 更多 >
编程相关推荐