Compution of particle size distribution by matlab img processing - matlab

I need to calculate the perimeter of some micro sized particles which are in a photo I captured.
First I Processed the image and now I want to work on 2D processed image which the particles are white and background is black as you know.
So I need some methods & codes to calculate the perimeter & diameter of particles in pixel unit. any suggestions?!
Thanks in advance

The following code might help you understand -
%%// Input image
BW = imread('text.png'); %%// Available in the MATLAB image library
figure,imshow(BW)
%%// Get the scalar distances around the boundaries of the regions/blobs
P = regionprops(BW, 'Perimeter');
%%// Get scalar values that specifies the diameter of a circle with the same
%%// area as the regions/blobs
D = regionprops(BW, 'EquivDiameter');
%%// Get list of pixels based on their labeling.
%%// Basically the indices of the structs produced by regionprops refer to the labels.
pixel_list = regionprops(BW, 'PixelIdxList');
%%// Let us find out information about the first blob (blob that is labeled as 1)
%%// 1. List of pixel coordinates as linear indices
blob1_pixel_list = pixel_list(1).PixelIdxList;
%%// Create an image of the same size as the original one and showing the
%%blob labeled as 1
blob1 = false(size(BW));
blob1(blob1_pixel_list) = true;
figure,imshow(blob1)
%%// Perimter of blob -1
blob1_perimeter = P(1).Perimeter
%%// Equivalent diameter of blob -1
blob1_equivdiameter_values = D(1).EquivDiameter
%%// Get perimeter and diameter values for all the blobs
perimeter_values = struct2array(P)
diameter_values = struct2array(D)

Related

Calculate the pixel distance to three defined pixel in matlab

I want to classify pixels of one tiff image according to pixel's RGB colour. The input is an image and three predefined colours for water(r0,g0,b0), forest(r1,g1,b1) and building(r2,g2,c2). The classification is based on the distance between image pixel and these three colors. If a pixel is closet to the water, the pixel is water and changed it the water RGB. The distance is calculated as (one sample) sqrt((x-r0)^2+(y-g0)^2+(z0-b0)^2)
The sample implementation is:
a=imread(..);
[row col dim] = size(a); % dim =3
for i=1:row
for j=1:col
dis1=sqrtCal(a(i,j,:)-water)
dis2=sqrtCal(a(i,j,:)-forest)
dis3=sqrtCal(a(i,j,:)-build)
a(i,j,:) = water;
if dis2< dis1
dis1 = dis2
a(i,j,:) = forest
end
dis3=sqrt(a(i,j,:)-build)
if dis3<dis1
a(i,j,:) = build
end
end
end
This implementation should work. The problem is that the two for loops is not a good choice.
So is there any good alternatives in the Matlab? The
D = pdist(X,distance)
Seems not appliable for my case.
I think this does what you want. The number of reference colors is arbitrary (3 in your example). Each reference color is defined as a row of the matrix ref_colors. Let MxN denote the number of pixels in the original image. Thus the original image is an MxNx3 array.
result_index is an MxN array which for each original pixel contains the index of the closest reference color.
result is a MxNx3 array in which each pixel has been assigned the RBG values of the closest reference color.
im = rand(10,12,3); %// example image
ref_colors = [ .1 .1 .8; ... %// water
.3 .9 .2; ... %// forest
.6 .6 .6 ]; %// build: example reference colors
dist = sum(bsxfun(#minus, im, permute(ref_colors, [3 4 2 1])).^2, 3);
%// 4D array containing the distance from each pixel to each reference color.
%// Dimensions are: 1st: pixel row, 2nd: pixel col, 3rd: not used,
%// 4th: index of reference color
[~, result_index] = min(dist, [], 4); %// compute arg min along 4th dimension
result = reshape(ref_colors(result_index,:), size(im,1), size(im,2), 3);
This one is another bsxfun based solution, but stays in 3D and could be more efficient -
%// Concatenate water, forest, build as a 2D array for easy processing
wfb = cat(2,water(:),forest(:),build(:))
%// Calculate square root of squared distances & indices corresponding to min vals
[~,idx] = min(sum(bsxfun(#minus,reshape(a,[],3),permute(wfb,[3 1 2])).^2,2),[],3)
%// Get the output with the minimum from the set of water, forest & build
a_out = reshape(wfb(:,idx).',size(a))
If you have the statistics toolbox installed, you can use this version based on knnsearch, that scales well for a large number of colors.
result_index = knnsearch(ref_colors, reshape(im,[],3));
result = reshape(ref_colors(result_index,:), size(im));

How to calculate radius of ring in MATLAB?

I have a stack of cortical bone images, high resolution and binarized. How do I go about calculating the mean inner and outer radii for each image? Here is an example of the kind of images I need to process:
This could be one approach -
%// Read in image and conert to binary
im = im2bw(imread('http://s9.postimg.org/aew1l7tvz/4_COPY_copy.png'));
figure, imshow(im), title('Original Image')
%// Fill holes giving us the "outer blob"
outer_blob = imfill(im,'holes');
outer_blob = biggest_blob(outer_blob); %// remove noise
figure, imshow(outer_blob), title('Outer Blob')
%// Get the inner filled blob by "removing" the original image from outer blob
inner_blob = outer_blob & ~im;
inner_blob = biggest_blob(inner_blob); %// remove noise
figure, imshow(inner_blob), title('Inner Blob')
%// Find the equivalent/mean inner and outer radii
inner_dia = regionprops(inner_blob,'Equivdiameter');
inner_radius = inner_dia.EquivDiameter/2
outer_dia = regionprops(outer_blob,'Equivdiameter');
outer_radius = outer_dia.EquivDiameter/2
Associated function code -
function out = biggest_blob(BW)
%// Find and labels blobs in the binary image BW
[L, num] = bwlabel(BW, 8);
%// Count of pixels in each blob, basically this should give the area of each blob
counts = sum(bsxfun(#eq,L(:),1:num));
%// Get the label(ind) cooresponding to blob with the maximum area
%// which would be the biggest blob
[~,ind] = max(counts);
%// Get only the logical mask of the biggest blob by comparing all labels
%// to the label(ind) of the biggest blob
out = (L==ind);
return;
Code run and debug images -
inner_radius =
211.4740
outer_radius =
267.8926

Getting whole line by combining its parts

I have an image and my aim is to get whole line which is shown with red line. I am working with matlab and I don't want to use IM2 = imdilate(IM,SE) function.
Is there any function or method to do that?
The image:
Note: Sorry for bad red line. I drew it with paint.
Edit:
The original image is below:
Here's what I have after using imdilate at an intermediate step -
%// Read in image and convert to a binary one
im = imread('Line.jpg');
bw = im2bw(im);
%// There seems to be a thin white boundary across the image, make it false(black)
bw1 = false(size(bw));
bw1(5:end-5,5:end-5) = bw(5:end-5,5:end-5);
bw1(biggest_blob(bw1)) = 0; %// remove biggest blob (bottom left corner one)
SE = strel('disk', 11, 8); %// structuring element for dilation
bw2 = imdilate(bw1,SE); %// dilate the image
bw3 = bwmorph(bw2,'thin',Inf); %// thin it
out = biggest_blob(bw3); %// out of many thinned lines, select the biggest one
Please remember that the motive behind removing the biggest blob at the start of the codes is that without that being removed, we would have gotten the biggest blob being attached to the island blobs that we were trying to connect/combine and thus would have messed up the desired output.
Associated function (taken from Select largest object in an image) -
function out = biggest_blob(BW)
%// Find and labels blobs in the binary image BW
[L, num] = bwlabel(BW, 8);
%// Count of pixels in each blob, basically this should give the area of each blob
counts = sum(bsxfun(#eq,L(:),1:num));
%// Get the label(ind) cooresponding to blob with the maximum area
%// which would be the biggest blob
[~,ind] = max(counts);
%// Get only the logical mask of the biggest blob by comparing all labels
%// to the label(ind) of the biggest blob
out = (L==ind);
return;
Result -

Get outer indecies of a region in a logical image

If I've any m x n logical image of a white region like the following:
How to get the indices of the boundary line between the white and black regions?
This simply comes down to detecting the edges of the given image. MATLAB already has a built-in implementation for that in the edge command. Here's an example of detecting the boundaries of an image I using the Canny filter:
A = edge(I, 'canny');
The non-zero elements in the resulting image A are what you're after. You can then use find to obtain their indices.
Since your input is a clear binary image, there is no need to use edge as suggested by #EitanT.
Getting the perimeter using morphological operations imdilate, imerode and regionprops:
% let input image be bw
we = bw & ~imerode( bw, strel('disk', 1) ); % get a binary image with only the boundary pixels set
st = regionprops(we, 'PixelIdxList'); % get the linear indices of the boundary
% get a binary image with pixels on the outer side of the shape set
be = ~bw & imdilate( bw, strel('disk', 1) );
st = regionprops(be, 'PixelList'); % get the row-col indices of the boundary

remove the holes in an image by average values of surrounding pixels

can any one please help me in filling these black holes by values taken from neighboring non-zero pixels.
thanks
One nice way to do this is to is to solve the linear heat equation. What you do is fix the "temperature" (intensity) of the pixels in the good area and let the heat flow into the bad pixels. A passable, but somewhat slow, was to do this is repeatedly average the image then set the good pixels back to their original value with newImage(~badPixels) = myData(~badPixels);.
I do the following steps:
Find the bad pixels where the image is zero, then dilate to be sure we get everything
Apply a big blur to get us started faster
Average the image, then set the good pixels back to their original
Repeat step 3
Display
You could repeat averaging until the image stops changing, and you could use a smaller averaging kernel for higher precision---but this gives good results:
The code is as follows:
numIterations = 30;
avgPrecisionSize = 16; % smaller is better, but takes longer
% Read in the image grayscale:
originalImage = double(rgb2gray(imread('c:\temp\testimage.jpg')));
% get the bad pixels where = 0 and dilate to make sure they get everything:
badPixels = (originalImage == 0);
badPixels = imdilate(badPixels, ones(12));
%# Create a big gaussian and an averaging kernel to use:
G = fspecial('gaussian',[1 1]*100,50);
H = fspecial('average', [1,1]*avgPrecisionSize);
%# User a big filter to get started:
newImage = imfilter(originalImage,G,'same');
newImage(~badPixels) = originalImage(~badPixels);
% Now average to
for count = 1:numIterations
newImage = imfilter(newImage, H, 'same');
newImage(~badPixels) = originalImage(~badPixels);
end
%% Plot the results
figure(123);
clf;
% Display the mask:
subplot(1,2,1);
imagesc(badPixels);
axis image
title('Region Of the Bad Pixels');
% Display the result:
subplot(1,2,2);
imagesc(newImage);
axis image
set(gca,'clim', [0 255])
title('Infilled Image');
colormap gray
But you can get a similar solution using roifill from the image processing toolbox like so:
newImage2 = roifill(originalImage, badPixels);
figure(44);
clf;
imagesc(newImage2);
colormap gray
notice I'm using the same badPixels defined from before.
There is a file on Matlab file exchange, - inpaint_nans that does exactly what you want. The author explains why and in which cases it is better than Delaunay triangulation.
To fill one black area, do the following:
1) Identify a sub-region containing the black area, the smaller the better. The best case is just the boundary points of the black hole.
2) Create a Delaunay triangulation of the non-black points in inside the sub-region by:
tri = DelaunayTri(x,y); %# x, y (column vectors) are coordinates of the non-black points.
3) Determine the black points in which Delaunay triangle by:
[t, bc] = pointLocation(tri, [x_b, y_b]); %# x_b, y_b (column vectors) are coordinates of the black points
tri = tri(t,:);
4) Interpolate:
v_b = sum(v(tri).*bc,2); %# v contains the pixel values at the non-black points, and v_b are the interpolated values at the black points.