python opencv图像拼接和显示

功能

用python的opencv读入多个图片,组成图片列表,而后将图片列表按照设定的比例拼接成一张图像。如图所示。

demo代码如下:

python 复制代码
# --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)
相关推荐
AI探索者10 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者10 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh12 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅12 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽13 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时16 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿19 小时前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng81 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi1 天前
Chapter 2 - Python中的变量和简单的数据类型
python