0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

binファイルからデータを10進化してpythonでグラフを作成する

Posted at

import struct
import os
import matplotlib.pyplot as plt

def get_unique_filename(base_name):
"""
Check if a file with the base name already exists, and if so,
generate a unique filename by appending an increasing number.
"""
if not os.path.exists(base_name):
return base_name

base, ext = os.path.splitext(base_name)
counter = 1
while True:
    new_name = f"{base}_{counter}{ext}"
    if not os.path.exists(new_name):
        return new_name
    counter += 1

def bin_to_decimal_array(input_file, output_base_name):
output_file = get_unique_filename(output_base_name)

with open(input_file, 'rb') as bin_file, open(output_file, 'w') as txt_file:
    while True:
        # 2バイトずつ読み取る
        byte_chunk = bin_file.read(2)
        if not byte_chunk:
            break  # ファイルの終わりに達したら終了
        
        # 2バイトをリトルエンディアンとして整数に変換
        number = struct.unpack('<H', byte_chunk)[0]
        
        # 整数値をファイルに書き込み
        txt_file.write(f"{number}\n")

print(f"Data has been written to {output_file}")
return output_file

def plot_data(input_file):
# データの読み込み
with open(input_file, 'r') as f:
data = [int(line.strip()) for line in f]

# 時間の配列を生成 (1msごとに取得されたデータ)
time = range(len(data))

# グラフの作成
plt.figure(figsize=(10, 5))
plt.plot(time, data, marker='o', linestyle='-', color='b')
plt.title('Speed vs Time')
plt.xlabel('Time (ms)')
plt.ylabel('Speed (mm/ms)')
plt.grid(True)
plt.savefig('speed_vs_time.png')  # グラフを画像ファイルとして保存
plt.show()

使用例

output_file = bin_to_decimal_array('Eval_Param.bin', 'Eval_Param_Out.txt')
plot_data(output_file)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?