请显示修改后完整的代码
时间: 2024-10-29 08:16:09 浏览: 7
以下是将降噪处理融入到原有代码中的完整版本:
```python
import numpy as np
import os
from scipy.signal import butter, filtfilt
import matplotlib.pyplot as plt
# 定义文件夹路径
folder_path = r'E:\试验数据(1)\速度\处理后数据集'
# 定义低通滤波器参数
cutoff_freq = 10 # 频率截止值
fs = 100 # 采样频率
filter_order = 2 # 滤波器阶数
def butter_lowpass_filter(data, cutoff, fs, order=filter_order):
nyquist = 0.5 * fs
normal_cutoff = cutoff / nyquist
b, a = butter(order, normal_cutoff, btype='low', analog=False)
filtered_data = filtfilt(b, a, data)
return filtered_data
# 检查文件夹下所有的.DAT文件
for filename in os.listdir(folder_path):
if filename.endswith('.DAT'):
# 构建完整文件路径
file_path = os.path.join(folder_path, filename)
# 读取.DAT文件并进行降噪处理
with open(file_path, 'rb') as f:
raw_data = f.read()
try:
cleaned_data = butter_lowpass_filter(np.frombuffer(raw_data, dtype=np.float64), cutoff_freq, fs)
except Exception as e:
print(f"Error processing file {filename}: {e}")
continue
# 从处理过的数据中提取频域信息
transformed_data = np.fft.fft(cleaned_data)
# 计算幅度谱
amplitude_spectrum = np.abs(transformed_data)
# 绘制幅度谱图形
plt.figure()
plt.plot(amplitude_spectrum)
plt.title(f'Amplitude Spectrum after noise reduction - {filename}')
plt.xlabel('Frequency')
plt.ylabel('Amplitude')
plt.grid(True)
# 在所有文件处理完毕后,显示所有图形
plt.show()
#
阅读全文