使用PIL库将一张小图贴到大图的指定位置

# FileName : copyHandsToMask
# Author : Donghao
# CreateTime : 2021-10-24 17:25
# ModifyTime : 2021-10-24 17:25
# Description : copy mask of hands to body mask

import os
import cv2
import glob
import tqdm
import numpy as np
from PIL import Image


# #手部标注存储路径
# hands_mask_dir = './15-4-tmp8/tmp8_hands_resieze4_labels/'
# #全身标注存储路径
# body_mask_dir = './15-4-tmp8/tmp8_labels/'
# #重新合成文件存储路径
# result_dir =  './15-4-tmp8/annotations/'
#手部标注存储路径
hands_mask_dir = './14_4-real/tmp4/tmp4_hands_resieze4_labels/'
#全身标注存储路径
body_mask_dir = './14_4-real/tmp4/tmp4_labels/'
#重新合成文件存储路径
result_dir =  './14_4-real/tmp4/annotations/'
if os.path.exists(result_dir) is False:
    os.makedirs(result_dir)


def Picture_Synthesis(mother_img,
                      son_img,
                      save_img,
                      factor = 1,
                      coordinate=None):

    """
    :param mother_img: 母图路径
    :param son_img: 子图路径
    :param save_img: 保存图片名
    :param coordinate: 子图在母图的坐标
    :param factor: 子图缩放因子,默认为1,即不进行缩放
    :return:
    """

    #将图片赋值,方便后面的代码调用
    M_Img = Image.open(mother_img)
    S_Img = Image.open(son_img)

    #给图片指定色彩显示格式
    M_Img = M_Img.convert("RGBA")  # CMYK/RGBA 转换颜色格式(CMYK用于打印机的色彩,RGBA用于显示器的色彩)

    # 获取图片的尺寸
    M_Img_w, M_Img_h = M_Img.size  # 获取被放图片的大小(母图)
    # print("母图尺寸:",M_Img.size)
    S_Img_w, S_Img_h = S_Img.size  # 获取小图的大小(子图)
    # print("子图尺寸:",S_Img.size)

    # 対子图进行缩放
    size_w = int(S_Img_w / factor)
    size_h = int(S_Img_h / factor)
    if S_Img_w > size_w:
        S_Img_w = size_w
    if S_Img_h > size_h:
        S_Img_h = size_h

    # # 重新设置子图的尺寸
    icon = S_Img.resize((S_Img_w, S_Img_h), Image.ANTIALIAS)
    w = int((M_Img_w - S_Img_w) / 2)
    h = int((M_Img_h - S_Img_h) / 2)
    # 第二个参数:
    # Image.NEAREST :低质量
    # Image.BILINEAR:双线性
    # Image.BICUBIC :三次样条插值
    # Image.ANTIALIAS:高质量

    try:
        if coordinate==None or coordinate=="":
            # print("未指定坐标,剧中粘贴")
            # 粘贴子图到母图的指定坐标(当前居中)
            coordinate=(w, h)
            M_Img.paste(icon, coordinate, mask=None)
        else:
            # print("已经指定坐标")
            # 粘贴子图到母图的指定坐标(当前居中)
            M_Img.paste(icon, coordinate, mask=None)
    except BaseException as e:
        print("坐标指定出错 ")
        with open('./errorlog.txt', 'a') as f:
            f.write(str(e) + '\n\n')

    # 保存图片
    M_Img.save(save_img)


if __name__ == '__main__':

    # root_path = '.'
    # dirlist = os.listdir(root_path)
    # for dir in tqdm(dirlist):
    #     child_path = os.path.join(root_path, dir)
    #     childlist = os.listdir(child_path)
    #
    #     for child in childlist:
    #         work_path = os.path.join(child_path, child)
    #         work_dir_list = os.listdir(work_path)
    # #手部标注存储路径
    # hands_mask_dir = './14_2-real/14-2-temp2/tmp2_hands_labels/'
    # #全身标注存储路径
    # body_mask_dir = './14_2-real/14-2-temp2/tmp2_labels/'
    # #重新合成文件存储路径
    # result_dir =  './14_2-real/14-2-temp2/annotations/'
    # if os.path.exists(result_dir) is False:
    #     os.makedirs(result_dir)

    hands_mask_path_list = glob.glob(hands_mask_dir + '*pseudo.jpg')
    body_mask_path_list = glob.glob(body_mask_dir + '*pseudo.png')
    # print(type(hands_mask_path_list), len(hands_mask_path_list), hands_mask_path_list[0])

    # 打开包含手坐标信息的txt文件
    with open('./hands_boxes.txt', 'r') as rf:
        hands_boxes_file = rf.readlines()
    # print(type(hands_boxes_file), hands_boxes_file[4],hands_boxes_file[1])

    for hands_mask_path in tqdm.tqdm(hands_mask_path_list):

        # 判断是否为全黑图片
        hands_mask = Image.open(hands_mask_path)
        r, g, b = hands_mask.getextrema()
        if r[1] == 0 and g[1] == 0 and b[1] == 0:
            continue

        hands_mask_name = os.path.basename(hands_mask_path)
        hand_number = hands_mask_name[-12:-11]
        origin_image_name = hands_mask_name[:-13] + '.png'
        body_mask_name = hands_mask_name[:-13] + '_pseudo.png'
        body_mask_path = body_mask_dir + body_mask_name

        # print(hand_number)
        # print(origin_image_name)
        # print(body_mask_name)
        # print(body_mask_path)

        if os.path.isfile(body_mask_path) is False:
            print(f"Body mask image not found: ")
            print(f"hands_mask_path: {hands_mask_path}")
            print(f"body_mask_path: {body_mask_path}")
            with open('./errorlog.txt', 'a') as f:
                f.write(f"Body mask image not found: \nhands_mask_path: {hands_mask_path}\nbody_mask_path: {body_mask_path}\n\n")
            continue

        save_path = os.path.join(result_dir, origin_image_name)
        if os.path.isfile(save_path):
            body_mask_path = save_path

        index = hands_boxes_file.index(origin_image_name + '\n')
        start_index = index + (int(hand_number) - 1) * 5 + 2
        lx = int(float(hands_boxes_file[start_index]))
        ly = int(float(hands_boxes_file[start_index + 1]))
        rx = int(float(hands_boxes_file[start_index + 2]))
        ry = int(float(hands_boxes_file[start_index + 3]))

        Picture_Synthesis(mother_img = body_mask_path,
                          son_img = hands_mask_path,
                          save_img = save_path,
                          factor = 4,
                          coordinate=(ly, lx))

    for body_mask_path in tqdm.tqdm(body_mask_path_list):
        body_mask_name = os.path.basename(body_mask_path)
        body_mask_name = body_mask_name[: -11] + '.png'

        save_path = os.path.join(result_dir, body_mask_name)
        if os.path.isfile(save_path) is False:
            img = Image.open(body_mask_path)
            img.save(save_path)

你可能感兴趣的:(计算机视觉,python,opencv,PIL)