I am trying to find out mean,kurtosis,skew etc of different connected regions seperately. May I found it using .PixelValue command using following code? or .PixelValue command to be used? Please help me.This is my first work.Please correct my code to find mean.
% Out is my region of interest output image.
[val num]=bwlabel(Out);
STATS=regionprops(val,'All');
for i=1:num
kk=STATS(i);
kk1=kk.PixelList;
% To find mean
[r c]=size(kk1);
ax(i)=r*c;
pp(i)=sum(sum(kk1));
bx(i)=pp(i)/su;
mean=bx(i);
end
If you want to compute the mean of the pixel values of a within connected components of Out, then you want to do as follows (assuming a is a grey-value image):
lab = bwlabel(Out);
stats = regionprops(lab,a,'PixelValues');
and then, for each stats.PixelValues, compute the mean:
m = zeros(size(stats))
for ii = 1:numel(stats);
m(ii) = mean(stats(ii).PixelValues);
end
or more simply:
m = cellfun(#mean,{stats.PixelValues})
Note that regionprops can be called with a second input image, which contains the grey values. The 'PixelValues' property is a list with pixel values for each connected component.
To further simplify the code, you can skip calling bwlabel, and directly pass the binary image to regionprops:
stats = regionprops(Out,a,'PixelValues');
Related
I am working on pedestrian step detection (acceleration). I want to calculate statistical features from my filtered signal. I have already calculated some and now I want to calculate gradient.
My data is of 1x37205 double. I calculated features using for loop with moving window size=2samples and 50% overlap of previous window. Below I am attaching the code I tried to calculate the gradient.
I am not sure if it is the right way to calculate or not? In addition, I am also unable to understand that what is the purpose to use gradient, how it can be useful for step detection and how to work with gradient? Could some one guide me or provide any code help in matlab?
%%Here M is mean and V is variance i already calculated from filtered data
G = zeros(length(window:length(M)), 2);
for i = window:length(M)
temp = gradient(M(i+1-window:i),V(i+1-window:i));
G(i, 1) = temp(2, 1); % "c1"
G(i, 2) = temp(2, 1); % "c2"
end
One of the best features of Matlab is its documentation. If you are unfamiliar on how to get specific function documentation, enter the following in the command line:
doc functionName
Alternatively, for 'brief' documentation that displays in the command line, you can enter:
help functionName
Also see the documentation link here.
Your question is worded poorly, so I will summarize what I understand and answer accordingly:
You have a step detection data (1*37205) double, let us call it stepSignal
stepSignal is position data
You want your window to be 2 steps with 50% overlap. This is the default behavior for the gradient function.
You do not need a "for" loop to achieve your goal. According to the documentation, "gradient" can take one input.
See the code below, and if need be add clarifications to the original question.
%% Assume that stepSignal is already imported into the workspace
velocity = gradient(stepSignal);
One last note, when you give "gradient" two inputs, it automatically assumes the second input is a uniform spacing value.
So I'm trying to understand convolution and the process on making gradients and I wanted to just see the horizontal gradient of the 1x2 operator on an image named I1. When I tried to use this code I only get a black screen so I'm trying to figure out what went wrong here,sans using conv of course. (I'm also going to try out Sobel too, so I'd like some tips on how to get that going.)
I1 = uint8(round(sum(C1,3)/3));
figure,imshow(I1);
Kern =[-1,1];
Omega = zeros([size(I1,1) size(I1,2)]);
for i=1:ROWS
for j=1:COLS
Work = double(I1(i,j)).*Kern;
Omega(i,j) = sum(Work(:));
end
end
figure,imshow(uint8(Omega));
The problem is that you're only using 1 pixel from I1 to multiply by your kernel. Since you're using one value, the end effect is:
a.*[-1 1]
which gives you
[-a a]
When you sum this, obviously you get zero. To fix this, you'll need to use the same number of pixels from I1 as you have elements in your kernel (in this case, 2). This will also mean that you need to adjust your loop indices:
for i=1:ROWS-1 % avoid accessing outside image
for j=1:COLS-1
Work = double(I1(i,j:j+1)).*Kern; % j:j+1 gives us 2 pixels
Omega(i,j) = sum(Work(:));
end
end
You can also condense the two lines inside the loop into one:
Kern = [-1;1]; % make Kern a column vector
...
for i=1:ROWS-1
for j=1:COLS-1
Omega(i,j) = double(I1(i,j:j+1))*Kern; % vector multiplication, not elementwise
end
end
Another thing you might want to try is use imagesc(Omega) instead of imshow. imagesc will scale the values of the image so it's more visible.
My data is x,y co-ordinates in multiple files
a=dir('*.mat')
b={a(:).name}
to load the filenames in a cell array
How do I use a loop to sequentially load one column of data from each file into consecutive rows of a new/separate array......?
I've been doing it individually using e.g.
Load(example1.mat)
A(:,1)=AB(:,1)
Load(example2.mat)
A(:,2)=AB(:,1)
Load(example3.mat)
A(:,3)=AB(:,1)
Obviously very primitive and time consuming!!
My Matlab skills are weak so any advice gratefully received
Cheers
Many thanks again, I'm still figuring out how to read the code but I used it like this;
a=dir('*.mat');
b={a(:).name};
test1=zeros(numel(b),1765);
for k=1:numel(b) S=load(b{k});
I then used the following code to create a PCA cluster plot
test1(k,:)=S.AB(:,2); end [wcoeff,score,latent,tsquared,explained] = pca(test1,... 'VariableWeights','variance');
c3 = wcoeff(:,1:3) coefforth = inv(diag(std(test1)))*wcoeff; I = c3'*c3 cscores = zscore(test1)*coefforth;
figure() plot(score(:,1),score(:,2),'+') xlabel('1st Principal Component') ylabel('2nd Principal Component') –
I was using 'gname' to label the points on the cluster plot but found that the point were simply labelled from 1 to the number of rows in the array.....I was going to ask you about this but I found out simply through trial and error if I used 'gname(b)' this labels the points with the .names listed in b.....
However the clusterplot starts to look very busy/messy once I have labelled quite a few points so now I am wondering is is possible to extract the filenames into a list by dragging round or selecting a few points, I think it is possible as I have read a few related topics.....but any tips/advice around gname or labelled/extracting labels from clusterplots would be greatly appreciated. Apologies again for my formatting I'm still getting used to this website!!!
Here is a way to do it. Hopefully I got what you wanted correctly :)
The code is commented but please ask any questions if something is unclear.
a=dir('*.mat');
b={a(:).name};
%// Initialize the output array. Here SomeNumber depends on the size of your data in AB.
A = zeros(numel(b),SomeNumber);
%// Loop through each 'example.mat' file
for k = 1:numel(b)
%// ===========
%// Here you could do either of the following:
1)
%// Create a name to load with sprintf. It does not require a or b.
NameToLoad = sprintf('example%i.mat',k);
%// Load the data
S = load(NameToLoad);
2)
%// Load directly from b:
S = load(b{k});
%// ===========
%// Now S is a structure containing every variable from the exampleX.mat file.
%// You can access the data using dot notation.
%// Store the data into rows of A
A(k,:) = S.AB(:,1);
end
Hope that is what you meant!
I am trying to find the difference between two images, using Matlab. The classic built in function that Matlab provides for this is because the two images don't have the same dimensions (The objects in the images are the same, but in the second image other objects are introduced).
And i thought i could use SURF Features to accomplish this.
Here's the code:
source = imread('source.png');
target = imread('target.png');
source = rgb2gray(source);
target = rgb2gray(target);
sourcePoints=detectSURFFeatures(source,'MetricThreshold',100.0,'NumOctaves',1,'NumScaleLevels',6);
targetPoints=detectSURFFeatures(target,'MetricThreshold',100.0,'NumOctaves',1,'NumScaleLevels',6);
%figure; imshow(source);
%hold on;
%plot(sourcePoints.selectStrongest(10000));
[sourceFeatures, sourcePoints]=extractFeatures(source,sourcePoints,'SURFSize',64);
[targetFeatures,targetPoints]=extractFeatures(target,targetPoints,'SURFSize',64);
boxPairs = matchFeatures(sourceFeatures, targetFeatures);
matchedSourcePoints = sourcePoints(boxPairs(:, 1), :);
matchedTargetPoints = targetPoints(boxPairs(:, 2), :);
figure;
showMatchedFeatures(source, target, matchedSourcePoints, matchedTargetPoints, 'montage');
display(matchedSourcePoints);
display(matchedTargetPoints);
The problem is that from what i know you have functions that only display matched SURF Points, and i would need to plot on the target image only the points that didn't match with the points in the source image.
The resulting "matchedTargetPoints" and the "targetPoints" variables are arrays of SURFPoints objects, so the find function doesn't work, subtracting or making array operations on them don't work.
I also tried to loop through "targetPoints" and check for every one if the point exists, but the script takes forever, so this also doesn't work.
Does anyone have any idea how this might be accomplished?
Any response is appreciated.
Thank you.
You can get the (x,y) locations of the points stored in an M-by-2 matrix by using the Location property of the SURFPoints object. Then you can get the unmatched points using logical indexing:
targetPointsLoc = targetPoints.Location;
unmatchedIdx = true(size(targetPoitnsLoc, 1), 1);
unmatchedIdx(boxPairs(:, 2)) = false;
unmatchedTargetPoints = targetPointsLoc(unmatchedIdx, :);
Now you can use plot to display the unmatched points.
Out of curiosity, why do you care about the unmatched points?
first of all, I'd like to describe my issue with the kmeans in Matlab.
I select a point via mouse and use it for cluster initialization. This works fine.
After the segmentation of the data, I reshape the data back into proper style, because I need a matrix.
Now I want to select only the cluster of which the user selected the data via mouse.
Therefore I select the index of the mouse-coordinates to select the label, which I want to segmentate. Because of other extra data which is not connected or nearby the relevant data, but also gots the same label.
I want to select only connected-components in a neighbourhood of 8.
So here is my code snippet so far:
flatimg = double(reshape(croppedimg,size(croppedimg,1)*size(croppedimg,2),size(croppedimg,3)));
% kmeans
[idx, clusters] = kmeans(flatimg,2,'start',[seedpoint1(3);seedpoint2(3)]);
% form it back to a matrix
k=reshape(idx,size(croppedimg,1),size(croppedimg,2));
%convert point, which is part of the label I want to linear index
selectedobjectpoint = sub2ind(size(croppedimg),seedpoint1(2),seedpoint1(1));
hgplabel = k(selectedobjectpoint);
idx_object = find(k, hgplabel);
% also tried: idx_object = find(k == hgplabel);
I added a screenshot, which shows the direct output of kmeans:
So my aim is it here to get only the "white" OR the "black" ones.
Help or advice appreciated. If you've got any questions regarding the snippet or the goal, feel free to ask.
Thank you in advance!
I think the FIND command is throwing you off. You want something like:
logicalImage = k == hgplabel;
bwImg = bwlabel(logicalImage);
imagesc(bwImg)
FIND will output the indices where k == hgplabel. You want the matrix of zeros and ones where k takes that value (I think).
If you just want the connected components of that, the output of bwlabel will contain unique integers for each connected component, so imagesc(bwImg == 1) will show just component 1. And you can specify the connectivity