# How can i plot hyperspectral image data with kmeans?

5 views (last 30 days)
Jo on 24 Jul 2021
I'm wondering why the matrix is not suitible for the idx=kmeans(X,k) and I want to plot the result.
Here's the code and the error message.
function kmeans()
clear;
data = double(data);
[fl,s,b] = size(data);
dat = zeros(fl*s,b);%matlab K-means算法要求输入矩阵是一个列向量组成的矩阵，列数为波段数，每一列为fl*s的像元值
for i=1:b
dat(:,i) = reshape(data(:,:,i),fl*s,1);
end
idx = kmeans(dat,2);
x1 = min(dat(:,1)):0.01:max(dat(:,1));
x2 = min(dat(:,2)):0.01:max(dat(:,2));
[x1G,x2G] = meshgrid(x1,x2);
XGrid = [x1G(:),x2G(:)]; % Defines a fine grid on the plot
idx2Region = kmeans(XGrid,3,'MaxIter',1,'Start',C);
end
Error using kmeans
Too many input arguments.
Error in kmeans (line 12)
idx = kmeans(dat,2);
Thanks for help!!!!!!

Sulaymon Eshkabilov on 24 Jul 2021
Remove in your code line 1 and last one, e.g.:
clear;
data = double(data);
...
[x1G,x2G] = meshgrid(x1,x2);
XGrid = [x1G(:),x2G(:)]; % Defines a fine grid on the plot
idx2Region = kmeans(XGrid,3,'MaxIter',1,'Start',C);
Sulaymon Eshkabilov on 24 Jul 2021
Most welcome!

Image Analyst on 24 Jul 2021
See my attached demo for kmeans for hyperspectral images. If you can't figure out how to apply it, attach your images.

Image Analyst on 24 Jul 2021
I'm also attaching a kmeans demo for RGB, and some other kmeans demos in case they might help someone. In general I don't really like kmeans unless you have well separated classes.
Jo on 24 Jul 2021
Thanks for the files! but what i want to do is to use the data and display something like this:
Is it something wrong with the function i used in code?

Image Analyst on 24 Jul 2021
What's wrong is that you called your function kmeans()
function kmeans()
clear;
and there is a built in function called kmeans. Now, in your kmeans() function you call a kmeans function:
idx = kmeans(dat,2);
Now, as you probably know, recursion is allowed in MATLAB. So how is MATLAB supposed to know, when it reaches that line, if it's supposed to recursively call your custom kmeans(), or the built-in kmeans()?
Also what's wrong is that you did not post your data or even a screenshot when you posted originally, meaning that you blew past the posting guidelines. But you can read them here:
Another wrong thing is calling clear as the first thing in a function. Functions have their own workspace so at the very first line there are no variables to even clear, unless you passed in some via the input argument list, and you certainly would NOT want to clear your input variables because you need to use them inside your function.

### Community Treasure Hunt

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

Start Hunting!

Translated by