首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用python根据JSON将图像排序到文件夹中

使用python根据JSON将图像排序到文件夹中
EN

Stack Overflow用户
提问于 2022-06-22 04:29:31
回答 1查看 91关注 0票数 1

我有一个图像数据集,我需要转换成Tensorflow格式进行图像分类。dataset JSON元数据格式如下所示:

代码语言:javascript
复制
{
  "0": {
    "image_filepath": "images/0.jpg",
    "anomaly_class": "A"
  },
  "1": {
    "image_filepath": "images/1.jpg",
    "anomaly_class": "B"
  },
  "2": {
    "image_filepath": "images/2.jpg",
    "anomaly_class": "C"
  },
  "3": {
    "image_filepath": "images/3.jpg",
    "anomaly_class": "D"
  },
  "4": {
    "image_filepath": "images/4.jpg",
    "anomaly_class": "E"
  },
  "5": {
    "image_filepath": "images/5.jpg",
    "anomaly_class": "F"
  },
  "6": {
    "image_filepath": "images/6.jpg",
    "anomaly_class": "G"
  },
  "7": {
    "image_filepath": "images/7.jpg",
    "anomaly_class": "H"
  },
  "8": {
    "image_filepath": "images/8.jpg",
    "anomaly_class": "I"
  },
  "9": {
    "image_filepath": "images/9.jpg",
    "anomaly_class": "J"
  },
  "10": {
    "image_filepath": "images/10.jpg",
    "anomaly_class": "K"
  },
  "11": {
    "image_filepath": "images/11.jpg",
    "anomaly_class": "L"
  },
  "12": {
    "image_filepath": "images/12.jpg",
    "anomaly_class": "M"
  },
.
.
.

"1000": {
    "image_filepath": "images/1000.jpg",
    "anomaly_class": "A"
  }
}

我想编写一个Python脚本,它使用键"anomaly_class“的值创建文件夹名,并将图像排序/移动到各自的文件夹中。

有什么帮助吗?

EN

回答 1

Stack Overflow用户

发布于 2022-06-22 05:15:31

这应该是可行的:

代码语言:javascript
复制
import os

json_object = {
  "0": {
    "image_filepath": "images/0.jpg",
    "anomaly_class": "A"
  },
  "1": {
    "image_filepath": "images/1.jpg",
    "anomaly_class": "B"
  },
  "2": {
    "image_filepath": "images/2.jpg",
    "anomaly_class": "C"
  }
}

# Parent Directory path
parent_dir = "D:/PyProject/"

for key in json_object:
    anomaly_class_folder_name = json_object[key]['anomaly_class']
    image_fp = json_object[key]['image_filepath']

    # Strip path from image file
    file_name = os.path.basename(image_fp)

    # Create Folder
    path = os.path.join(parent_dir, anomaly_class_folder_name)
    os.mkdir(path)

    # Move file to target directory
    os.replace(image_fp, path + "/" + file_name)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72709703

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档