Major_Python常用工具函数utils

Python

from major_utils import *
import os
'''

获取所有和正确类别不一致的图像,复制到错误分析的文件夹中
找到和当前类别不一致的图像的名称,用这个名称在source_dir文件夹中找到不一致的那张图像,然后把那张图像放到错误分析的文件夹中


'''

# 0.输入
source_dir = r"./predict4"
current_cls_name = 0
anay_dir_name = r"./error_"+str(current_cls_name)




# 1.读取txt文件
# 找到和当前类别不一致的图像的名称,用这个名称在source_dir文件夹中找到不一致的那张图像,然后把那张图像放到错误分析的文件夹中
with open("./view_test.txt","r",encoding="utf-8") as f:
    # 2.遍历每一行
    res = f.readline()
    # 3.获取图像名称 ,和第一个类别
    imgNamePath =  res.split(" ")[2]
    imgName = os.path.basename(imgNamePath)
    clsName = res.split(" ")[4]
    # 4.第一个预测的类别和current_cls_name真是类别比较,如果不一致,就将这个图像在source_dir找到,找到复制到错误分析文件夹中
    if clsName != str(current_cls_name):
        src_path = os.path.join(source_dir,imgName)
        makedir(anay_dir_name)
        dst_path = os.path.join(anay_dir_name,imgName)
        copyfile(src_path=src_path,dst_path=dst_path)

    while res:
        # 2.遍历每一行
        res = f.readline()
        # 3.获取图像名称 ,和第一个类别
        imgNamePath = res.split(" ")[2]
        imgName = os.path.basename(imgNamePath)
        clsName = res.split(" ")[4]
        # 4.第一个预测的类别和current_cls_name真是类别比较,如果不一致,就将这个图像在source_dir找到,找到复制到错误分析文件夹中
        if clsName != str(current_cls_name):
            src_path = os.path.join(source_dir,imgName)
            makedir(anay_dir_name)
            dst_path = os.path.join(anay_dir_name,imgName)
            copyfile(src_path=src_path,dst_path=dst_path)


major_utils

from tkinter.filedialog import askopenfilename,askdirectory
import shutil
import os
import cv2
from PIL import Image
import json


'''
读取json
'''
def readJsonFile(file_path):
    with open(file_path, encoding='utf-8-sig', errors='ignore') as file:
        ValueDict = json.load(file)
        return ValueDict


'''
打开文件选择器
'''
def openfile():
    file_path = askopenfilename(title='请选择文件')
    return file_path


'''
打开文件夹选择器
'''
def opendir():
    dir_path = askdirectory(title='请选择文件夹')
    return dir_path


'''
写txt文本
'''
def write_file_rewrite(content,file_path):
    with open(file_path,'w',encoding='utf-8') as file:
        file.write(content)

'''
获取路径的文件名,不含尾缀
'''
def getFileNameWithoutExt(path):
    return os.path.splitext(os.path.basename(path))[0]

'''
添加txt文本
'''
def write_file_append(content,file_path):
    with open(file_path, 'a', encoding='utf-8') as file:
        file.write(content)


'''
读取txt文本
'''
def read_file(file_path):
    with open(file_path,'r') as file:
        return file.readlines()


'''
获取所有文件夹路径
'''
def get_alldirs_path(dir_path):
    tuples = os.walk(dir_path)
    dirs = []
    for tuple in tuples:
        dirs.append(tuple[0])
    return dirs


'''
获取文件夹路径
'''
def get_dirs_path(dir_path):
    files_dirs_path = os.listdir(dir_path)
    dirs_path = []
    for i in files_dirs_path:
        if(os.path.isdir(os.path.join(dir_path,i))):
            dir_p = os.path.join(dir_path,i)
            dirs_path.append(dir_p)
    return dirs_path


'''
获取文件路径
'''
def get_files_path(dir_path):
    files_path = os.listdir(dir_path)
    files_path_list = []
    for i in files_path:
        if (os.path.isfile(os.path.join(dir_path,i))):
            filw_p = os.path.join(dir_path,i)
            files_path_list.append(filw_p)
    return files_path_list



'''
获取父目录
'''
def get_path_parent_dir(dir_path):
    up_path = os.path.dirname(dir_path)
    return  up_path


'''
复制文件
'''
def copyfile(src_path,dst_path):
    shutil.copy(src_path, dst_path)  # src target


'''
剪切文件
'''
def movefile(src_path,dst_path):
    if not os.path.isfile(src_path):
        print("%s not exist!" % (src_path))
    else:
        fpath, fname = os.path.split(src_path)  # 分离文件名和路径
        if not os.path.exists(dst_path):
            os.makedirs(dst_path)  # 创建路径
        shutil.move(src_path, dst_path + fname)  # 移动文件
        # print("move %s -> %s" % (src_path, dst_path + fname))


'''
重命名文件
'''
def renamefile(src_path,dst_path):
    pass


'''
判断文件是否存在
'''
def is_exist_file(file_path):
    pass


'''
删除文件
'''
def removefile():
    pass

'''
获取当前工作目录
'''
def getcwd():
    pass


def makedir(dir_path):
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)

def copydir(src_dir_path,dst_dir_path):
    try:
        files = get_files_path(src_dir_path)
        makedir(dst_dir_path)
        for file in files:
            src_path = file
            dst_path = os.path.join(dst_dir_path, os.path.basename(file))
            copyfile(src_path=src_path, dst_path=dst_path)
    except Exception as exp:
        print(exp)



def movedir():
    pass

def renamedir():
    pass

'''
删除文件夹
'''
def deletedir(dir_path):
    import shutil
    shutil.rmtree(dir_path)

'''
显示图像
'''
def img_show(cv2Img):
    img = Image.fromarray(cv2.cvtColor(cv2Img, cv2.COLOR_BGR2RGB))
    img.show()


if __name__ == '__main__':
    a =[1,2,3]
    b = [2,5,6]
    a.append(b)
    print("")


示例

import tkinter as tk
import tkinter.font as tkFont
from major_utils import *
from tqdm import tqdm
import time


class App2:
    def __init__(self, root):
        #setting title
        root.title("Frm_复制图像对应的json放到一个文件夹中")
        #setting window size
        width=585
        height=316
        screenwidth = root.winfo_screenwidth()
        screenheight = root.winfo_screenheight()
        alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
        root.geometry(alignstr)
        root.resizable(width=False, height=False)

        GLabel_188=tk.Label(root)
        ft = tkFont.Font(family='Times',size=10)
        GLabel_188["font"] = ft
        GLabel_188["fg"] = "#333333"
        GLabel_188["justify"] = "center"
        GLabel_188["text"] = "图像文件夹:"
        GLabel_188.place(x=30,y=50,width=90,height=30)

        GLabel_535=tk.Label(root)
        ft = tkFont.Font(family='Times',size=10)
        GLabel_535["font"] = ft
        GLabel_535["fg"] = "#333333"
        GLabel_535["justify"] = "center"
        GLabel_535["text"] = "JSON文件夹"
        GLabel_535.place(x=30,y=90,width=87,height=30)

        self.GLineEdit_502=tk.Entry(root)
        self.GLineEdit_502["borderwidth"] = "1px"
        ft = tkFont.Font(family='Times',size=10)
        self.GLineEdit_502["font"] = ft
        self.GLineEdit_502["fg"] = "#333333"
        self.GLineEdit_502["justify"] = "center"
        self.GLineEdit_502_content = tk.StringVar()
        self.GLineEdit_502["textvariable"] = self.GLineEdit_502_content
        self.GLineEdit_502.place(x=120,y=50,width=382,height=32)

        self.GLineEdit_741=tk.Entry(root)
        self.GLineEdit_741["borderwidth"] = "1px"
        ft = tkFont.Font(family='Times',size=10)
        self.GLineEdit_741["font"] = ft
        self.GLineEdit_741["fg"] = "#333333"
        self.GLineEdit_741["justify"] = "center"
        self.GLineEdit_741_content = tk.StringVar()
        self.GLineEdit_741["textvariable"] = self.GLineEdit_741_content
        self.GLineEdit_741.place(x=120,y=90,width=383,height=30)

        GButton_281=tk.Button(root)
        GButton_281["bg"] = "#f0f0f0"
        ft = tkFont.Font(family='Times',size=10)
        GButton_281["font"] = ft
        GButton_281["fg"] = "#000000"
        GButton_281["justify"] = "center"
        GButton_281["text"] = "复制JSON"
        GButton_281.place(x=390,y=180,width=114,height=30)
        GButton_281["command"] = self.GButton_281_command

    def GButton_281_command(self):
        # 图像文件夹
        input_dir = self.GLineEdit_502_content.get()
        # JSON文件夹
        input_dir2 = self.GLineEdit_741_content.get()
        # 存放文件夹
        output_dir = os.path.join(input_dir2,"JSON"+str(time.time()))
        if not os.path.exists(output_dir):
            makedir(output_dir)
        file_paths = get_files_path(input_dir)

        for index_file,file_path in enumerate(tqdm(file_paths)):
            name = os.path.basename(file_path).split(".")[0]
            try:
                src_path = os.path.join(input_dir2,name+".json")
                dst_path = os.path.join(output_dir,name+".json")
                copyfile(src_path=src_path,dst_path=dst_path)
                print(src_path)
            except Exception as exp:
                pass


if __name__ == "__main__":
    root = tk.Tk()
    app = App2(root)
    root.mainloop()

常用包

pip install tqdm -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install opencv-python -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install pillow -i https://pypi.tuna.tsinghua.edu.cn/simple
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值