90 lines
2.9 KiB
Python
90 lines
2.9 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
Created on Wed Dec 18 15:44:33 2024
|
||
|
||
@author: ieemoo-zl003
|
||
"""
|
||
|
||
import json
|
||
import struct
|
||
import numpy as np
|
||
|
||
json_path = r"D:\DetectTracking\practice\resv11_test.json"
|
||
|
||
def write_binary_file(filename, datas):
|
||
with open(filename, 'wb') as f:
|
||
# 先写入数据中的key数量(为C++读取提供便利)
|
||
key_count = len(datas)
|
||
f.write(struct.pack('I', key_count)) # 'I'代表无符号整型(4字节)
|
||
|
||
feats_32, feats_16 = [], []
|
||
for data in datas:
|
||
key = data['key']
|
||
feats = data['value']
|
||
key_bytes = key.encode('utf-8')
|
||
key_len = len(key)
|
||
length_byte = struct.pack('<B', key_len)
|
||
f.write(length_byte)
|
||
# f.write(struct.pack('Q', len(key_bytes)))
|
||
f.write(key_bytes)
|
||
value_count = len(feats)
|
||
f.write(struct.pack('I', (value_count * 256)))
|
||
# 遍历字典,写入每个key及其对应的浮点数值列表
|
||
for values in feats:
|
||
# 写入每个浮点数值(保留小数点后六位)
|
||
feat16 = []
|
||
for value in values:
|
||
# 使用'f'格式(单精度浮点,4字节),并四舍五入保留六位小数
|
||
value_half = np.float16(value)
|
||
# print(value_half.tobytes())
|
||
f.write(value_half.tobytes())
|
||
|
||
feat16.append(value_half)
|
||
|
||
feats_16.append(feat16)
|
||
feats_32.append(values)
|
||
|
||
feats16 = np.array(feats_16)
|
||
feats32 = np.array(feats_32)
|
||
|
||
|
||
print("Done")
|
||
|
||
|
||
def main_xh():
|
||
|
||
# 1. 打开JSON文件
|
||
with open(json_path, 'r', encoding='utf-8') as file:
|
||
# 2. 读取并解析JSON文件内容
|
||
data = json.load(file)
|
||
|
||
for flag, values in data.items():
|
||
# 逐个写入values中的每个值,保留小数点后六位,每个值占一行
|
||
write_binary_file(r"D:\DetectTracking\practice\data_.bin", values)
|
||
|
||
|
||
|
||
'''
|
||
with open('D://07Test/全实时/output.txt', 'w', encoding='utf-8') as txt_file:
|
||
for flag, values in data.items():
|
||
# 逐个写入values中的每个值,保留小数点后六位,每个值占一行
|
||
for value in values:
|
||
key = value['key']
|
||
feats = value['value']
|
||
# 写入key
|
||
txt_file.write(key)
|
||
txt_file.write("\n")
|
||
for feat in feats:
|
||
for number in feat:
|
||
# 使用格式化字符串保留六位小数,并写入文件
|
||
txt_file.write(f"{number:.6f} ")
|
||
txt_file.write("\n")
|
||
|
||
'''
|
||
def main_wang():
|
||
pass
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main_xh()
|
||
|