OpenCV单窗口并排显示多张图片
- 效果
- 代码
PS:本例的代码适合图片的宽度和高度都相同。
效果
原始三张图片:
合并显示:
代码
import cv2
import numpy as npdef opencv_multi_img():# 读取图片img1 = cv2.imread('saw_1.jpeg')img2 = cv2.imread('saw_2.jpeg')img3 = cv2.imread('saw_3.jpeg')# 检查图片是否成功加载if img1 is None or img2 is None or img3 is None:print("Error: Unable to load one or more images.")return# 获取图片的高度和宽度h1, w1, _ = img1.shapeh2, w2, _ = img2.shapeh3, w3, _ = img3.shape# 确保所有图片的高度相同if h1 != h2 or h1 != h3:print("Error: Images must have the same height.")return# 创建一个空白的大画布max_width = w1 + w2 + w3 # 三张图片的总宽度canvas = np.zeros((h1, max_width, 3), dtype=np.uint8)# 将图片放置到画布上canvas[:, :w1] = img1canvas[:, w1:w1 + w2] = img2canvas[:, w1 + w2:w1 + w2 + w3] = img3# 展示多个图片cv2.imshow("multi_img", canvas)# 等待用户按键关闭窗口cv2.waitKey(0)cv2.destroyAllWindows()# 调用函数
opencv_multi_img()