使用asammdf修改MF4文件通道数据时如何保持原有结构?
问题描述
我正在使用Python的asammdf模块编辑MF4文件中某一通道的数据并重新保存,但用mdf.append复制旧通道并添加新通道后,生成的新MF4文件结构和原文件不一致,希望保留原文件的结构。
原文件结构:
当前生成的新文件结构(不符合需求):
我的代码如下:
origin_mdf_path = 'c:/files/data/origin.mf4' new_mdf_path = 'c:/files/data/new_mdf.mf4' mdf = MDF(origin_mdf_path) new_mdf = MDF() for m in mdf.iter_channels(): if m.name != 'VideoRawdata_VC0': new_mdf.append(m) else: new_samples = rebuild_samples(m.samples) new_signal = Signal( samples=new_samples, timestamps=m.timestamps, unit=m.unit, name=m.name, conversion=m.conversion, raw=m.raw, master_metadata=m.master_metadata, display_names=m.display_names, attachment=m.attachment, stream_sync=m.stream_sync, invalidation_bits=m.invalidation_bits, source=m.source, encoding=m.encoding, group_index=m.group_index, channel_index=m.channel_index) new_mdf.append(new_signal) new_mdf.save(new_mdf_path)
解决方案
问题出在你新建了空的MDF对象来重新添加通道,这会丢失原文件的组结构、元数据、通道分组等关键信息。正确做法是直接在原MDF对象上修改目标通道,而非重构整个文件:
from asammdf import MDF, Signal origin_mdf_path = 'c:/files/data/origin.mf4' new_mdf_path = 'c:/files/data/new_mdf.mf4' # 加载原MF4文件 mdf = MDF(origin_mdf_path) # 找到目标通道并替换样本数据 target_channel_name = 'VideoRawdata_VC0' for channel in mdf.iter_channels(): if channel.name == target_channel_name: new_samples = rebuild_samples(channel.samples) # 创建新信号,复用原通道所有属性,仅替换样本 new_signal = Signal( samples=new_samples, timestamps=channel.timestamps, unit=channel.unit, name=channel.name, conversion=channel.conversion, raw=channel.raw, master_metadata=channel.master_metadata, display_names=channel.display_names, attachment=channel.attachment, stream_sync=channel.stream_sync, invalidation_bits=channel.invalidation_bits, source=channel.source, encoding=channel.encoding, group_index=channel.group_index, channel_index=channel.channel_index ) # 替换原通道 mdf.replace(new_signal) break # 保存修改后的文件,overwrite参数可按需开启 mdf.save(new_mdf_path, overwrite=True)
关键说明
- 使用
mdf.replace()替换原通道,而非新建MDF对象,能完整保留原文件的组结构、元数据和其他通道配置。 - 找到目标通道后立即
break,避免不必要的循环遍历。 - 保存时
overwrite=True用于覆盖已存在的目标文件,可根据实际需求调整。
内容的提问来源于stack exchange,提问作者hljjj
相关产品推荐
相关产品推荐

