python写的一些小工具

清理文件夹

删除某路径下所有带有delName字段的文件,如:删除.DS_Store文件

import os
import string
import shutil

def DelMacFile(path,delName):
    '''
    删除某个文件夹下所有带有delName字段的文件
    :param path: 删除path路径下所有符合的文件,eg:F:/test
    :param delName:需要删除文件所包含的字段
    :return: 处理成功或失败
    '''
    list=os.walk(path)
    for i in list:
        #print(i)
        for f in i[2]:
            if delName in f: #若遍历的文件名包含delName字段,则将其删除
                targetFile=i[0]+'/'+f
                targetFile=targetFile.replace('\\','/')
                #print(targetFile)

                if os.path.isdir(targetFile):
                    shutil.rmtree(targetFile)
                    print("成功删除文件夹:"+targetFile)
                elif os.path.isfile(targetFile):
                    print("成功删除文件:" + targetFile)
                    os.remove(targetFile)

if __name__ == '__main__':
    path="F:/code/FET-GAN-master/FET-GAN-master/test"
    delName=".DS_Store"
    DelMacFile(path,delName)

存储tensor格式图片

将tensor格式的图片存储到本地,便于观察训练时的数据变化

from torchvision import transforms
from PIL import Image
import numpy as np
import time
import torch
from PIL import Image
import os

# loader使用torchvision中自带的transforms函数
loader = transforms.Compose([
    transforms.ToTensor()])

unloader = transforms.ToPILImage()

device = torch.device('cuda')


# 1 PIL读取图片转化为Tensor
# 输入图片地址
# 返回tensor变量
def image_loader(image_name):
    image = Image.open(image_name).convert('RGB')
    image = loader(image).unsqueeze(0)
    return image.to(device, torch.float)


# 2 将PIL图片转化为Tensor
# 输入tensor变量
# 输出PIL格式图片
def tensor_to_PIL(tensor):
    image = tensor.cpu().clone()
    image = image.squeeze(0)
    image = unloader(image)
    return image


# 4 直接展示tensor格式图片
def imshow(tensor, title=None):
    image = tensor.cpu().clone()  # we clone the tensor to not do changes on it
    image = image.squeeze(0)  # remove the fake batch dimension
    image = unloader(image)
    plt.imshow(image)
    if title is not None:
        plt.title(title)
    plt.pause(0.001)  # pause a bit so that plots are updated


# 5 直接保存tensor格式图片
def save_image(tensor, path, keyName,**para):
    dir = path
    image = tensor.cpu().clone()  # we clone the tensor to not do changes on it
    image = image.squeeze(0)  # remove the fake batch dimension
    print("需要存储tensor的size为:",image.size())

    if len(image.size())==4:
        # (number,channels,width,height)
        for num,i in enumerate(image):
            #print(i.size())
            image = unloader(i)
            save_path=path + '/' + time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime()) + '_(' + keyName+'_'+str(num) +').png'
            image.save(save_path)
            print("存储"+keyName+" 第"+str(num)+"张图片:"+save_path)
    elif len(image.size())==3:
        image = unloader(image)
        image.save(path + '/' + time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime()) + '_'+keyName+'.png')
        print("存储一张"+keyName+"图片:"+path + '/' + time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())+ '_'+keyName+'.png')
    else:
        print("tensor数据维数不正确")

if __name__ == '__main__':
    image_name = "F:/1.png"
    t_image1 = image_loader(image_name)

    path="F:\test"
    save_image(t_image1, path)

合并2张图片

from PIL import Image

def ConcatImgs(img1_path,img2_path,targetImg_path):
    '''
    :param img1_path: 图片1的路径
    :param img2_path: 图片2的路径
    :param targetImg_path: 合并后新图片的存储路径
    :return:
    '''
    img1=Image.open(img1_path)
    img2=Image.open(img2_path)
    size=img1.size[0]
    target = Image.new('RGB', (size * 2, size * 1))  # 拼接前需要写拼接完成后的图片大小
    target.paste(img1,(0,0,size,size))
    target.paste(img2,(size,0,size*2,size))
    target.save(targetImg_path)

if __name__ == '__main__':
    img1_path="E:/code/yin-master/datasets/datasets_v7/0/A_0.png"
    img2_path = "E:/code/yin-master/datasets/datasets_v7/0/C_0.png"
    targetImg_path="E:/pycharm_workspace/utils/targetImg.png"
    ConcatImgs(img1_path,img2_path,targetImg_path)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值