ValueError:Unicode strings with encoding declaration are not supported.

训练神经网络是,需要将标注好的数据转换成tensorflow特定数据,tfrecord。但是在转换时,发生以下错误:ValueError:Unicode strings with encoding declaration are not supported.Please use bytes or XML fragments without declaration.

ValueError:Unicode strings with encoding declaration are not supported.

错误显示不支持的解码格式,以为时标注的xml文件出错了,就把相应的图片和标注文件删除了,发现还是出错。很感谢这篇博客的作者:https://blog.****.net/Fkk921912333/article/details/78537726 ,作者博客“解析 XML 字符串”部分,介绍了相关的xml文件解析方法,最主要的一句:print(etree.tostring(root, pretty_print=True).decode('utf-8'))。对比自己的creat_te_record文件,修改了读取文件时格式,即加入‘utf-8’,改变读取xml文件的编码方式,即可顺利转换数据。因为用的是tensorflow官方给的转换文件,具体语句为将xml = etree.fromstring(xml_str)改为xml = etree.fromstring(xml_str.encode('utf-8'))。可以据此更改自己的文件语句。