创建一个python代码,可以批量复制标注的json文件到未标注的图片上,并对应图片名称对应命名新的json文件
时间: 2024-04-14 22:26:41 浏览: 16
以下是一个可以实现批量复制标注的 JSON 文件到未标注的图片上,并对应命名新的 JSON 文件的 Python 代码示例:
```python
import os
import json
import shutil
def batch_copy_and_rename_json(source_dir, image_dir, destination_dir):
if not os.path.exists(destination_dir):
os.makedirs(destination_dir)
for file_name in os.listdir(source_dir):
if file_name.endswith('.json'):
json_file = os.path.join(source_dir, file_name)
image_name = file_name[:-5] # 去掉文件扩展名 ".json"
image_file = os.path.join(image_dir, image_name)
if os.path.exists(image_file):
destination_file = os.path.join(destination_dir, f"{image_name}.json")
# 复制图片
shutil.copy(image_file, destination_dir)
# 更新 JSON 文件中的图片路径
with open(json_file, 'r') as f:
data = json.load(f)
data['image_path'] = os.path.join(destination_dir, f"{image_name}.jpg")
with open(destination_file, 'w') as f:
json.dump(data, f, indent=4)
print(f"已复制并重命名 {file_name} 到 {destination_file}")
else:
print(f"未找到与 {file_name} 相对应的图片文件")
print('批量复制和重命名完成!')
# 设置源目录、图片目录和目标目录
source_directory = '/path/to/source/directory' # 替换为实际源目录的路径
image_directory = '/path/to/image/directory' # 替换为实际图片目录的路径
destination_directory = '/path/to/destination/directory' # 替换为实际目标目录的路径
# 执行批量复制和重命名
batch_copy_and_rename_json(source_directory, image_directory, destination_directory)
```
请确保替换代码中的 `source_directory`、`image_directory` 和 `destination_directory` 变量为实际的源目录、图片目录和目标目录的路径。此代码将遍历源目录中的所有 JSON 文件,根据文件名称找到对应的图片文件,并将其复制到目标目录中。同时,代码还会更新 JSON 文件中的图片路径,并将其保存到目标目录中,文件名与对应的图片文件名一致。在复制和重命名完成后,将输出相应的提示消息。
提醒:在运行代码之前,请确保已安装 `shutil` 和 `json` 模块。