Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Image Processing

Subject: Image Processing

From: Moey Makki

Date: 11 Nov, 2010 17:21:03

Message: 1 of 25

Hey,

I am a new comer to matlab and i got couple questions to ask and hopefully someone will help.

I got an assessment for uni which is to work on aa image with sweets in.

In the picture there two sweets that are touching and i having difficulty to sperate them into two objects instead of being counted as one object.

My code so far is :

I = imread('image_d.jpg');
 
Gray_IMG = rgb2gray(I);
figure, imshow(Gray_IMG),
 
I3 = max(max(Gray_IMG))-Gray_IMG;
figure, imshow(I3)
 
background = imopen(I3,strel('disk',25));
figure, imshow(background);
 
 
NewBG = imsubtract(I3, background);
figure, imshow(NewBG);
 
 
Adjust_IMG = imadjust(NewBG);
figure, imshow(Adjust_IMG);
 
level = graythresh(Adjust_IMG);
BW_IMG = im2bw(Adjust_IMG,level);
BW_IMG = bwareaopen(BW_IMG, 50);
figure, imshow(BW_IMG);


se = strel('disk',5);

I_DI = imdilate(BW_IMG,se);
figure, imshow(I_DI);

I_R = imerode(I_DI, se);
figure, imshow(I_R);a

Subject: Image Processing

From: Sean

Date: 11 Nov, 2010 17:40:07

Message: 2 of 25

"Moey Makki" <avirex_2@msn.com> wrote in message <ibh8lv$dng$1@fred.mathworks.com>...
> Hey,
>
> I am a new comer to matlab and i got couple questions to ask and hopefully someone will help.
>
> I got an assessment for uni which is to work on aa image with sweets in.
>
> In the picture there two sweets that are touching and i having difficulty to sperate them into two objects instead of being counted as one object.
>
> My code so far is :
>
> I = imread('image_d.jpg');
>
> Gray_IMG = rgb2gray(I);
> figure, imshow(Gray_IMG),
>
> I3 = max(max(Gray_IMG))-Gray_IMG;
> figure, imshow(I3)
>
> background = imopen(I3,strel('disk',25));
> figure, imshow(background);
>
>
> NewBG = imsubtract(I3, background);
> figure, imshow(NewBG);
>
>
> Adjust_IMG = imadjust(NewBG);
> figure, imshow(Adjust_IMG);
>
> level = graythresh(Adjust_IMG);
> BW_IMG = im2bw(Adjust_IMG,level);
> BW_IMG = bwareaopen(BW_IMG, 50);
> figure, imshow(BW_IMG);
>
>
> se = strel('disk',5);
>
> I_DI = imdilate(BW_IMG,se);
> figure, imshow(I_DI);
>
> I_R = imerode(I_DI, se);
> figure, imshow(I_R);a

It's going to be hard for us to give you any recommendations without being able to see your image. Post it on a free image site like yfrog or imageshack.

Without seeing the image, try an erosion followed by a watershed segmentation. Look at:
doc watershed
for details and examples.

Subject: Image Processing

From: ImageAnalyst

Date: 11 Nov, 2010 20:00:12

Message: 3 of 25

Try marker-controlled watershed segmentation:
http://blogs.mathworks.com/steve/2006/06/02/cell-segmentation/

Subject: Image Processing

From: Moey Makki

Date: 11 Nov, 2010 20:12:04

Message: 4 of 25

[IMG]http://i785.photobucket.com/albums/yy137/imoey_photo/building/image_d.jpg[/IMG]

Hi,

thanks for replying!

i have uploaded a picture on photo bucket and the link it on top, hopefully it will work!

Subject: Image Processing

From: Moey Makki

Date: 11 Nov, 2010 20:16:03

Message: 5 of 25

<a href="http://s785.photobucket.com/albums/yy137/imoey_photo/building/?action=view¤t=image_d.jpg" target="_blank"><img src="http://i785.photobucket.com/albums/yy137/imoey_photo/building/image_d.jpg" border="0" alt="Photobucket"></a>

Subject: Image Processing

From: ImageAnalyst

Date: 11 Nov, 2010 20:20:02

Message: 6 of 25

OK, now that I've seen it, you could also use color segmentation if
you didn't want to do thresholding and watershed. It's just an
alternate way - there are always alternate ways to do things. Here
are some color segmentation demos:
http://www.mathworks.com/matlabcentral/fileexchange/authors/31862

Subject: Image Processing

From: Sean

Date: 11 Nov, 2010 20:29:04

Message: 7 of 25

"Moey Makki" <avirex_2@msn.com> wrote in message <ibhimk$plp$1@fred.mathworks.com>...
> [IMG]http://i785.photobucket.com/albums/yy137/imoey_photo/building/image_d.jpg[/IMG]
>
> Hi,
>
> thanks for replying!
>
> i have uploaded a picture on photo bucket and the link it on top, hopefully it will work!

This one liner ought to do it:

%%%
I = imread('sweets.jpg'); %your image

L=imdilate(bwlabel(imerode(bwareaopen(imfill(imclearborder(I(:,:,1)<150),'holes'),200),strel('disk',7))),strel('disk',7));

imshow(label2rgb(L))
%%%

You can now do math etc. on L and it'll "treat" those two objects separately. I'll leave decoding it and figuring our what's going on and the order of operations to you!

Subject: Image Processing

From: Moey Makki

Date: 11 Nov, 2010 20:33:03

Message: 8 of 25

ImageAnalyst <imageanalyst@mailinator.com> wrote in message <0f1a3829-4346-4e5c-9955-f9eadbfeea27@z20g2000pra.googlegroups.com>...
> OK, now that I've seen it, you could also use color segmentation if
> you didn't want to do thresholding and watershed. It's just an
> alternate way - there are always alternate ways to do things. Here
> are some color segmentation demos:
> http://www.mathworks.com/matlabcentral/fileexchange/authors/31862

I have just been looking at the demos and i found that could help called the blobsdemo. i am just in the process of lookign at the m file and trying to understand what tot do!

So much code (>_<) lol

Subject: Image Processing

From: ImageAnalyst

Date: 11 Nov, 2010 20:45:03

Message: 9 of 25

On Nov 11, 3:33 pm, "Moey Makki" <avire...@msn.com> wrote:
> I have just been looking at the demos and i found that could help called the blobsdemo. i am just in the process of lookign at the m file and trying to understand what tot do!
>
> So much code (>_<) lol
---------------------------------------------------------
Yes, blobsdemo can measure your blobs once you've separated them.
It's a little long because it demonstrates a lot and it very verbose.
But it's very verbose to be helpful to you and to make things very
clear and understandable. It's really not bad at all. Just digest it
a few lines at a time and you'll see it's really not as bad as it
looks at first.

Subject: Image Processing

From: Moey Makki

Date: 11 Nov, 2010 22:10:05

Message: 10 of 25

I dont excatly how you mean when you said use "math" to treat the two stuck objects separately.

As in i need to find an algorithm that will separate them?

regards
Moey

Subject: Image Processing

From: Sean

Date: 11 Nov, 2010 22:24:04

Message: 11 of 25

"Moey Makki" <avirex_2@msn.com> wrote in message <ibhpjt$cof$1@fred.mathworks.com>...
> I dont excatly how you mean when you said use "math" to treat the two stuck objects separately.
>
> As in i need to find an algorithm that will separate them?
>
> regards
> Moey

Math would be if you wanted the centroids or areas of each individual object.
That did separate them i.e. one object is completely labelled with it's own number and the other a different one. When you run the IMSHOW command, you'll see that they're different colors. This means MATLAB is seeing them as separated. I eroded the two objects to separate them, then I did the connected components analysis (in this case bwlabel) to label each object as it's own, I then dilated them back to their original size to be as accurate as possible.
If you don't mind that the objects aren't their original size, then skip the dilation.

Subject: Image Processing

From: Moey Makki

Date: 11 Nov, 2010 22:44:04

Message: 12 of 25

Yea the IMSHOW command works excatly as you described.

When i run the
"
cc = bwconncomp(L)

sweetdata= regionprops(cc, 'basic')

sweetdata().Area
"

it gave the NumObjects:8, but they are actually 9.

the whole point of my project is to use morphology to automatically count the number of sweets in the image, and to count the number of sweets of each type.

Then i have to determine the mean area of all the sweets. Then to calculate the price of all the sweets i.e 20 pence for each sweet!

Subject: Image Processing

From: Sean

Date: 11 Nov, 2010 22:55:04

Message: 13 of 25

"Moey Makki" <avirex_2@msn.com> wrote in message <ibhrjk$jps$1@fred.mathworks.com>...
> Yea the IMSHOW command works excatly as you described.
>
> When i run the
> "
> cc = bwconncomp(L)
>
> sweetdata= regionprops(cc, 'basic')
>
> sweetdata().Area
> "
>
> it gave the NumObjects:8, but they are actually 9.
>
> the whole point of my project is to use morphology to automatically count the number of sweets in the image, and to count the number of sweets of each type.
>
> Then i have to determine the mean area of all the sweets. Then to calculate the price of all the sweets i.e 20 pence for each sweet!


numObj = unique(L(:)) - 1; %-1 for background

or do CC on the eroded image, not the dilated one - as I alluded to in my last post.

Subject: Image Processing

From: ImageAnalyst

Date: 11 Nov, 2010 23:32:23

Message: 14 of 25

On Nov 11, 5:10 pm, "Moey Makki" <avire...@msn.com> wrote:
> I dont excatly how you mean when you said use "math" to treat the two stuck objects separately.
>
> As in i need to find an algorithm that will separate them?
>
> regards
> Moey

------------------------------------------------------------
Moey:
I don't see that I said to use "math" to separate them. I don't think
I would have said that unless I were teasing you for not giving us the
information to allow us to help you properly. In fact, both Sean and
I said to use watershed. In fact I gave you a link to Steve's blog
where he gives you all the watershed code to do it. Did you apply
that code to your image? Remember it's your homework assignment (not
mine) so I'm not just going to give you turnkey code. But it should
be a very very easy thing to do - just follow Steve's example.
ImageAnalyst

Subject: Image Processing

From: Moey Makki

Date: 12 Nov, 2010 00:35:05

Message: 15 of 25

hahahaha no, i don't mean for you to do it for me, just wanted guidance because i am very new to Matlab and i am having a melt down because of it hahaha

I clicked on the link where it showed me some demos and i am trying to understand the steps into the different operations....

Subject: Image Processing

From: Moey Makki

Date: 12 Nov, 2010 00:54:04

Message: 16 of 25

I have used:
"
D = -bwdist(~L);
D(~L) = -Inf;
WT = watershed(D);
figure, imshow(label2rgb(WT,'jet','w'))



cc = bwconncomp(WT)

sweetdata= regionprops(cc, 'basic')

sweetdata().Area"

<a href="http://s785.photobucket.com/albums/yy137/imoey_photo/building/?action=view¤t=1.jpg" target="_blank"><img src="http://i785.photobucket.com/albums/yy137/imoey_photo/building/1.jpg" border="0" alt="Photobucket"></a>

With that it gives me 10 NumObjects when the aim is 9. Dose the back ground count as a object?

Subject: Image Processing

From: ImageAnalyst

Date: 12 Nov, 2010 01:21:42

Message: 17 of 25

No the background does not count as a foreground object. Alright, at
least you gave it a try. Here's what I got:
(As usual, BE SURE to fix all the line breaks that will be introduced
by the newsreader!!!!!)


clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
imtool close all; % Close all imtool figures.
clearvars; % Erase all existing variables.
workspace; % Make sure the workspace panel is showing.
fontSize = 20;

% Read in the sweets image.
folder = 'C:\Documents and Settings\user\My Documents\Downloads';
baseFileName = 'image_d.jpg';
fullFileName = fullfile(folder, baseFileName);
rgbImage = imread(fullFileName);
% Get the dimensions of the image. numberOfColorBands should be = 1.
[rows columns numberOfColorBands] = size(rgbImage);
% Display the original color image.
subplot(2, 2, 1);
imshow(rgbImage, []);
title('Original Color Image', 'FontSize', fontSize);
set(gcf, 'Position', get(0,'Screensize')); % Enlarge figure to full
screen.
set(gcf,'name','Demo by ImageAnalyst','numbertitle','off')

grayImage = rgb2gray(rgbImage);
% Display the original gray scale image.
subplot(2, 2, 2);
imshow(grayImage, []);
title('Grayscale Image', 'FontSize', fontSize);

% Binarize the image
level = graythresh(grayImage)
% Threshold
binaryImage = grayImage < (level * 255);
% Get rid of dark vignetting in corner.
binaryImage = imclearborder(binaryImage);
% Make is solid by filling holes.
binaryImage = imfill(binaryImage, 'holes');
% Get rid of small noise.
binaryImage = bwareaopen(binaryImage, 100);

% Display the binary image.
subplot(2, 2, 3);
imshow(binaryImage, []);
title('Binary Image', 'FontSize', fontSize);

% Erode 7 pixels to separate.
erodedImage = imerode(binaryImage, ones(15));
% Display the binary image.
subplot(2, 2, 3);
imshow(erodedImage, []);
title('Binary Image', 'FontSize', fontSize);

% Count the remaining blobs
[labeledImage numberOfBlobs] = bwlabel(erodedImage, 8); % Label
each blob so we can make measurements of it
coloredLabels = label2rgb (labeledImage, 'hsv', 'k', 'shuffle'); %
pseudo random color labels

% Get all the blob properties.
blobMeasurements = regionprops(labeledImage, 'all');

subplot(2, 2, 4);
imagesc(coloredLabels);
caption = sprintf('Pseudo colored labels, from label2rgb().\nBlobs are
numbered from top to bottom, then from left to right.');
title(caption);

% Loop over all blobs printing their measurements to the command
window.
labelShiftX = -7; % Used to align the labels in the centers of the
blobs.
fontSize = 12;
fprintf(1,'# Area X Y\n');
for k = 1 : numberOfBlobs % Loop through all blobs.
blobArea = blobMeasurements(k).Area; % Get area.
blobCentroid = blobMeasurements(k).Centroid; % Get centroid.
    fprintf(1,'#%2d %17.1f %11.1f %11.1f\n', k, blobArea,
blobCentroid);
% Put the "blob number" labels on the "boundaries" grayscale image.
subplot(2, 2, 2);
text(blobCentroid(1) + labelShiftX, blobCentroid(2), num2str(k),...
'FontSize', fontSize, 'FontWeight', 'Bold', 'Color', 'y');
subplot(2, 2, 4);
text(blobCentroid(1) + labelShiftX, blobCentroid(2), num2str(k),...
'FontSize', fontSize, 'FontWeight', 'Bold', 'Color', 'y');
end

message = sprintf('There are %d sweets.\nLook in the command window
for the areas.', numberOfBlobs);
uiwait(msgbox(message));

Subject: Image Processing

From: Moey Makki

Date: 12 Nov, 2010 01:45:40

Message: 18 of 25

I have adjusted the code and it works perfectly, now that i know the process i am going to look at it very carefully and apply it to my other images..

I am very grateful for the help i got here !!

(^,^)

I will keep you posted on my final out come of all the images!

Regards
Moey

Subject: Image Processing

From: Moey Makki

Date: 12 Nov, 2010 16:28:05

Message: 19 of 25

One more question...

Now that i have the are for the sweets, can i use an if statement to make matlab remember a particular sweet's price? As in if the area of a certain sweet is above a certain number, the sweet is this price?

Regards
Moey

Subject: Image Processing

From: Sean

Date: 12 Nov, 2010 16:39:04

Message: 20 of 25

"Moey Makki" <avirex_2@msn.com> wrote in message <ibjpuk$199$1@fred.mathworks.com>...
> One more question...
>
> Now that i have the are for the sweets, can i use an if statement to make matlab remember a particular sweet's price? As in if the area of a certain sweet is above a certain number, the sweet is this price?
>
> Regards
> Moey

of course.

Have a matrix of areas and prices; something like an nx3:
[amin amax price]
[0 20 0.03;
 21 40 0.10;
 41 75 0.15];
etc.

Then find where it falls in that table (greater than or equal to column 1 and less than or equal to column 2) yields that price.

Subject: Image Processing

From: Moey Makki

Date: 12 Nov, 2010 22:38:04

Message: 21 of 25

I tried to crack doing it a matrix but i gave up lol

i have devised a plan which includes "

priceCal = blobArea;
if (priceCal <= 1832)
    Sweet1Price = 20
    elseif (priceCal <= 1593)
    Sweet2Price = 20
    elseif (priceCal <= 1336)
    Sweet3Price = 5
end "

To just show the prices at the command window at the end but all i get is just the price for sweet 1 and nothing comes up for sweet 2 and 3...

Subject: Image Processing

From: ImageAnalyst

Date: 12 Nov, 2010 23:41:00

Message: 22 of 25

Make sure it's inside the loop over all blobs. Then use the
debugger! Step through line by line to see what all the variables
are. And, have an else block. You have no else block so if some
priceCal is >= 1832, you're not going to do anything. If you're in a
loop, probably most of your areas fall into that >= 1832 category and
hence nothing gets sent to the command window for them - only the one
blob <= 1832 gets printed.

Finally, and MOST IMPORTANT, look at your if blocks. Tell me which of
those if's is a priceCal of 1000 supposed to fall into? See what I
mean. You need to start with the smallest at the top and go down from
there increasing the areas in order. Otherwise small areas always get
caught by the first "if" and never go into the other ones.

Subject: Image Processing

From: Moey Makki

Date: 13 Nov, 2010 00:49:04

Message: 23 of 25

I took onboard what you said and i tried to understand , so this is what i got ouy.
Result:


Sweet # Area Centroid
# 1 1832.0 205.8 192.5

SweetPrice =
    20

# 2 1336.0 291.9 188.1

SweetPrice =
     5

# 3 1593.0 349.7 183.8

SweetPrice =

    20

>>



Code:

fontSize = 15;
fprintf(1,'Sweet # Area Centroid\n');
for k = 1 : numberOfBlobs % Loop through all blobs.
blobArea = blobMeasurements(k).Area; % Get area.
blobCentroid = blobMeasurements(k).Centroid; % Get centroid.
    fprintf(1,'#%2d %17.1f %11.1f %11.1f\n', k, blobArea, blobCentroid);

    % Put the "blob number" labels on the "boundaries" grayscale image.
subplot(2, 2, 2);
text(blobCentroid(1) + labelShiftX, blobCentroid(2), num2str(k),...
'FontSize', fontSize, 'FontWeight', 'Bold', 'Color', 'y');
subplot(2, 2, 4);
text(blobCentroid(1) + labelShiftX, blobCentroid(2), num2str(k),...
'FontSize', fontSize, 'FontWeight', 'Bold', 'Color', 'y');

priceCal = blobArea;
if (priceCal >= 1832)
    SweetPrice = 20
    
elseif (priceCal >= 1593)
    SweetPrice = 20

else
    SweetPrice = 5
end


end

Subject: Image Processing

From: ImageAnalyst

Date: 13 Nov, 2010 02:11:40

Message: 24 of 25

On Nov 12, 7:49 pm, "Moey Makki" <avire...@msn.com> wrote:
> priceCal = blobArea;
> if (priceCal >= 1832)
>     SweetPrice = 20
>
> elseif (priceCal >= 1593)
>     SweetPrice = 20
>
> else
>     SweetPrice = 5
> end
----------------------------------------------
You can of course drop the first if since the price will be 20 if the
area >= 1593. No need to check for if it's >= 1832 since the price
will be the same (20).

Subject: Image Processing

From: Moey Makki

Date: 13 Nov, 2010 02:20:04

Message: 25 of 25

Yea as soon as i posted the code here i figured out i can take the else if out coz the two sweets have the same price.

Thank you soooo mucch for your help, i think this about ticks all the boxes for the assessment, and now i have to apply the code for the remanning images...

i am soo happy right now u wont believe it if i told you...i was having a very hard time with matlab.

Regards
Moey

Tags for this Thread

No tags are associated with this thread.

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us