python在生活中的应用-制作图片九宫格

目的:批量将多张植物照片加上植物名字后拼接成多张3*3的图片。

思路:先给给张图片命名;然后代码实现加名字和拼图操作。

结果:

python在生活中的应用-制作图片九宫格_第1张图片   

代码:

# 该代码用于将图片文件名批量添加到图片上
# 并将多张图片合并拼接为1张

# code1:读取一个文件中所有图片的名称
# 参考:https://blog.csdn.net/hou9876543210/article/details/115544223
import os
image_path = r"./flower_photo"
if os.path.isdir(image_path):
    # img_infos = os.listdir(image_path)
    # print(img_infos)
    img_infos_raw = os.listdir(image_path)
    # print(img_infos_raw)
    img_infos = [x for x in img_infos_raw if x.endswith('.jpg')]
    img_infos = sorted(img_infos) # 排序
    # print(img_infos)
    title = [i.split('.')[0] for i in img_infos]
    # print(title)
# ['logo.png', 'logo的副本.png']
# ['logo', 'logo的副本']



# code2:图片指定区域涂色
# 参考:https://blog.csdn.net/baldo/article/details/124114423
import cv2
for i in range(len(img_infos)):
    #打开图片
    img = cv2.imread(os.path.join('./flower_photo/',img_infos[i]))
    #img(指定区域) = (RGB色)
    # (4640, 3472, 3)
    h = 38 + 500 
    w = 3472 - 58 
    img[38:h, 58:w] = (255,255,255)
    #save figure
    cv2.imwrite(os.path.join('./flower_photo_add_background/',img_infos[i]), img)   




# code3-在图片上添加文字
# 参考:https://blog.csdn.net/qq_42257666/article/details/122135600
# Mac下查找支持的字体 https://blog.csdn.net/weixin_47728768/article/details/115054531

from PIL import Image, ImageDraw, ImageFont
# import matplotlib.pyplot as plt

for i in range(len(img_infos)):
    #打开图片
    img = Image.open(os.path.join('./flower_photo_add_background/',img_infos[i]))
    draw = ImageDraw.Draw(img)
    #设置字体和大小
    font_path = os.path.join("assets", "Hiragino Sans GB.ttc")
    myfont = ImageFont.truetype(font_path, size=400, encoding='utf-8')    
    fillcolor = "black" #设置字体颜色#CC3299粉色
    #读取图片的size,也就是宽度和高度 width, height = img.size
    #在(30,30)的位置开始写
    draw.text((60,60), title[i], font=myfont, fill=fillcolor)
    #保存图片
    img.save(os.path.join('./flower_photo_add_title/',img_infos[i]))
    #显示图片
    # plt.imshow(img)
    # plt.show()


# code4-将多张图片合并为1张
# 参考:https://blog.csdn.net/qq_40502460/article/details/120176473
# opencv,cv2:https://blog.csdn.net/fuhanghang/article/details/121260534
# import cv2
import numpy as np
import math
for i in range(int(len(title)/9)):
    img_list = []
    for j in range(9):
        img_path = os.path.join('./flower_photo_add_title/', img_infos[i*9+j])
        img = cv2.imread(img_path)
        h = math.floor(img.shape[0]/3)
        w = math.floor(img.shape[1]/3)
        img = cv2.resize(img, (w, h))
        img_list.append(img)
    # img0~img8
    # np.vstack():在竖直方向上堆叠
    # np.hstack():在水平方向上平铺
    mid1 = np.hstack((img_list[0], img_list[1], img_list[2]))
    mid2 = np.hstack((img_list[3], img_list[4], img_list[5]))
    mid3 = np.hstack((img_list[6], img_list[7], img_list[8]))

    img_result = np.vstack((mid1, mid2, mid3))
    out_path = os.path.join('./flower_photo_merge/', img_infos[i*9])
    cv2.imwrite(out_path, img_result)






你可能感兴趣的:(Python数据分析,python,opencv,计算机视觉)