Is there a way to extract the gray background from the image and just to keep the rainbow

25 views (last 30 days)
I have the following image produced by a diffraction grating on chip producing diffraction pattern.
Is there a way to extract all the color spots while removing the noise of the background?
What I tried was clustering but I don't think is the tool for this task.
Here are all raw images: https://drive.google.com/drive/folders/1B3K4JZd0QXebFceb09hsIKSUl4zCdyzn?usp=sharing
% Read image
img = imread('rainbow.png');
img = im2double(img);
% Reshape image into N x 3 color pixels
pixels = reshape(img, [], 3);
% Number of color clusters (you can adjust this)
k = 5;
% Run k-means clustering on the colors
[idx, C] = kmeans(pixels, k, 'Distance', 'sqeuclidean', 'Replicates', 3);
% Reconstruct clustered image
clusteredImg = reshape(C(idx,:), size(img));
% Show original and clustered version
figure;
subplot(1,2,1);
imshow(img);
title('Original Image');
subplot(1,2,2);
imshow(clusteredImg);
title(sprintf('Color Clusters (k = %d)', k));

Accepted Answer

Mathieu NOE
Mathieu NOE on 12 Nov 2025 at 15:46
hello
here a quick answer - as I understand you want to extract the rainbow area from the entire picture . You can do a boundary + inpolygon action as shown below :
% Read image
img = imread('rainbow.png');
imgray = rgb2gray(im2double(img));
[m,n] = size(imgray);
figure
imagesc(imgray)
axis square
colorbar('vert')
% image tresholding
ul = max(imgray,[],'all');
ind = find(imgray>0.6*ul);
[y,x] = ind2sub(size(imgray),ind);
% select rainbow boundary
k = boundary(x,y,0.75);
hold on
plot(x(k),y(k),'r')
% keep only "rainbow" portion of image
[X,Y] = meshgrid(1:n,1:m);
[in, on] = inpolygon(X,Y,x(k),y(k));
img_out = NaN(size(imgray));
img_out(in) = imgray(in);
figure
imagesc(img_out)
% colormap( [0 0 0; parula(256)] ); % if you want NaN be displayed in black
colormap( [1 1 1; parula(256)] ); % if you want NaN be displayed in white
axis square
colorbar('vert')

More Answers (0)

Products


Release

R2025a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!