查看: 1563|回复: 1

如何用opencv连接两个图片

[复制链接]

6

主题

21

帖子

65

积分

注册会员

Rank: 2

积分
65
发表于 2018-10-12 15:42:33 | 显示全部楼层 |阅读模式
我用OpenCV 2.1将两个图像合并为一个,两个图像相邻放置。下面是用python实现的代码
  1. import numpy as np, cv

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

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

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

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

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

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

  15. h,w = vis.shape
  16. vis2 = cv.CreateMat(h, w, cv.CV_32FC3)
  17. vis0 = cv.fromarray(vis)
  18. cv.CvtColor(vis0, vis2, cv.CV_GRAY2BGR)
  19. cv.ShowImage('test', vis2)
  20. cv.WaitKey()
复制代码
这两张输入图片是:


下面是得到的结果:
3yzIv.png

这可能很难与网站的其他部分区分开来,但大部分图像是白色的,与个别图像的位置相对应。黑色区域是没有写入图像数据的地方

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


回复

使用道具 举报

5

主题

53

帖子

130

积分

注册会员

Rank: 2

积分
130
发表于 2018-10-12 15:45:37 | 显示全部楼层
对于图像大小相同的情况(这是显示图像处理结果的常见情况),可以使用numpy的连接来简化代码
垂直堆叠(img1 / img2):
  1. vis = np.concatenate((img1, img2), axis=0)
复制代码


水平堆叠(img1在img2的左边):
  1. vis = np.concatenate((img1, img2), axis=1)
复制代码


验证:
  1. import cv2
  2. import numpy as np
  3. img = cv2.imread('img.png')
  4. vis = np.concatenate((img1, img2), axis=1)
  5. cv2.imwrite('out.png', vis)
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表