import os,os.path def find_file(arg,dirname,files): for i in files: file_path = os.path.join(dirname,f) if os.path.isfile(file_path): print("fand file:%s" % file_path) fpath = r'45112200931' os.walk(fpath,find_file(),())

时间: 2024-02-27 07:58:34 浏览: 17
这是一个 Python 的代码,用于在指定目录下查找指定的文件。代码中定义了一个函数 find_file(),它会遍历指定目录下的所有文件和子目录,如果找到了指定的文件,则会打印出该文件的路径。最后,通过调用 os.walk() 函数来遍历指定目录下的所有文件和子目录,并将结果传递给 find_file() 函数。 不过,这段代码中有一些问题。首先,在 find_file() 函数中,函数参数中的 files 变量应该改为 i,否则会导致变量未定义的错误。其次,在 os.walk() 函数的调用中,第二个参数应该传递一个函数对象,而不是函数的调用结果。最后,如果要查找的文件名是一个变量,应该使用字符串格式化来构造文件路径。下面是修正后的代码: ```python import os def find_file(arg, dirname, files): for f in files: file_path = os.path.join(dirname, f) if os.path.isfile(file_path) and f == arg: print("Found file: %s" % file_path) fpath = r'45112200931' os.walk(fpath, find_file, ('test.txt',)) ``` 这里修正了函数参数中的 files 变量,将其改为 i。同时在 os.walk() 函数的第二个参数中传递了一个函数对象 find_file,而不是它的调用结果。在 find_file() 函数中,通过比较文件名和指定的文件名 arg 来判断是否找到了目标文件。最后,在构造文件路径时使用了字符串格式化,将变量 f 插入到路径字符串中。

相关推荐

修改以下代码使其能够输出模型预测结果: def open_image(self): file_dialog = QFileDialog() file_paths, _ = file_dialog.getOpenFileNames(self, "选择图片", "", "Image Files (*.png *.jpg *.jpeg)") if file_paths: self.display_images(file_paths) def preprocess_images(self, image_paths): data_transform = transforms.Compose([ transforms.CenterCrop(150), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) self.current_image_paths = [] images = [] for image_path in image_paths: image = Image.open(image_path) image = data_transform(image) image = torch.unsqueeze(image, dim=0) images.append(image) self.current_image_paths.append(image_path) return images def predict_images(self): if not self.current_image_paths: return for i, image_path in enumerate(self.current_image_paths): image = self.preprocess_image(image_path) output = self.model(image) predicted_class = self.class_dict[output.argmax().item()] self.result_labels[i].setText(f"Predicted Class: {predicted_class}") self.progress_bar.setValue((i+1)*20) def display_images(self, image_paths): for i, image_path in enumerate(image_paths): image = QImage(image_path) image = image.scaled(300, 300, Qt.KeepAspectRatio) if i == 0: self.image_label_1.setPixmap(QPixmap.fromImage(image)) elif i == 1: self.image_label_2.setPixmap(QPixmap.fromImage(image)) elif i == 2: self.image_label_3.setPixmap(QPixmap.fromImage(image)) elif i == 3: self.image_label_4.setPixmap(QPixmap.fromImage(image)) elif i == 4: self.image_label_5.setPixmap(QPixmap.fromImage(image))

这是对单个文件进行预测“import os import json import torch from PIL import Image from torchvision import transforms import matplotlib.pyplot as plt from model import convnext_tiny as create_model def main(): device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print(f"using {device} device.") num_classes = 5 img_size = 224 data_transform = transforms.Compose( [transforms.Resize(int(img_size * 1.14)), transforms.CenterCrop(img_size), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) # load image img_path = "../tulip.jpg" assert os.path.exists(img_path), "file: '{}' dose not exist.".format(img_path) img = Image.open(img_path) plt.imshow(img) # [N, C, H, W] img = data_transform(img) # expand batch dimension img = torch.unsqueeze(img, dim=0) # read class_indict json_path = './class_indices.json' assert os.path.exists(json_path), "file: '{}' dose not exist.".format(json_path) with open(json_path, "r") as f: class_indict = json.load(f) # create model model = create_model(num_classes=num_classes).to(device) # load model weights model_weight_path = "./weights/best_model.pth" model.load_state_dict(torch.load(model_weight_path, map_location=device)) model.eval() with torch.no_grad(): # predict class output = torch.squeeze(model(img.to(device))).cpu() predict = torch.softmax(output, dim=0) predict_cla = torch.argmax(predict).numpy() print_res = "class: {} prob: {:.3}".format(class_indict[str(predict_cla)], predict[predict_cla].numpy()) plt.title(print_res) for i in range(len(predict)): print("class: {:10} prob: {:.3}".format(class_indict[str(i)], predict[i].numpy())) plt.show() if __name__ == '__main__': main()”,改为对指定文件夹下的左右文件进行预测,并绘制混淆矩阵

from pdb import set_trace as st import os import numpy as np import cv2 import argparse parser = argparse.ArgumentParser('create image pairs') parser.add_argument('--fold_A', dest='fold_A', help='input directory for image A', type=str, default='../dataset/50kshoes_edges') parser.add_argument('--fold_B', dest='fold_B', help='input directory for image B', type=str, default='../dataset/50kshoes_jpg') parser.add_argument('--fold_AB', dest='fold_AB', help='output directory', type=str, default='../dataset/test_AB') parser.add_argument('--num_imgs', dest='num_imgs', help='number of images',type=int, default=1000000) parser.add_argument('--use_AB', dest='use_AB', help='if true: (0001_A, 0001_B) to (0001_AB)',action='store_true') args = parser.parse_args() for arg in vars(args): print('[%s] = ' % arg, getattr(args, arg)) splits = os.listdir(args.fold_A) for sp in splits: img_fold_A = os.path.join(args.fold_A, sp) img_fold_B = os.path.join(args.fold_B, sp) img_list = os.listdir(img_fold_A) if args.use_AB: img_list = [img_path for img_path in img_list if '_A.' in img_path] num_imgs = min(args.num_imgs, len(img_list)) print('split = %s, use %d/%d images' % (sp, num_imgs, len(img_list))) img_fold_AB = os.path.join(args.fold_AB, sp) if not os.path.isdir(img_fold_AB): os.makedirs(img_fold_AB) print('split = %s, number of images = %d' % (sp, num_imgs)) for n in range(num_imgs): name_A = img_list[n] path_A = os.path.join(img_fold_A, name_A) if args.use_AB: name_B = name_A.replace('_A.', '_B.') else: name_B = name_A path_B = os.path.join(img_fold_B, name_B) if os.path.isfile(path_A) and os.path.isfile(path_B): name_AB = name_A if args.use_AB: name_AB = name_AB.replace('_A.', '.') # remove _A path_AB = os.path.join(img_fold_AB, name_AB) im_A = cv2.imread(path_A, cv2.IMREAD_COLOR) im_B = cv2.imread(path_B, cv2.IMREAD_COLOR) im_AB = np.concatenate([im_A, im_B], 1) cv2.imwrite(path_AB, im_AB),解释上述代码,并告诉我怎么设置文件夹格式

以下代码有什么错误,怎么修改: import tensorflow.compat.v1 as tf tf.disable_v2_behavior() from PIL import Image import matplotlib.pyplot as plt import input_data import model import numpy as np import xlsxwriter num_threads = 4 def evaluate_one_image(): workbook = xlsxwriter.Workbook('formatting.xlsx') worksheet = workbook.add_worksheet('My Worksheet') with tf.Graph().as_default(): BATCH_SIZE = 1 N_CLASSES = 4 image = tf.cast(image_array, tf.float32) image = tf.image.per_image_standardization(image) image = tf.reshape(image, [1, 208, 208, 3]) logit = model.cnn_inference(image, BATCH_SIZE, N_CLASSES) logit = tf.nn.softmax(logit) x = tf.placeholder(tf.float32, shape=[208, 208, 3]) logs_train_dir = 'log/' saver = tf.train.Saver() with tf.Session() as sess: print("从指定路径中加载模型...") ckpt = tf.train.get_checkpoint_state(logs_train_dir) if ckpt and ckpt.model_checkpoint_path: global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1] saver.restore(sess, ckpt.model_checkpoint_path) print('模型加载成功, 训练的步数为: %s' % global_step) else: print('模型加载失败,checkpoint文件没找到!') prediction = sess.run(logit, feed_dict={x: image_array}) max_index = np.argmax(prediction) workbook.close() def evaluate_images(test_img): coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for index,img in enumerate(test_img): image = Image.open(img) image = image.resize([208, 208]) image_array = np.array(image) tf.compat.v1.threading.Thread(target=evaluate_one_image, args=(image_array, index)).start() coord.request_stop() coord.join(threads) if __name__ == '__main__': test_dir = 'data/test/' import glob import xlwt test_img = glob.glob(test_dir + '*.jpg') evaluate_images(test_img)

import time import tensorflow.compat.v1 as tf tf.disable_v2_behavior() from tensorflow.examples.tutorials.mnist import input_data import mnist_inference import mnist_train tf.compat.v1.reset_default_graph() EVAL_INTERVAL_SECS = 10 def evaluate(mnist): with tf.Graph().as_default() as g: #定义输入与输出的格式 x = tf.compat.v1.placeholder(tf.float32, [None, mnist_inference.INPUT_NODE], name='x-input') y_ = tf.compat.v1.placeholder(tf.float32, [None, mnist_inference.OUTPUT_NODE], name='y-input') validate_feed = {x: mnist.validation.images, y_: mnist.validation.labels} #直接调用封装好的函数来计算前向传播的结果 y = mnist_inference.inference(x, None) #计算正确率 correcgt_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correcgt_prediction, tf.float32)) #通过变量重命名的方式加载模型 variable_averages = tf.train.ExponentialMovingAverage(0.99) variable_to_restore = variable_averages.variables_to_restore() saver = tf.train.Saver(variable_to_restore) #每隔10秒调用一次计算正确率的过程以检测训练过程中正确率的变化 while True: with tf.compat.v1.Session() as sess: ckpt = tf.train.get_checkpoint_state(minist_train.MODEL_SAVE_PATH) if ckpt and ckpt.model_checkpoint_path: #load the model saver.restore(sess, ckpt.model_checkpoint_path) global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1] accuracy_score = sess.run(accuracy, feed_dict=validate_feed) print("After %s training steps, validation accuracy = %g" % (global_step, accuracy_score)) else: print('No checkpoint file found') return time.sleep(EVAL_INTERVAL_SECS) def main(argv=None): mnist = input_data.read_data_sets(r"D:\Anaconda123\Lib\site-packages\tensorboard\mnist", one_hot=True) evaluate(mnist) if __name__ == '__main__': tf.compat.v1.app.run()对代码进行改进

from pdb import set_trace as st import os import numpy as np import cv2 import argparse parser = argparse.ArgumentParser('create image pairs') parser.add_argument('--fold_A', dest='fold_A', help='input directory for image A', type=str, default='./dataset/blurred') parser.add_argument('--fold_B', dest='fold_B', help='input directory for image B', type=str, default='./dataset/sharp') parser.add_argument('--fold_AB', dest='fold_AB', help='output directory', type=str, default='../dataset/out') parser.add_argument('--num_imgs', dest='num_imgs', help='number of images',type=int, default=1000000) parser.add_argument('--use_AB', dest='use_AB', help='if true: (0001_A, 0001_B) to (0001_AB)',action='store_true') args = parser.parse_args() for arg in vars(args): print('[%s] = ' % arg, getattr(args, arg)) splits = os.listdir(args.fold_A) for sp in splits: img_fold_A = os.path.join(args.fold_A, sp) img_fold_B = os.path.join(args.fold_B, sp) img_list = os.listdir(img_fold_A) if args.use_AB: img_list = [img_path for img_path in img_list if '_A.' in img_path] num_imgs = min(args.num_imgs, len(img_list)) print('split = %s, use %d/%d images' % (sp, num_imgs, len(img_list))) img_fold_AB = os.path.join(args.fold_AB, sp) if not os.path.isdir(img_fold_AB): os.makedirs(img_fold_AB) print('split = %s, number of images = %d' % (sp, num_imgs)) for n in range(num_imgs): name_A = img_list[n] path_A = os.path.join(img_fold_A, name_A) if args.use_AB: name_B = name_A.replace('_A.', '_B.') else: name_B = name_A path_B = os.path.join(img_fold_B, name_B) if os.path.isfile(path_A) and os.path.isfile(path_B): name_AB = name_A if args.use_AB: name_AB = name_AB.replace('_A.', '.') # remove _A path_AB = os.path.join(img_fold_AB, name_AB) im_A = cv2.imread(path_A, cv2.IMREAD_COLOR) im_B = cv2.imread(path_B, cv2.IMREAD_COLOR) im_AB = np.concatenate([im_A, im_B], 1) cv2.imwrite(path_AB, im_AB),运行上述代码,提示错误:NotADirectoryError: [WinError 267] 目录名称无效。: 'D:\Users\Administrator\PycharmProjects\pythonProject\DeblurGAN-master\datasets\blurred\1.jpg'

def unzip_infer_data(src_path,target_path): ''' 解压预测数据集 ''' if(not os.path.isdir(target_path)): z = zipfile.ZipFile(src_path, 'r') z.extractall(path=target_path) z.close() def load_image(img_path): ''' 预测图片预处理 ''' img = Image.open(img_path) if img.mode != 'RGB': img = img.convert('RGB') img = img.resize((224, 224), Image.BILINEAR) img = np.array(img).astype('float32') img = img.transpose((2, 0, 1)) # HWC to CHW img = img/255 # 像素值归一化 return img infer_src_path = '/home/aistudio/data/data55032/archive_test.zip' infer_dst_path = '/home/aistudio/data/archive_test' unzip_infer_data(infer_src_path,infer_dst_path) para_state_dict = paddle.load("MyCNN") model = MyCNN() model.set_state_dict(para_state_dict) #加载模型参数 model.eval() #验证模式 #展示预测图片 infer_path='data/archive_test/alexandrite_6.jpg' img = Image.open(infer_path) plt.imshow(img) #根据数组绘制图像 plt.show() #显示图像 #对预测图片进行预处理 infer_imgs = [] infer_imgs.append(load_image(infer_path)) infer_imgs = np.array(infer_imgs) label_dic = train_parameters['label_dict'] for i in range(len(infer_imgs)): data = infer_imgs[i] dy_x_data = np.array(data).astype('float32') dy_x_data=dy_x_data[np.newaxis,:, : ,:] img = paddle.to_tensor (dy_x_data) out = model(img) lab = np.argmax(out.numpy()) #argmax():返回最大数的索引 print("第{}个样本,被预测为:{},真实标签为:{}".format(i+1,label_dic[str(lab)],infer_path.split('/')[-1].split("_")[0])) print("结束") 以上代码进行DNN预测,根据这段代码写一段续写一段利用这个模型进行宝石预测的GUI界面,其中包含预测结果是否正确的判断功能

把下面的格式改成代码形式,并每行进行一局注释#!/usr/bin/env python # -*- coding: utf-8 -*- import time def read_file(file_path): test_file = open(file_path, "r") test_words = test_file.read() test_file.close() return test_words def save_result(result, file_path): output_file = open(file_path, "w") output_file.write(result) print("Save completed") def count_word(input_str): count_words = input_str.split() count_dict = {} for word in count_words: word = word.lower() if word not in count_dict.keys(): count_dict[word] = 1 else: count_dict[word] += 1 return count_dict def get_min(count_dict): min_count = min(count_dict.values()) min_words = [] for word, count in count_dict.items(): if count == min_count: min_words.append(word) return min_words, min_count def get_localtime(): localtime = time.localtime() return time.strftime("%H:%M:%S", localtime) def convert2str(*args): output_str = "The words and corresponding times:\n" for arg in args: try: if type(arg) == list: tmp_str = " ".join(arg) output_str += tmp_str elif type(arg) == int or type(arg) == str: output_str += " : " output_str += str(arg) except: print("Error, unknown type:", type(arg)) return output_str if __name__ == '__main__': test_words = read_file("test_words.txt") count_result = count_word(test_words) min_words, min_count = get_min(count_result) print("check_time:", get_localtime()) print("check_result:", min_words, min_count) output_str = convert2str(min_words, min_count) save_result(output_str, "test_word_result.txt")

最新推荐

recommend-type

vb仓库管理系统(可执行程序+源码+ 开题报告+ 答辩稿)【VB】.zip

vb仓库管理系统(可执行程序+源码+ 开题报告+ 答辩稿)【VB】
recommend-type

中文翻译Introduction to Linear Algebra, 5th Edition 2.1节

中文翻译Introduction to Linear Algebra, 5th Edition 2.1节 线性代数的核心问题是求解方程组。这些方程都是线性的,即未知数仅与数相乘——我们绝不会 遇见 x 乘以 y。我们的第一个线性方程组较小。接下来你来看看它引申出多远: 两个方程 两个未知数 x − 2y = 1 3x + 2y = 11 (1) 我们一次从一个行开始。第一个方程 x − 2y = 1 得出了 xy 平面的一条直线。由于点 x = 1, y = 0 解 出该方程,因此它在这条直线上。因为 3 − 2 = 1,所以点 x = 3, y = 1 也在这条直线上。若我们选择 x = 101,那我们求出 y = 50。 这条特定直线的斜率是 12,是因为当 x 变化 2 时 y 增加 1。斜率在微积分中很重要,然而这是线 性代数! 图 2.1 将展示第一条直线 x − 2y = 1。此“行图”中的第二条直线来自第二个方程 3x + 2y = 11。你 不能错过两条线的交点 x = 3, y = 1。点 (3, 1) 位于两条线上并且解出两个方程。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

识别MATLAB微分方程求解中的混沌行为:分析非线性方程混沌行为的实用技巧

![matlab求解微分方程](https://img-blog.csdnimg.cn/2021062810300367.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MTQ3OTY3OA==,size_16,color_FFFFFF,t_70) # 1. MATLAB微分方程求解概述 微分方程是描述物理、工程和金融等领域中动态系统的数学模型。MATLAB提供了强大的工具来求解微分方程,包括内置求解器和自定义函数
recommend-type

physon如何做ERP系统

作为一个AI语言模型,我可以给您提供一些基本的建议和思路: 1.明确需求和目标:在开始开发ERP系统之前,需要明确您的业务需求和目标,了解您的业务流程、流程数据、员工角色和权限、财务管理等方面的要求,这样才能更好的设计和开发ERP系统。 2.选择技术框架和开发工具:选择合适的技术框架和开发工具是ERP系统开发的关键。选择一种流行的技术框架和工具可以提高开发效率和质量。 3.设计数据库:ERP系统需要一个功能强大的数据库来存储数据。设计数据库需要考虑数据的完整性、安全性和可扩展性。 4.设计系统架构:系统架构是ERP系统的骨架,需要考虑系统的可扩展性、可维护性和性能。 5.开发和测试:
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

探索MATLAB微分方程求解中的分岔分析:揭示方程动态行为的秘密

![matlab求解微分方程](https://img-blog.csdnimg.cn/2021062810300367.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MTQ3OTY3OA==,size_16,color_FFFFFF,t_70) # 1. MATLAB微分方程求解概述 微分方程在科学、工程和金融等领域有着广泛的应用。MATLAB作为一种强大的数值计算软件,提供了丰富的微分方程求解工具。本章将概述
recommend-type

ic验证工作中如何在平台中加入发数的总数?

在进行IC验证工作时,可以通过以下步骤在平台中加入发数的总数: 1. 打开IC验证工具(如Cadence Virtuoso)并打开对应的设计文件。 2. 在设计文件中选择需要计算发数的部分电路或模块。 3. 在IC验证工具中打开时序分析工具(如Cadence Tempus)。 4. 在时序分析工具中设置好时钟频率、时钟周期等参数。 5. 执行时序分析,生成时序报告。 6. 在时序报告中查找发数统计信息,将其记录下来。 7. 将发数统计信息添加到平台中,以便在之后的仿真或验证中使用。 需要注意的是,发数统计信息可能因为设计文件的不同而有所差异,需要根据实际情况进行调整和计算。
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。