本文主要是介绍python-opencv支持中文路径读写系列:查找涉及读写相关代码的文件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
查找涉及python-opencv读写相关代码的文件
做这个工作的目的,主要是想将常见的cv2.imread与cv2.imwrite相关的代码批量替换成对应的cv2.imdecode与cv2.imencode以便于支持中文路径名的图像文件。
查找代码示例
import osdef search_file_code_key(file_path, import_statement, function_calls,
):with open(file_path, 'r', encoding='utf-8') as f:content_list = f.readlines()# print(f"==>> content_list: {content_list}")import_statement_index = -1for i, content in enumerate(content_list):# print(f"==>> content: {content}")# print(f"==>> import_statement: {import_statement}")# 检查是否包含import语句if import_statement in content:# print(f"Found '{import_statement}' in {file_path}")import_statement_index = ibreakif import_statement_index != -1:content_write_list = []# 如果包含import语句,检查是否包含指定的函数调用for func in function_calls:for i, content in enumerate(content_list[import_statement_index:], import_statement_index):# print(f"{file_path}\n")if func in content:# print(f"Found '{func}' in {file_path}")content_write_list.append(f"{func} {i}")if content_write_list:content_write = f"{file_path} {' '.join(content_write_list)}\n"return content_writereturn ""def search_code_key(data_path, import_statement, function_calls,txt_search_result_path
):with open(txt_search_result_path, 'w', encoding='utf-8') as f:# 判断data_path是目录还是文件if os.path.isfile(data_path):# print(f"==>> data_path is a file: {data_path}")content_write = search_file_code_key(data_path, import_statement, function_calls,)if content_write:f.write(content_write)else:# print(f"==>> data_path is a directory: {data_path}")# 遍历指定目录及其所有子目录for root, dirs, files in os.walk(data_path):# print(f"==>> files: {files}")for file in files:if file.endswith('.py'):# if file.startswith('poly'):# 构建完整的文件路径file_path = os.path.join(root, file)# print(f"==>> file_path: {file_path}")# 检查文件内容content_write = search_file_code_key(file_path, import_statement, function_calls,)if content_write:f.write(content_write)# 指定要搜索的目录/文件
data_path = "./test.py"
txt_path = "./test_code_info.txt"# 指定要检查的import语句和函数调用
import_statement = 'import cv2'
function_calls = ['cv2.imread', 'cv2.imwrite']# 调用函数
search_code_key(data_path, import_statement, function_calls, txt_path
)
需要转换的源代码文件示例
import cv2mask_file = "test.png"
binary_mask = cv2.imread(mask_file, cv2.IMREAD_GRAYSCALE)
binary_mask_1 = cv2.imread(mask_file,cv2.IMREAD_GRAYSCALE,
)cv2.imwrite("test_1.png", binary_mask)
cv2.imwrite("test_2.png",binary_mask_1,
)
查找到的相关代码结果示例
./test.py cv2.imread 3 cv2.imread 4 cv2.imwrite 9 cv2.imwrite 10
这篇关于python-opencv支持中文路径读写系列:查找涉及读写相关代码的文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!