【python】将json内解码失败的中文修改为英文(‘utf-8‘ codec can‘t decode,labelme标注时文件名未中文)

出现问题的场景:

语义分割数据集,使用labelme工具进行标注,然后标注图片存在中文名,导致json标签文件写入中文图片名,从而解析失败。
在这里插入图片描述
在这里插入图片描述
代码解析json文件时,出现报错:
在这里插入图片描述

python脚本需求:

  1. 将文件名和标签json文件改名为英文;
  2. 将json文件内的"imagePath"修改为英文;
# -*- coding: utf-8 -*-
# @Time : 2023/9/13 11:04
# @Author : CLW
# @FileName: rename_and_reset_json.py
# @Software: PyCharm


'''
算法功能:
指遍历定目录下,将指定格式(main_types)的文件改名,还可以将同名的指定类型(sub_types)的文件一同改名
然后将json文件内的imagePath修改为新文件名

应用场景:
1. labelme标注后,名称含有中文,需要把图片和json一同改为英文
···

'''


import os
import json
'''
####################    输入参数设置(开始)    #################### 
'''
root_dir = r'D:\dataset\乌海君正\液位计zt_ywj_1x\zt_ywj_1x-乌海君正化工'
main_types = ['jpg']
sub_types = ['json']     # 附属格式文件,如果与主要格式文件同名,则可以一同改吗,不需要则为空
rename_front = 'WHJZHG_ywj1x_'  # 改名的前缀
count = 1   # 改名所用的计数
'''
####################    输入参数设置(结束)    #################### 
'''

def Edit_label(jsonfile, new_name):
    # Candidate encodings to try
    encodings = ['utf-8-sig', 'utf-8', 'latin-1']  # Add more if necessary
    print("jsonfile=", jsonfile)

    # Try different encodings until successful
    for encoding in encodings:
        try:
            with open(jsonfile, 'rb') as jf:
                content = jf.read().decode(encoding)
                info = json.loads(content)
                print("encoding=", encoding)
                # Modify the content as needed
                info["imagePath"] = new_name

            with open(jsonfile, 'w', encoding='utf-8') as fw:
                # Write the modified content back to the file using UTF-8 encoding
                json.dump(info, fw, ensure_ascii=False)
            break  # Break the loop if successful
        except UnicodeDecodeError:
            continue  # Try the next encoding if decoding fails

    # Handle case when no encoding works
    else:
        print("Unable to decode JSON file using any of the specified encodings.")




for root, dir, files in os.walk(root_dir):
    for file in files:
        if file.split('.')[-1] in main_types:
            # 主体文件改名
            new_main_filename = rename_front + '_' + str(count) + '.' + file.split('.')[-1]
            print(os.path.join(root, new_main_filename))
            os.rename(os.path.join(root, file), os.path.join(root, new_main_filename))
            # 改json文件
            json_name = file[:-len(file.split('.')[-1])] + 'json'
            new_json_name = new_main_filename[:-len(new_main_filename.split('.')[-1])] + 'json'
            if os.path.exists(os.path.join(root, json_name)):
                Edit_label(os.path.join(root, json_name), new_json_name)
            # 修改附属文件
            for sub_t in sub_types:
                sub_filename = file[:-len(file.split('.')[-1])] + sub_t
                # 如果存在附属文件则修改
                if os.path.exists(os.path.join(root, sub_filename)):
                    new_sub_filename = new_main_filename[:-len(new_main_filename.split('.')[-1])] + sub_t
                    print(os.path.join(root, new_sub_filename))
                    os.rename(os.path.join(root, sub_filename), os.path.join(root, new_sub_filename))
            count += 1


最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-11 16:12:08       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-11 16:12:08       106 阅读
  3. 在Django里面运行非项目文件

    2024-05-11 16:12:08       87 阅读
  4. Python语言-面向对象

    2024-05-11 16:12:08       96 阅读

热门阅读

  1. Python: 日期和时间格式化

    2024-05-11 16:12:08       32 阅读
  2. element-plus 工作经验总结

    2024-05-11 16:12:08       34 阅读
  3. nginx开启目录索引搭建文件服务器

    2024-05-11 16:12:08       37 阅读
  4. openssh升级最新脚本及问题处理

    2024-05-11 16:12:08       25 阅读
  5. VIM_beginner

    2024-05-11 16:12:08       28 阅读
  6. 用python写一个自动生成android开机动画的工具

    2024-05-11 16:12:08       36 阅读
  7. C语言中 #include<>与 include ““的区别

    2024-05-11 16:12:08       34 阅读