如何去除彩虹衍射图灰色背景,仅保留彩虹区域?
彩虹衍射图像背景替换方案
问题描述
彩虹衍射图案
我有一张彩虹衍射光栅的CCD图像,希望仅保留可见的彩虹区域,将原灰色背景替换为黑色,是否可行?
我尝试了聚类方法,但仅检测到类似轮廓的颜色区域:
import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans from skimage.io import imread from skimage.util import img_as_float # Read image and convert to float [0,1] img = img_as_float(imread('upscale.jpg')) # Reshape image into N x 3 color pixels pixels = img.reshape(-1, 3) # Number of color clusters (you can adjust this) k = 5 # Run k-means clustering on the colors kmeans = KMeans(n_clusters=k, random_state=0, n_init=3) idx = kmeans.fit_predict(pixels) C = kmeans.cluster_centers_ # Reconstruct clustered image clustered_img = C[idx].reshape(img.shape) # Show original and clustered version fig, axes = plt.subplots(1, 2, figsize=(12, 6)) axes[0].imshow(img) axes[0].set_title('Original Image') axes[0].axis('off') axes[1].imshow(clustered_img) axes[1].set_title(f'Color Clusters (k = {k})') axes[1].axis('off') plt.tight_layout() plt.show()
我期望仅显示黑色背景上的彩虹光斑,该图像是通过衍射光栅拍摄的彩虹CCD图像。
解决方案:基于HSV颜色空间的精准分割
完全可以实现你的需求。KMeans聚类的局限性在于它仅基于颜色相似度归类,无法针对性区分"高饱和度彩色"和"低饱和度灰色"这类特征明确的区域。改用HSV颜色空间的饱和度阈值分割,能更精准地分离彩虹区域与背景。
核心思路
彩虹区域是高饱和度的彩色,背景是低饱和度的灰色——利用这一特征,通过饱和度通道筛选目标区域,直接将背景置为黑色。
代码实现
import numpy as np import matplotlib.pyplot as plt from skimage.io import imread from skimage.color import rgb2hsv from skimage.morphology import opening, disk # 读取图像 img = imread('upscale.jpg') # 转换为HSV颜色空间 hsv_img = rgb2hsv(img) # 提取饱和度通道(范围0-1,值越高颜色越鲜艳) saturation = hsv_img[:, :, 1] # 设置饱和度阈值(可根据图像实际情况微调) threshold = 0.2 # 生成掩码:保留饱和度高于阈值的区域 mask = saturation > threshold # 应用掩码,将背景区域设为黑色 result_img = img.copy() result_img[~mask] = [0, 0, 0] # 可选:形态学开运算去除背景噪点 selem = disk(2) cleaned_mask = opening(mask, selem) cleaned_result = img.copy() cleaned_result[~cleaned_mask] = [0, 0, 0] # 展示结果 fig, axes = plt.subplots(1, 3, figsize=(18, 6)) axes[0].imshow(img) axes[0].set_title('原始图像') axes[0].axis('off') axes[1].imshow(result_img) axes[1].set_title('阈值分割结果') axes[1].axis('off') axes[2].imshow(cleaned_result) axes[2].set_title('去噪后结果') axes[2].axis('off') plt.tight_layout() plt.show()
关键调整点
- 饱和度阈值
threshold:如果背景仍有残留,适当提高阈值;如果彩虹区域被误删,适当降低阈值。 - 形态学操作:
disk(2)的尺寸可根据噪点大小调整,去除背景中的微小彩色杂点。
内容的提问来源于stack exchange,提问作者wosker4yan
相关产品推荐
相关产品推荐

