python图像拼接

1.拼接图片中间无间隙
from PIL import Image,ImageDraw,ImageFont
import cv2
import numpy as np
import os

def draw_title(picture_name,code):
    img = Image.open(r"D:\WPS\img\{}".format(picture_name))
    img = img.resize((1000, 800))
    draw = ImageDraw.Draw(img)
    img_font = ImageFont.truetype("c:\Windows\Fonts\msyh.ttc",size=50)
    if code=="NG":
        draw.multiline_text((10,10),code,fill="red",font=img_font)
    else:
        draw.multiline_text((10, 10), code, fill="green", font=img_font)
    img.save(r"D:\WPS\img\{}.png".format(code))

def join(png1, png2, flag='horizontal'):

    img1, img2 = Image.open(png1), Image.open(png2)
    # img1 = img1.resize((800,500),Image.ANTIALIAS)
    # img2 = img2.resize((800,500),Image.ANTIALIAS)
    size1, size2 = img1.size, img2.size
    if flag == 'horizontal':
        joint = Image.new('RGB', (size1[0] + size2[0], size1[1]))
        loc1, loc2 = (0, 0), (size1[0], 0)
        joint.paste(img2, loc2)
        joint.paste(img1, loc1)
        joint.save(r'D:\WPS\img\horizontal.jpg')
    elif flag == 'vertical':
        joint = Image.new('RGB', (size1[0], size1[1] + size2[1]))
        loc1, loc2 = (0, 0), (0, size1[1])
        joint.paste(img1, loc1)
        joint.paste(img2, loc2)
        joint.save(r'D:\WPS\img\vertical.jpg')

def dir_picture_name(path):
    picture_list = []
    picture_name = ""
    for picture_item in os.listdir(path):
        if "bomLabel" in picture_item:
            picture_name = picture_item
            picture_list.append(picture_name)
            draw_title(picture_name,"OK")
        elif "predictions.jpg" in picture_item:
            picture_name = picture_item
            picture_list.append(picture_name)
            draw_title(picture_name,"NG")
        else:
            pass
    if len(picture_list) != 0:
        # 横向拼接
        join( r"D:\WPS\img\OK.png",r"D:\WPS\img\NG.png", flag='horizontal')
        # 纵向拼接
        # join(png1, png2, flag='vertical')
    else:
        print("90 Esop pic or parse pic is not exiest!")
if __name__ == '__main__':
    dir_picture_name(r'D:\WPS\img')
    # # 两张图片地址:
    # png1 = r"D:\WPS\img\BomLabel.jpg"
    # png2 = r"D:\WPS\img\NG.jpg"

2.中间有间隙

import cv2 as cv
import numpy as np
import os
import matplotlib.pyplot as plt
from PIL import Image,ImageDraw,ImageFont

def draw_title(picture_name,code):
    img = Image.open(r"D:\WPS\img\{}".format(picture_name))
    #修改两个图片尺寸
    img = img.resize((1400, 1200))
    draw = ImageDraw.Draw(img)
    img_font = ImageFont.truetype("c:\Windows\Fonts\msyh.ttc",size=50)
    if code=="NG":
        draw.multiline_text((10,10),code,fill="red",font=img_font)
    else:
        draw.multiline_text((10, 10), code, fill="green", font=img_font)
    img.save(r"D:\WPS\img\{}.png".format(code))

def show_images(images, titles=None, num_cols=None, scale=8, normalize=False):
    """ 一个窗口中绘制多张图像:
    Args:
        images: 可以为一张图像(不要放在列表中),也可以为一个图像列表
        titles: 图像对应标题、
        num_cols: 每行最多显示多少张图像
        scale: 用于调整图窗大小
        normalize: 显示灰度图时是否进行灰度归一化
    """
    # 多张图片显示
    if not isinstance(scale, tuple):
        scale = (scale, scale)

    num_imgs = len(images)
    if num_cols is None:
        num_cols = int(np.ceil((np.sqrt(num_imgs))))
    num_rows = (num_imgs - 1) // num_cols + 1

    idx = list(range(num_imgs))
    _, figs = plt.subplots(num_rows, num_cols,
                           figsize=(scale[1] * num_cols, scale[0] * num_rows))
    for f, i, img in zip(figs.flat, idx, images):
        if len(img.shape) == 3:
            # opencv库中函数生成的图像为BGR通道,需要转换一下
            B, G, R = cv.split(img)
            img = cv.merge([R, G, B])
            f.imshow(img)
        elif len(img.shape) == 2:
            # pyplot显示灰度需要加一个参数
            if normalize:
                f.imshow(img, cmap='gray')
            else:
                f.imshow(img, cmap='gray', vmin=0, vmax=255)
        else:
            raise TypeError("Invalid shape " +
                            str(img.shape) + " of image data")
        if titles is not None:
            f.set_title(titles[i], y=-0.15)
        f.axes.get_xaxis().set_visible(False)
        f.axes.get_yaxis().set_visible(False)
    # 将不显示图像的fig移除,不然会显示多余的窗口
    if len(figs.shape) == 1:
        figs = figs.reshape(-1, figs.shape[0])
    for i in range(num_rows * num_cols - num_imgs):
        figs[num_rows - 1, num_imgs % num_cols + i].remove()
    plt.savefig("d:\wps\img\plt.jpg")
    # plt.show()

def dir_picture_name(path):
    picture_list = []
    picture_name = ""
    for picture_item in os.listdir(path):
        if "bomLabel" in picture_item:
            picture_name = picture_item
            picture_list.append(picture_name)
            draw_title(picture_name,"OK")
        elif "predictions.jpg" in picture_item:
            picture_name = picture_item
            picture_list.append(picture_name)
            draw_title(picture_name,"NG")
        else:
            pass

if __name__ == '__main__':
    dir_picture_name(r'D:\WPS\img')
    src1 = cv.imread(r"d:\wps\img\OK.png")
    src2 = cv.imread(r"d:\wps\img\NG.png")
    if os.path.isfile(r"d:\wps\img\OK.png") or os.path.isfile(r"d:\wps\img\NG.png"):
        show_images([src1,src2])
    else:
        print("cant parse label!")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值