Find the connected component in matlab - matlab

Given a BW image that contains some connected components.
Then, given a single pixel P in the image. How to find which component that contains the pixel P? It is guaranteed that the pixel P is always on the white area in one of the connected components.
Currently, I use CC = bwconncomp(BW) than I iterate each component using 'for' loop. In the each component, I iterate the index pixel. For each pixels, I check whether the value equal to the (index of) pixel P or not. If I find it, I record the number of connected component.
However, it seems it is not efficient for this simple task. Any suggestion for improvement? Thank you very much in advance.

MATLAB provides multiple functions that implement connected-component in different ways.
In your example, I would suggest bwlabel.
http://www.mathworks.com/help/images/ref/bwlabel.html
[L, num] = bwlabel(imgBW) This will perform a full-image connected-component labeling on a black-and-white image.
After calling this function, the label value that pixel P belongs to can be read off the result matrix L, as in label_to_find = L(row, col) index. Simple as that.
To extract a mask image for that label, use logical(L == label_to_find).
If you use different software packages such as OpenCV you will be able to get better performance (efficiency in terms of cutting unnecessary or redundant computation), but in MATLAB the emphasis is on convenience and prototyping speed.

Related

How to calculate Gradient in matlab?

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.

Applying (with as few loops as possible) a function to given elements/voxels (x,y,z) taken from subfields of multiple structs (nifti's) in MATLAB?

I have a dataset of n nifti (.nii) images. Ideally, I'd like to be able to get the value of the same voxel/element from each image, and apply a function to the n data points. I'd like to do this for each voxel/element across the whole image, so that I can reconvert the result back into .nii format.
I've used the Tools for NIfTI and ANALYZE image toolbox to load my images:
data(1)=load_nii('C:\file1.nii');
data(2)=load_nii('C:\file2.nii');
...
data(n)=load_nii('C:\filen.nii');
From which I obtain a struct object with each sub-field containing one loaded nifti. Each of these has a subfield 'img' corresponding to the image data I want to work on. The problem comes from trying to select a given xyz within each img field of data(1) to data(n). As I discovered, it isn't possible to select in this way:
data(:).img(x,y,z)
or
data(1:n).img(x,y,z)
because matlab doesn't support it. The contents of the first brackets have to be scalar for the call to work. The solution from googling around seems to be a loop that creates a temporary variable:
for z = 1:nz
for x = 1:nx
for y = 1:ny
for i=1:n;
points(i)=data(i).img(x,y,z);
end
[p1(x,y,z,:),~,p2(x,y,z)] = fit_data(a,points,b);
end
end
end
which works, but takes too long (several days) for a single set of images given the size of nx, ny, nz (several hundred each).
I've been looking for a solution to speed up the code, which I believe depends on removing those loops by vectorisation, preselecting the img fields (via getfield ?)and concatenating them, and applying something like arrayfun/cellfun/structfun, but i'm frankly a bit lost on how to do it. I can only think of ways to pre-select which themselves require loops, which seems to defeat the purpose of the exercise (though a solution with fewer loops, or fewer nested loops at least, might do it), or fun into the same problem that calls like data(:).img(x,y,z) dont work. googling around again is throwing up ways to select and concatenate fields within a struct, or a given field across multiple structs. But I can't find anything for my problem: select an element from a non-scalar sub-field in a sub-struct of a struct object (with the minimum of loops). Finally I need the output to be in the form of a matrix that the toolbox above can turn back into a nifti.
Any and all suggestions, clues, hints and help greatly appreciated!
You can concatenate images as a 4D array and use linear indexes to speed up calculations:
img = cat(4,data.img);
p1 = zeros(nx,ny,nz,n);
p2 = zeros(nx,ny,nz);
sz = ny*nx*nz;
for k = 1 : sz
points = img(k:sz:end);
[p1(k:sz:end),~,p2(k)] = fit_data(a,points,b);
end

Avoiding for loop with cells and matrixes involved

I am trying to avoid the for loops and I have been reading through all the old posts there are about it but I am not able to solve my problem. I am new in MATLAB, so apologies for my ignorance.
The thing is that I have a 300x2 cell and in each one I have a 128x128x256 matrix. Each one is an image with 128x128 pixels and 256 channels per pixel. In the first column of the 300x2 cell I have my parallel intensity values and in the second one my perpendicular intensity values.
What I want to do is to take every pixel of every image (for each component) and sum the intensity values channel by channel.
The code I have is the following:
Image_par_channels=zeros(128,128,256);
Image_per_channels=zeros(128,128,256);
Image_tot_channels=zeros(128,128,256);
for a=1:128
for b=1:128
for j=1:256
for i=1:numfiles
Image_par_channels(a,b,j)=Image_par_channels(a,b,j)+Image_cell_par_per{i,1}(a,b,j);
Image_per_channels(a,b,j)=Image_per_channels(a,b,j)+Image_cell_par_per{i,2}(a,b,j);
end
Image_tot_channels(a,b,j)=Image_par_channels(a,b,j)+2*G*Image_per_channels(a,b,j);
end
end
end
I think I could speed it up introducing (:,:,j) instead of specifying a and b. But still a for loop. I am trying to use cellfun without any success due to my lack of expertise. Could you please give me a hand?
I would really appreciate it.
Many thanks and have a nice day!
Y
I believe you could do something like
Image_par_channels=zeros(128,128,256);
Image_per_channels=zeros(128,128,256);
Image_tot_channels=zeros(128,128,256);
for i=1:numfiles
Image_par_channels = Image_par_channels + Image_cell_par_per{i,1};
Image_per_channels = Image_per_channels + Image_cell_par_per{i,2};
end
Image_tot_channels = Image_par_channels + 2*G*Image_per_channels;
I haven't work with matlab in a long time, but I seem to recall you can do something like this. g is a constant.
EDIT:
Removed the +=. Incremental assignment is not an operator available in matlab. You should also note that Image_tot_channels can be build directly in the loop, if you don't need the other two variables later.

Apply an operation on a sliding window in Matlab

I have an big image and I have to :
First, apply a function to every possible patch of the image, like a sliding window. This is actually very similar to convolution, which is supported in Matlab, but instead I need to calculate a "key value" (real) on each image patch (let's consider it a black box function). As suggested by the comments, perharps I can use the "blockproc" function
Then, I need to find n smallest key values and their respective positions, but the catch is that I have several overlapping windows with similarly low key values then sorting will preserve all of them in the list, which is undesirable. Instead I want to detect those overlapping windows and keep only the one with the lowest key value. You can say that I want to find not the n smallest key values but only the n local minima (not sure if this analogy is correct though) . I can't give the code because it is too long and complicated (face recognition using eigenfaces with +5 functions)
Step 1: apply nlfilter to the original image:
keyimg = nlfilter(img, windowsize, keyfun);
Step 2: apply im2col to keyimg and sort key values:
colimg = im2col(keyimg, windowsize, 'sliding');
minimg = sort(colimg, 1); % perhaps take only the first `k` rows

How to efficiently loop through matrix elements

I have a matlab script for 8-bit image analysis and I'm trying to enhance objects in the image by subtracting the background with no objects present. What I want to do at a pixel level is:
if B-I>50 then E=I
else E=255-B-I
Where, B is the background, I the image and E my enhanced image. I know I can do this by looping through each element of the image matrix by the following:
diff=imsubtract(B,I);
nrows=1024;
ncols=1360;
for r=1:nrows
for c=1:ncols
if diff(r,c)>50
E=I(r,c);
else
E=255-diff(r,c);
end
end
end
But is this rather slow when going multiple images. I've also tried the follow:
E=255-diff;
E(diff>50)=I;
But receive the following error:
In an assignment A(I) = B, the
number of elements in B and I must
be the same.
Any tips on optimizing this would be greatly apprenticed!
In an assignment A(I) = B, the number of elements in B and I must be
the same.
The reason for this error is that you are trying to assign all the content of I to a subset of E (those pixels where diff>50). You have to specifically tell MATLAB that you want those pixels set to the matching pixels in I.
E(diff>50)=I(diff>50);
Incidentally you should be careful using imsubtract here. For pixels where I has a higher value than B, that will result in zeros (if your values are uint8). It may be okay (not 100% clear if you're looking for the absolute difference or really just where B is larger than I)
What if you use use find()
ind = find(B-I>50)
E(ind) = I(ind)
% And then the ones that are not `B-I>50`
E(~ind) = 255-B(~ind)-I(~ind)
Try this vectorized approach that uses logical indexing. I could not test it out on images though, so would be great if that's taken care of.
Code
diff1=double(imsubtract(B,I));
E = double(I).*(diff1>50) + (255-diff1).*(diff1<=50);
You might be needed to convert the datatype back to unsigned integer formats as used for images.