import json
import os
def process_coco_json(json_file, image_folder):
with open(json_file, "r") as f:
data = json.load(f)
# Collect image IDs with annotations
image_ids_with_annotations = set()
for annotation in data["annotations"]:
image_ids_with_annotations.add(annotation["image_id"])
# Filter images with annotations
new_images = [image for image in data["images"] if image["id"] in image_ids_with_annotations]
# Collect empty image filenames
empty_image_filenames = [image["file_name"] for image in data["images"] if image["id"] not in image_ids_with_annotations]
# Update images in the JSON data
data["images"] = new_images
# Save the updated JSON data
with open(json_file, "w") as f:
json.dump(data, f)
# Remove empty images from the image folder
for filename in empty_image_filenames:
file_path = os.path.join(image_folder, filename)
if os.path.exists(file_path):
os.remove(file_path)
def main():
train_json = "train.json"
train_folder = "train"
val_json = "val.json"
val_folder = "val"
process_coco_json(train_json, train_folder)
process_coco_json(val_json, val_folder)
if __name__ == "__main__":
main()
解析train.json和val.json文件,删除json文件中空目标图像的信息,并删除对应文件夹下的空目标图像文件
最新推荐文章于 2023-08-23 14:39:24 发布