Discuz! Board

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 2509|回复: 0

python求光谱峰值和半峰宽

[复制链接]

399

主题

1251

帖子

4020

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
4020
发表于 2023-12-11 09:54:46 | 显示全部楼层 |阅读模式
  1. import os
  2. import numpy as np
  3. import csv

  4. def traverse_folder(folder_path):
  5.     # 遍历文件夹下的所有文件和子文件夹
  6.     data = [["file","peak wavelength(nm)","half width(nm)"]]
  7.     for root, dirs, files in os.walk(folder_path):
  8.         for file in files:
  9.             # 判断文件后缀是否为 .txt
  10.             if file.endswith('.txt'):
  11.                 file_path = os.path.join(root, file)
  12.                 print(file_path)  # 可根据需求进行处理
  13.                 peak,width = find_peak_and_width(file_path)
  14.                 data.append([file_path,peak,width])
  15.       # 指定CSV文件路径
  16.     #print(data)
  17.     file_path = 'data.csv'

  18.     # 打开CSV文件并写入数据
  19.     with open(file_path, mode='w', newline='') as file:
  20.         writer = csv.writer(file)
  21.         writer.writerows(data)
  22.     print("数据已成功存入CSV文件。")        
  23.                
  24. def find_peak_and_width(file_path):
  25.     # 读取光谱文件数据
  26.    # data = np.loadtxt(file_path,dtype=str,usecols = 7)
  27.     data = np.array(read_variable_columns(file_path))
  28.     #print(type(data))
  29.     # 提取光谱曲线的 x 和 y 数据
  30.     x = data[:, 0]
  31.     y = data[:, 1]
  32.     # 使用SciPy的find_peaks函数找到光谱曲线中的峰值
  33.     peaks = np.array([np.argmax(y)])

  34.     # 获取峰值波长和半峰宽
  35.     peak_wavelength = x[peaks[0]]
  36.     half_max_value = y[peaks[0]] / 2
  37.     half_max_left, half_max_right = peak_widths(y, peaks, rel_height=half_max_value)

  38.     # 打印峰值波长和半峰宽
  39.     #print("峰值波长: {:.3f}".format(peak_wavelength))
  40.    # print("半峰宽: {:.3f}".format(x[half_max_right] - x[half_max_left]))
  41.     return peak_wavelength,x[half_max_right] - x[half_max_left]
  42.    

  43. def peak_widths(y, peaks, rel_height):
  44.     i = peaks[0]
  45.     while y[i]>rel_height:
  46.         i=i-1;
  47.     half_max_left = i;
  48.     i = peaks[0]
  49.     while y[i]>rel_height:
  50.         i=i+1;
  51.     half_max_right = i;
  52.     return half_max_left, half_max_right

  53. def read_variable_columns(file_path):
  54.     # 存储每一行的数据
  55.     data = []

  56.     # 打开文件并读取行数据
  57.     with open(file_path, 'r') as file:
  58.         reader = csv.reader(file, delimiter='\t')
  59.         
  60.         for row in reader:
  61.             #print(row)
  62.             data.append(row)
  63.     data = [[float(value) for value in row] for row in data[14:]]
  64.     #print(data)
  65.     return data



  66. traverse_folder('spectrum')
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|DiscuzX

GMT+8, 2025-6-8 13:38 , Processed in 0.035433 second(s), 19 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表