用python的opencv读入多个图片,组成图片列表,而后将图片列表按照设定的比例拼接成一张图像。如图所示。
# --coding:utf-8--
# 读取图片,汇总结果
import cv2 as cv
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import math
def show(imgs_np):
cv.namedWindow("image")
cv.imshow('image', imgs_np)
cv.waitKey(0)
def cat(imgs:list,row=2,colcumn=2,resize_shape=[1920,1080]):
len_=imgs.__len__()
img0=imgs[0]
img_shape=img0.shape
img_row_first=[]
new_imgs=[]
# 把列表里的图片统一尺寸
for i in range(len_):
new_img = cv.resize(imgs[i], [img_shape[1], img_shape[0]], interpolation=cv.INTER_LINEAR)
new_imgs.append(new_img)
del imgs
# 找到每一行的图片作为合并初始图片
for i in range(row):
img_row_first.append(new_imgs[i*colcumn])
# 每一行内的每一列合并
# for i in range(len_):
# now_col=math.floor(i/row)
# img_cat=img_row_first[now_col]
# img_cat=np.concatenate((img_cat,new_imgs[i]),axis=1)
# img0=np.concatenate((img2,new_img),axis=1)
img_cat=[]
for r in range(row):
img_cat_row=img_row_first[r]
for c in range(colcumn):
if c!=0:
img_cat_row=np.concatenate((img_cat_row,new_imgs[c]),axis=1)
img_cat.append(img_cat_row)
# 将所有行得到的图片合并
img_cat0=img_cat[0]
for i in range(len(img_cat)):
if i != 0:
img_cat0 = np.concatenate((img_cat0, img_cat[i]), axis=0)
# 将最终拼接后的图片resize成需要的尺寸
img_cat0=cv.resize(img_cat0,resize_shape,interpolation=cv.INTER_LINEAR)
return img_cat0
if __name__=="__main__":
# imgs = Image.open("/media/lbw/E/lbw/data/scene/datasets/test/test/2.jpg",mode='r')
imgs1=cv.imread("/media/lbw/E/lbw/data/scene/datasets/test/rural/13.png")
imgs2=cv.imread("/media/lbw/E/lbw/data/scene/datasets/test/rural/16.png")
imgs3=cv.imread("/media/lbw/E/lbw/data/scene/datasets/test/rural/18.jpg")
imgs4=cv.imread("/media/lbw/E/lbw/data/scene/datasets/test/rural/23.png")
imgs_list=[imgs1,imgs2,imgs3,imgs4]
# show(imgs1)
img0=cat(imgs_list)
show(img0)