
本文介绍如何解析结构不规范的csv文件(含标题行、引号包裹、多余字符等),提取其中15组24×32的红外传感器读数,并批量生成高质量热力图。
本文介绍如何解析结构不规范的csv文件(含标题行、引号包裹、多余字符等),提取其中15组24×32的红外传感器读数,并批量生成高质量热力图。
Arduino采集的IR传感器数据常以非标准格式导出:文件中混有说明性文本(如 "Ambient temperature = ")、每行被双引号包围、数值末尾带冗余逗号和空格——这导致标准 csv.reader 无法直接解析为数值矩阵,astype(float) 会因字符串格式错误而失败。
正确处理的关键在于跳过元数据、手动清洗字符串、逐行分割转换。以下是完整、鲁棒的解决方案:
✅ 步骤一:读取并定位有效数据块
假设每组24行数据连续排列(共15组 × 24行 = 360行),且每组前有1–2行非数据行(如标题、空行)。我们先按行读取全部内容,再通过索引或关键词定位起始位置:
使用 qbo-mileage CLI 及用户凭证,从 Airtable、Outlook 或 Google Calendar 记录生成 QuickBooks Online 里程 CSV 文件。
with open("serial_data.csv", "r", encoding="utf-8") as f:
lines = [line.strip() for line in f.readlines()]
# 示例:若每组数据从第2行开始,每组占24行,则第0组在 lines[2:26],第1组在 lines[26:50],依此类推
n_groups = 15
group_size = 24
all_heatmaps = []
for i in range(n_groups):
start_idx = 2 + i * group_size # 调整此偏移量以匹配实际文件结构
end_idx = start_idx + group_size
group_lines = lines[start_idx:end_idx]✅ 步骤二:清洗与转换为浮点数组
对每组24行,去除引号、首尾空格/逗号,按 ', ' 分割,并转为 float:
cleaned_rows = []
for line in group_lines:
# 去除双引号、换行符、首尾空格及末尾逗号/空格
clean_line = line.strip('" \n,')
if not clean_line:
continue
# 按 ', ' 分割(注意空格),过滤空字符串
str_values = [v.strip() for v in clean_line.split(', ') if v.strip()]
float_row = list(map(float, str_values))
cleaned_rows.append(float_row)
# 验证尺寸:应为24×32
if len(cleaned_rows) == 24 and all(len(r) == 32 for r in cleaned_rows):
arr_24x32 = np.array(cleaned_rows)
all_heatmaps.append(arr_24x32)
else:
raise ValueError(f"Group {i}: expected 24×32, got {len(cleaned_rows)}×{len(cleaned_rows[0]) if cleaned_rows else 0}")✅ 步骤三:批量绘制热力图
使用 matplotlib.pyplot.imshow 绘制每个数组,并添加颜色条、标题等:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(3, 5, figsize=(15, 9)) # 3×5网格展示15个热图
axes = axes.flatten()
for idx, (arr, ax) in enumerate(zip(all_heatmaps, axes)):
im = ax.imshow(arr, cmap='viridis', aspect='auto')
ax.set_title(f'Reading #{idx+1}', fontsize=10)
ax.axis('off') # 可选:隐藏坐标轴
# 添加统一颜色条
cbar = fig.colorbar(im, ax=axes, shrink=0.6, aspect=20, label='Temperature (°C)')
plt.tight_layout()
plt.savefig('ir_sensor_heatmaps.png', dpi=300, bbox_inches='tight')
plt.show()⚠️ 注意事项与优化建议
-
Arduino端改进优先:最根本的解决方式是修改Arduino串口输出逻辑,避免写入非CSV字符。例如:
// 发送纯CSV格式(无引号、无标题、每行32个数字,用逗号分隔) for (int i = 0; i < 24; i++) { for (int j = 0; j < 32; j++) { Serial.print(sensorData[i][j]); if (j < 32-1) Serial.print(","); } Serial.println(); } - 容错增强:生产环境建议加入异常捕获与日志,例如 try...except ValueError 并记录问题行。
- 内存优化:若数据量极大,可逐组处理并保存为 .npy 文件,而非全部载入内存。
- 配色与标注:根据温度范围选择 cmap(如 'plasma' 更适合热成像),并用 plt.text() 标注极值位置。
通过以上三步,你不仅能成功解析“伪CSV”,还能自动化生成15张专业级热力图,为红外热成像分析提供可靠的数据可视化支持。

















