Python實(shí)現(xiàn)常見數(shù)據(jù)格式轉(zhuǎn)換的方法詳解
xml_to_csv
代碼如下:
import os import glob import pandas as pd import xml.etree.ElementTree as ET def xml_to_csv(path): xml_list = [] for xml_file in glob.glob(path + '/*.xml'): tree = ET.parse(xml_file) root = tree.getroot() for member in root.findall('object'): value = (root.find('filename').text, int(root.find('size')[0].text), int(root.find('size')[1].text), member[0].text, int(member[4][0].text), int(member[4][1].text), int(member[4][2].text), int(member[4][3].text) ) xml_list.append(value) column_name = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax'] xml_df = pd.DataFrame(xml_list, columns=column_name) return xml_df def main(): print(os.getcwd()) # 結(jié)果為E:\python_code\crack\models_trainning # ToDo 根據(jù)自己實(shí)際目錄修改 # image_path = os.path.join(os.getcwd(), 'dataset/crack/test') # 根據(jù)自己實(shí)際目錄修改,或者使用下面的路徑 image_path = 'E:/python_code/crack/models_trainning/dataset/crack/test' print(image_path) xml_df = xml_to_csv(image_path) xml_df.to_csv('./dataset/crack/train/crack_test.csv', index=None) # 根據(jù)自己實(shí)際目錄修改 print('Successfully converted xml to csv.') main()
這里需要注意的是,這里的話我們只需要修改路徑,就不需要在終端運(yùn)行(每次需要先去該目錄下)了,對(duì)于不玩linux的同學(xué)比較友好。
print(os.getcwd())
結(jié)果為E:\python_code\crack\models_trainning
image_path = os.path.join(os.getcwd(), 'dataset/crack/test') image_path = 'E:/python_code/crack/models_trainning/dataset/crack/test'
以上兩種圖片路徑方法都可以,一個(gè)采用的是os.path.join()進(jìn)行路徑拼接。
xml_df.to_csv('./dataset/crack/train/crack_test.csv', index=None)
保存為csv的路徑可以隨意寫
結(jié)果如下
csv_to_tfrecord
# -*- coding: utf-8-*- from __future__ import division from __future__ import print_function from __future__ import absolute_import import os import io import pandas as pd import tensorflow as tf import tensorflow.compat.v1 as tf from PIL import Image from research.object_detection.utils import dataset_util from collections import namedtuple, OrderedDict flags = tf.app.flags flags.DEFINE_string('csv_input', '', 'Path to the CSV input') flags.DEFINE_string('output_path', '', 'Path to output TFRecord') FLAGS = flags.FLAGS # 將分類名稱轉(zhuǎn)成ID號(hào) def class_text_to_int(row_label): if row_label == 'crack': return 1 # elif row_label == 'car': # return 2 # elif row_label == 'person': # return 3 # elif row_label == 'kite': # return 4 else: print('NONE: ' + row_label) # None def split(df, group): data = namedtuple('data', ['filename', 'object']) gb = df.groupby(group) return [data(filename, gb.get_group(x)) for filename, x in zip(gb.groups.keys(), gb.groups)] def create_tf_example(group, path): print(os.path.join(path, '{}'.format(group.filename))) with tf.gfile.GFile(os.path.join(path, '{}'.format(group.filename)), 'rb') as fid: encoded_jpg = fid.read() encoded_jpg_io = io.BytesIO(encoded_jpg) image = Image.open(encoded_jpg_io) width, height = image.size filename = (group.filename + '.jpg').encode('utf8') image_format = b'jpg' xmins = [] xmaxs = [] ymins = [] ymaxs = [] classes_text = [] classes = [] for index, row in group.object.iterrows(): xmins.append(row['xmin'] / width) xmaxs.append(row['xmax'] / width) ymins.append(row['ymin'] / height) ymaxs.append(row['ymax'] / height) classes_text.append(row['class'].encode('utf8')) classes.append(class_text_to_int(row['class'])) tf_example = tf.train.Example(features=tf.train.Features(feature={ 'image/height': dataset_util.int64_feature(height), 'image/width': dataset_util.int64_feature(width), 'image/filename': dataset_util.bytes_feature(filename), 'image/source_id': dataset_util.bytes_feature(filename), 'image/encoded': dataset_util.bytes_feature(encoded_jpg), 'image/format': dataset_util.bytes_feature(image_format), 'image/object/bbox/xmin': dataset_util.float_list_feature(xmins), 'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs), 'image/object/bbox/ymin': dataset_util.float_list_feature(ymins), 'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs), 'image/object/class/text': dataset_util.bytes_list_feature(classes_text), 'image/object/class/label': dataset_util.int64_list_feature(classes), })) return tf_example def main(csv_input, output_path, imgPath): writer = tf.python_io.TFRecordWriter(output_path) path = imgPath examples = pd.read_csv(csv_input) grouped = split(examples, 'filename') for group in grouped: tf_example = create_tf_example(group, path) writer.write(tf_example.SerializeToString()) writer.close() print('Successfully created the TFRecords: {}'.format(output_path)) if __name__ == '__main__': # ToDo 修改相應(yīng)目錄 imgPath = r'E:\python_code\crack\models_trainning\dataset\crack\test' output_path = 'dataset/crack/test/crack_test.record' csv_input = 'dataset/crack/test/crack_test.csv' main(csv_input, output_path, imgPath)
如xml_to_csv類似,只要把路徑改好即可
imgPath是圖片所在文件夾路徑
output_path是tfrecord生成的路徑
csv_iinput是使用的csv的路徑
當(dāng)然,你可能會(huì)出現(xiàn)下面報(bào)錯(cuò),起初筆者還以為是編碼問題,可是始終未能解決。后來仔細(xì)檢查發(fā)現(xiàn),是自己路徑搞錯(cuò)了,因此大家出現(xiàn)這個(gè)錯(cuò)誤的時(shí)候,檢查一下路徑先。
到此這篇關(guān)于Python實(shí)現(xiàn)常見數(shù)據(jù)格式轉(zhuǎn)換的方法詳解的文章就介紹到這了,更多相關(guān)Python數(shù)據(jù)格式轉(zhuǎn)換內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python PyCryptodome庫(kù)介紹與實(shí)例教程
PyCryptodome提供了豐富的加密功能,可以滿足多種安全需求,本文介紹了幾個(gè)常見的使用場(chǎng)景,包括對(duì)稱加密、非對(duì)稱加密、哈希函數(shù)和消息認(rèn)證碼,感興趣的朋友跟隨小編一起看看吧2024-07-07動(dòng)態(tài)創(chuàng)建類實(shí)例代碼
Python中要?jiǎng)?chuàng)建一個(gè)類的實(shí)例,要首先導(dǎo)入該類或者該類所屬的模塊。2009-10-10Python使用pyserial進(jìn)行串口通信的實(shí)例
今天小編就為大家分享一篇Python使用pyserial進(jìn)行串口通信的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-07-07Python基于pyopencv人臉識(shí)別并繪制GUI界面
本文詳細(xì)講解了Python基于pyopencv人臉識(shí)別并繪制GUI界面,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-12-12教你用Python代碼實(shí)現(xiàn)合并excel文件
近幾天一直因?yàn)閑xcel文件太多太雜的原因苦惱,今天特地整理了本篇文章,文章介紹的非常詳細(xì),對(duì)正在學(xué)習(xí)python的小伙伴們有很好地幫助,需要的朋友可以參考下2021-05-05Python的10道簡(jiǎn)單測(cè)試題(含答案)
這篇文章主要介紹了Python的10道簡(jiǎn)單測(cè)試題(含答案),學(xué)習(xí)了一段時(shí)間python的小伙伴來做幾道測(cè)試題檢驗(yàn)一下自己的學(xué)習(xí)成果吧2023-04-04