python常用用法
获取目录下的所有文件
os.listdir()
>>> my_list = ['a', 'b', 'c'] >>> for idx, val in enumerate(my_list): ... print(idx, val)
创建文件夹
porject_path = os.getcwd() print(porject_path) chip_path2 = "./design_my/img_output/mask_chips/"+img_name+'/' chip_path= os.path.join(porject_path,chip_path2) print(chip_path) if os.path.exists(chip_path): print(chip_path," had exist!") else: os.makedirs(chip_path) print("create: ", chip_path) mask_output = "./design_my/img_output/mask_output/" if os.path.exists(mask_output): print(mask_output," had exist!") else: os.makedirs(mask_output) print("create: ", mask_output) create: /home/lhw/Gradute/collage/fbrs_interactive_segmentation-master/./design_my/img_output/mask_chips/000000000625/ create: ./design_my/img_output/mask_output/
获取dict的第一个元素的value
d = {'a': 1, 'b': 2} print(list(d.values())[0]) print(next(iter(d.values()))) #适用于数据量多的时候会更快
import os file_name = os.path.basename(__file__) print(file_name) # 输出为 test.py file_name = file_name.split('.')[0] print(file_name) # 输出为 test stem, suffix = os.path.splitext(filename) print(stem, suffix) # test .py
文件名排序
# img_path = "./openpose_data/img/COCO_train2014_000000000625.jpg" img_paths = "./openpose_data/img/" img_list = os.listdir(img_paths) img_list.sort(key=lambda x: int(x[:-4])) # 倒着数第四位'.'为分界线,按照‘.'左边的数字从小到大排序 print(img_list)
计算两个mask图像的IOU
def mask_iou(det_mask, pred_mask): ''' Computes IoU between two masks Input: two 2D array mask ''' Union = (pred_mask + det_mask) != 0 Intersection = (pred_mask * det_mask) != 0 return np.sum(Intersection) / np.sum(Union)