59 lines
2.2 KiB
Python
59 lines
2.2 KiB
Python
import cv2
|
|
import numpy as np
|
|
import matplotlib.pyplot as plt
|
|
|
|
# 1. 读取图像 (请把 'spectrum.jpg' 替换成你第一张图的文件名)
|
|
img_path = r"C:\Users\peng0\Downloads\DownloadsIMG_0438(1).JPG"
|
|
img = cv2.imread(img_path)
|
|
|
|
if img is None:
|
|
print("找不到图像,请检查路径!")
|
|
else:
|
|
# OpenCV 默认读取是 BGR 格式,转换为 RGB 用于显示
|
|
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
|
|
|
# 2. 转换到 HSV 色彩空间,并提取亮度 (Value) 通道
|
|
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
|
|
v_channel = hsv[:, :, 2] # 亮度通道,0-255
|
|
|
|
# 3. 提取光谱的垂直剖面
|
|
# 因为光带基本水平,我们选取图像中间的一列(或者中间几列求平均)作为剖面
|
|
height, width = v_channel.shape
|
|
mid_col_start = int(width * 0.4)
|
|
mid_col_end = int(width * 0.6)
|
|
|
|
# 对中间这段区域按行求平均,得到一维的亮度分布
|
|
# 这样能减少单列像素的噪点影响
|
|
brightness_profile = np.mean(
|
|
v_channel[:, mid_col_start:mid_col_end], axis=1)
|
|
|
|
# 同时也把 RGB 三个通道的剖面提取出来
|
|
r_profile = np.mean(img_rgb[:, mid_col_start:mid_col_end, 0], axis=1)
|
|
g_profile = np.mean(img_rgb[:, mid_col_start:mid_col_end, 1], axis=1)
|
|
b_profile = np.mean(img_rgb[:, mid_col_start:mid_col_end, 2], axis=1)
|
|
|
|
# 4. 绘图
|
|
plt.figure(figsize=(10, 6))
|
|
|
|
# 画总亮度曲线
|
|
plt.plot(brightness_profile, np.arange(height),
|
|
label='Overall Brightness', color='black', linewidth=2)
|
|
|
|
# 画出 RGB 三条通道的强度,展示不同颜色的分布
|
|
plt.plot(b_profile, np.arange(height),
|
|
label='Blue Channel', color='blue', alpha=0.7)
|
|
plt.plot(g_profile, np.arange(height),
|
|
label='Green Channel', color='green', alpha=0.7)
|
|
plt.plot(r_profile, np.arange(height),
|
|
label='Red Channel', color='red', alpha=0.7)
|
|
|
|
# 5. 图表设置
|
|
plt.gca().invert_yaxis() # 图像坐标系 y 轴是向下的,反转一下与图片对应
|
|
plt.title('Pseudo-Spectrum Analysis of the Captured Image')
|
|
plt.xlabel('Pixel Intensity (0-255)')
|
|
plt.ylabel('Vertical Position (Y-axis)')
|
|
plt.legend()
|
|
plt.grid(True, alpha=0.3)
|
|
|
|
plt.show()
|