[python] 个人日常python工具代码
生成文件目录结构
生成文件夹或文件的目录结构,并保存结果。可选是否滤除目录,特定文件以及可以设定最大查找文件结构深度。效果如下:
root:[z:/]
|--a.py
|--image
| |--cat1.jpg
| |--cat2.jpg
| |--cat3.jpg
| |--cat4.jpg
| |--cat5.jpg
| |--cat6.jpg
|--result
| |--result.jpg
|--save.txt
|--test.py
参考
https://blog.csdn.net/feizai1208917009/article/details/88396501
代码如下:
import os
import os.path
# 结果保存路径
txtFilePath="save.txt"
savetxtFile = open(txtFilePath, 'w',encoding='utf-8')
# 文件查找路径
findFilePath="z:/"
# 是否只显示目录
isShowDir = False
# 最大子目录文件深度
maxDepth = 3
# 需要跳过的文件目录和文件
skipFile = [".git","doc"]
# 需要跳过的文件类型
#skipFileType = [".txt",".MOV"]
skipFileType=[]
def saveFile(depth,item):
# 保存的内容
saveCotent="| " * depth + "|--" + item
print(saveCotent)
savetxtFile.write( saveCotent)
savetxtFile.write("\n")
def listDir(path, depth):
# 获得绝对路径
absPath=os.path.abspath(path)
if depth == 0:
print("root:[" + path + "]")
savetxtFile.write("root:[" + path + "]")
savetxtFile.write("\n")
# 超过最大深度
if depth > maxDepth:
return
# 展开目录文件
for item in os.listdir(path):
# 跳过指定的文件目录和文件
if item not in skipFile:
# 跳过指定的后缀文件
if os.path.splitext(item)[1] in skipFileType:
continue
# 获得项目绝对目录地址
absItem=os.path.join(absPath,item)
# 是否只显示目录
if isShowDir is True:
if os.path.isdir(absItem) is True:
saveFile(depth,item)
else:
saveFile(depth,item)
# 查找子项
if os.path.isdir(absItem):
listDir(absItem, depth +1)
if __name__ == '__main__':
listDir(findFilePath, 0)
savetxtFile.close()
多图合并
将多图合并为一张图像,并添加图像对应文字,效果如下:
参考
https://blog.csdn.net/qq_37598011/article/details/101551593
https://cloud.tencent.com/developer/ask/204503
代码如下:
import os
import numpy as np
from PIL import ImageFont, ImageDraw, Image
# 创建字体文件
# 文字名
def creat_font_img(value):
# 设置空白图像
img = Image.new('RGB', (TEXTWIDTH, TEXTHEIGHT), "white")
# 设置需要显示的字体 宋体
fontpath = TEXTFONT
# 32为字体大小
font = ImageFont.truetype(fontpath, TEXTSIZE)
# 绘图
img_pil = img
draw = ImageDraw.Draw(img_pil)
# 获取字体宽度
sum_width = 0
sum_height = 0
# 添加文字
for char in value:
width, height = draw.textsize(char, font)
sum_width += width
sum_height = height
# 绘制文字信息
# 文字居中
draw.text(((img_pil.size[0] - sum_width) / 2, (img_pil.size[1] -
sum_height) / 2 + TEXTOFFSET), value, font=font, fill=(0, 0, 0))
return img_pil
# 创建单个带标题和图像的文字
def create_single_img(path):
# 提取图片
img = Image.open(path)
# 提取图像名
text = img.filename.split(".")[0]
imgFont = creat_font_img(text)
# 图像大小重置
img = img.resize((IMGWIDTH, IMGHEIGHT))
# 合并的图像
mergeImg = Image.new(
"RGB", (IMGWIDTH+IMAGESPACE, IMGHEIGHT+TEXTHEIGHT), "white")
mergeImg.paste(imgFont, (0, 0))
# 贴图
mergeImg.paste(img, (0, TEXTHEIGHT))
return mergeImg
def create_multi_img(dirpath):
# 转到工作目录
os.chdir(dirpath)
mergeImgs = []
for dirname in os.listdir(dirpath):
if dirname.split(".")[-1] == 'jpg':
# print(dirname)
mergeImgs.append(create_single_img(dirname))
if ROW*COL is not len(mergeImgs):
print("错误,请检查图像数量")
# 单个图像尺寸
mergeW, mergeH = mergeImgs[0].size
finalImg = Image.new("RGB", (mergeW*COL, mergeH*ROW), "white")
# 第几张图
num = 0
# 排列图像
for top in range(0, mergeH*ROW, mergeH):
for left in range(0, mergeW*COL, mergeW):
#print(left, top)
finalImg.paste(mergeImgs[num], (left, top))
num = num+1
return finalImg
# -----------------
# 全局变量
# 图片排列方式
ROW = 3
COL = 2
# 单个图像大小
IMGWIDTH, IMGHEIGHT = 600, 600
# 图像间距
IMAGESPACE = 10
# 文字图像尺寸 文字图像宽需要与单张输入图像等宽
TEXTWIDTH, TEXTHEIGHT = IMGWIDTH, 100
# 文字大小和文字上下偏移量
TEXTSIZE, TEXTOFFSET = 64, 5
# 文字字体名
# simsun宋体, msyh.ttc微软雅黑
TEXTFONT = "font/msyh.ttc"
if __name__ == '__main__':
finalImg = create_multi_img("./")
# 保存图像
finalImg.save("result.jpg", dpi=(300.0, 300.0))
找出文件夹中相似图像
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 8 06:18:17 2021
@author: luohenyueji
"""
import threading
import time
import queue
import cv2
import os
import numpy as np
import cv2
import shutil
import numpy as np
import os
# 计算hash值
def consume(thread_name, q, result):
while True:
filename, img = q.get()
phash_value = cv2.img_hash.PHash_create().compute(img)
result[str(filename)] = phash_value
q.task_done()
# 读取图像
def produce(thread_name, q, imgPath):
for i in os.listdir(imgPath):
if i.split('.')[-1] == 'jpg':
filename = os.path.join(imgPath, i)
imgfile = cv2.imread(filename)
if imgfile is None:
continue
q.put([filename, imgfile])
print(filename)
q.join()
# 结果
result = {}
imgpath = "save"
q = queue.Queue()
p = threading.Thread(target=produce, args=("producer", q, imgpath))
c1 = threading.Thread(target=consume, args=("consumer1", q, result))
c2 = threading.Thread(target=consume, args=("consumer2", q, result))
c3 = threading.Thread(target=consume, args=("consumer3", q, result))
c4 = threading.Thread(target=consume, args=("consumer4", q, result))
c1.setDaemon(True)
c2.setDaemon(True)
c3.setDaemon(True)
c4.setDaemon(True)
p.start()
c1.start()
c2.start()
c3.start()
c4.start()
p.join()
np.save("file.npy", result)
filehash = np.load('file.npy', allow_pickle=True).item()
save_file = "save_similar"
os.makedirs(save_file, exist_ok=True)
# pash计算结构
phash_create = cv2.img_hash.PHash_create()
# 阈值
pash_thre = 10
while (len(filehash)):
# 取keys
now_keys = list(filehash.keys())[0]
# 还剩多少图片
print("还剩{}图片".format(len(filehash.keys())))
now_keys_value = filehash.pop(now_keys)
# 相同图像存储
similar_filename = []
# 循环计算值
for keys in filehash:
pash_value = phash_create.compare(now_keys_value, filehash[keys])
if pash_value < pash_thre:
similar_filename.append(keys)
try:
# 移动图像
if len(similar_filename) > 0:
# 获得关键key名字
now_keys_filename = os.path.basename(now_keys)
# 创建的保存文件路径
save_file_path = os.path.join(save_file, now_keys_filename[:-4])
os.makedirs(save_file_path, exist_ok=True)
# 移动关键keys图片
shutil.move(now_keys,os.path.join(save_file_path,now_keys_filename))
# 从字典中移除值,并移动图片
for i in similar_filename:
filehash.pop(i)
# 获得key名字
keys_filename = os.path.basename(i)
# 移动图片
shutil.move(i, os.path.join(save_file_path, keys_filename))
except:
continue
本文来自博客园,作者:落痕的寒假,转载请注明原文链接:https://www.cnblogs.com/luohenyueji/p/16970278.html