文件读取中 */* 即data_root.glob(‘*/*‘)

该篇博客介绍了如何利用Python的glob模块遍历指定路径下的所有子目录,并获取其中的所有图片文件。通过data_root.glob('*/*'),可以获取flower_photos文件夹下daisy和dandelion两个子目录中的jpg图片文件。这个方法对于批量处理图片数据非常有用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用glob获取所有文件并存入列表中。这里*的意思为获取所有文件,因此*/*的意思则为获取文件夹下的所有文件及它们的子文件。

文件路径若为

data_root:

         C:\Users\Administrator\.keras\datasets\flower_photos

其中文件架构若为

flower_photos

|

|————————daisy

         |——————5547758_eea9edfd54_n.jpg

|

|————————dandelion

         |——————7355522_b66e5d3078_m.jpg

all_image_paths = list(data_root.glob('*/*'))
print(all_image_paths )
#结果

[WindowsPath('C:/Users/Administrator/.keras/datasets/flower_photos/daisy/5547758_eea9edfd54_n.jpg'), 
WindowsPath('C:/Users/Administrator/.keras/datasets/flower_photos/dandelion/7355522_b66e5d3078_m.jpg')]

data_root.glob('*/*')中的*/*为读取子文件夹daisy和dandelion下的所有图片5547758_eea9edfd54_n.jpg、7355522_b66e5d3078_m.jpg

注意若使用 print(all_image_paths[0] )打印

'C:/Users/Administrator/.keras/datasets/flower_photos/daisy/5547758_eea9edfd54_n.jpg'

 

将这段代码改成可读取路径下的所有图片,包括子目录下的图片,并输出:import os # os.environ['CUDA_VISIBLE_DEVICES']='3' import sys import argparse import time import torch import torch.nn as nn import torchvision import torch.backends.cudnn as cudnn import torch.optim import model_small import numpy as np from PIL import Image import glob import time # --- Parse hyper-parameters --- # parser = argparse.ArgumentParser(description='PyTorch implementation of CLIP-LIT (liang. 2023)') # parser.add_argument('-i', '--input', help='directory of input folder', default='./input/') parser.add_argument('-i', '--input', help='directory of input folder', default='./buchonginfrared/') parser.add_argument('-o', '--output', help='directory of output folder', default='./result_buchonginfrared/') parser.add_argument('-c', '--ckpt', help='test ckpt path', default='./pretrained_models/enhancement_model.pth') args = parser.parse_args() # U_net = model_small.UNet_emb_oneBranch_symmetry_noreflect(3,1) U_net = model_small.UNet_emb_oneBranch_symmetry(3,1) state_dict = torch.load(args.ckpt) # create new OrderedDict that does not contain `module.` from collections import OrderedDict new_state_dict = OrderedDict() for k, v in state_dict.items(): name = k[7:] # remove `module.` new_state_dict[name] = v U_net.load_state_dict(new_state_dict) U_net.cuda() #U_net.load_state_dict(torch.load('./pretrained_models/enhancement_model.pth')) def lowlight(image_path): data_lowlight = Image.open(image_path)#.convert("RGB") data_lowlight = (np.asarray(data_lowlight)/255.0) data_lowlight = torch.from_numpy(data_lowlight).float().cuda() data_lowlight = data_lowlight.permute(2,0,1) data_lowlight = data_lowlight.unsqueeze(0) light_map = U_net(data_lowlight) enhanced_image = torch.clamp((data_lowlight / light_map), 0, 1) image_path = args.output+os.path.basename(image_path) image_path = image_path.replace('.jpg','.png') image_path = image_path.replace('.JPG','.png') result_path = image_path if not os.path.exists(image_path.replace('/'+image_path.split("/")[-1],'')): os.makedirs(image_path.replace('/'+image_path.split("/")[-1],'')) torchvision.utils.save_image(enhanced_image, result_path) if __name__ == '__main__': with torch.no_grad(): filePath = args.input file_list = os.listdir(filePath) print(file_list) for file_name in file_list: image=filePath+file_name print(image) lowlight(image)
最新发布
07-28
import csv import glob import os path = "D:\cclog\cclog" class StartUpTimeAnalysis: def init(self,fn): ext = os.path.splitext(fn)[-1].lower() if ext == '.xml': # self.root = etree.parse(fn) self.prepare_xml() else: with open(fn,'r') as fin: self.text = fin.read() # for line in fin: # if '[START UP TIMING]' in line: # # self.text += '\n%s' % line # self.text += line self.prepare_log() def prepare_xml(self): data = {} _app_init_done_delay = self.app_init_done_delay.split(" ")[-4] _graph_init_done_delay = self.graph_init_done_delay.split(" ")[-4] _render_frame_done_delay = self.render_frame_done_delay.split(" ")[-5] data["_app_init_done_delay"] = _app_init_done_delay data["_graph_init_done_delay"] = _graph_init_done_delay data["_render_frame_done_delay"] = _render_frame_done_delay return data def prepare_log(self): raw = self.text self.app_init_done_delay = '\n'.join( [el for el in raw.split('\n') if 'after appInit @' in el]) self.graph_init_done_delay = '\n'.join( [el for el in raw.split('\n') if 'avm graph init done' in el]) self.render_frame_done_delay = '\n'.join([el for el in raw.split('\n') if 'cc_render_renderFrame num:0' in el]) if name == 'main': line = ['index','LOG_FILE_NAME', 'APP_INIT_DONE_DELAY', 'GRAPH_INIT_DONE_DELAY', 'RENDER_FRAME_DONE_DELAY'] resultFilePath = os.path.join(path, "result_cold_start_time.csv") fout = open(resultFilePath, 'w', newline='') book = csv.writer(fout) book.writerow(line) print(os.path.join(path + '/**/VisualApp.localhost.root.log.ERROR*')) app_init_done_delay = [] graph_init_done_delay = [] render_frame_done_delay = [] for file_name in glob.glob(os.path.join(path + '/**/VisualApp.localhost.root.log.ERROR*')): res = {} index = os.path.dirname(file_name).split("\\")[-1] res['INDEX'] = index res['LOG_FILE_NAME'] = "VisualApp.localhost.root.log.ERROR_" + index st = StartUpTimeAnalysis(file_name) data = st.prepare_xml() res.update(data) app_init_done_delay.append(float(res["_app_init_done_delay"])) graph_init_done_delay.append(float(res["_graph_init_done_delay"])) render_frame_done_delay.append(float(res["_render_frame_done_delay"])) values = res.values() book.writerow(values) DA_MAX = ['', "MAX_VALUE", max(app_init_done_delay), max(graph_init_done_delay), max(render_frame_done_delay)] DA_MIN = ['', "MIN_VALUE", min(app_init_done_delay), min(graph_init_done_delay), min(render_frame_done_delay)] DA_AVG = ['', "AVG_VALUE", sum(app_init_done_delay)/len(app_init_done_delay), sum(graph_init_done_delay)/len(graph_init_done_delay), sum(render_frame_done_delay)/len(render_frame_done_delay)] book.writerow(DA_MAX) book.writerow(DA_MIN) book.writerow(DA_AVG) fout.close() 解释一下每行代码的意思
07-15
# 获取指定目录下的所有图片路径12 image_paths = glob.glob(directory + "/*.png") + glob.glob(directory + "/*.jpg") for image_path in image_paths: # 读取图片 image = cv2.imread(image_path) # 将图片转换为灰度图像 gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 解码二维码 barcodes = pyzbar.decode(gray) for barcode in barcodes: # 解码得到的二维码数据转换为UTF-8格式 barcode_data = barcode.data.decode("utf-8") # 获取二维码在图片中的位置 (x, y, w, h) = barcode.rect # 更新字典中二维码对应的图片名为最后一次出现的图片名 qr_code_dict[barcode_data] = (barcode_data, image_path, (x, y)) rospy.loginfo(barcode_data) # 打开或创建文件,并以写入模式打开 with open("/root/picture/openmv/qr_codes.txt", "w") as f: #qr_codes为文件.txt /root/oo/ # 遍历字典中的每个二维码和对应的图片名 for qr_code, image_name in qr_code_dict.items(): #qr_code接收键 image_name接收对应键的值 # 将图片名、二维码信息和坐标写入文件 f.write('{}\t{}\t\n'.format(image_name, qr_code)) # 打开或创建CSV文件,并以写入模式打开 with open("/root/picture/openmv/qr_codes.csv", "w") as csv_file: writer = csv.writer(csv_file) # 写入CSV文件的表头 writer.writerow(["QR Code"]) # 遍历字典中的每个二维码和对应的图片名 for qr_code, image_name in qr_code_dict.items(): # 替换二维码内容中的双引号 qr_code = qr_code.replace('"', '') # 将二维码内容写入CSV文件 writer.writerow([qr_code])
07-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Alocus_

如果我的内容帮助到你,打赏我吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值