inverting an image in a preexisting code

2 views (last 30 days)
I have a code that was created to analyze white particles on a black background, and I need to alter it to analyze black particles on a white background.
RGB=imread('CW5000.jpg');
s_wavelength=4; ; %use every 4th pixel for the perimeter calculation
I = rgb2gray(RGB);
threshold=.4 %black and white threshold
bw = im2bw(I,threshold);
imshow(bw)
bw = bwareaopen(bw,350);
se = strel('disk',2);
bw = imclose(bw,se);
bw = imfill(bw,'holes');
[B,L] = bwboundaries(bw,'noholes');
imshow(label2rgb(L, @jet, [.5 .5 .5]))
hold on
for k = 1:length(B)
boundary = B{k};
plot(boundary(:,2), boundary(:,1), 'y', 'LineWidth', 1)
end
stats = regionprops(L,'Area','Centroid','MajorAxisLength','MinorAxisLength')
for k = 1:length(B)
boundary = B{k};
A = size(boundary)
boundary2=boundary(s_wavelength:s_wavelength:A(1,1),:);
delta_sq = diff(boundary2).^2;
perimeter = sum(sqrt(sum(delta_sq,2)));
area2 = stats(k).Area;
area=polyarea(boundary2(:,1),boundary2(:,2));
metric = 4*pi*area/perimeter^2;
metric_string=sprintf('%2.2f',metric);
text(boundary(1,2)+0,boundary(1,1)+50,metric_string,'Color','k',...
'FontSize',12,'FontWeight','bold');
%text(boundary(1,2)+40,boundary(1,1)+100,metric_string2,'Color','c',...
%'FontSize',12,'FontWeight','bold');
%text(boundary(1,2)+30,boundary(1,1)+150,metric_string3,'Color','g',...
%'FontSize',12,'FontWeight','bold');
%text(boundary(1,2)+30,boundary(1,1)+200,metric_string4,'Color','k',...
%'FontSize',12,'FontWeight','bold');
end
  3 Comments
Miranda Raven
Miranda Raven on 10 Jan 2018

This is what an image looks like. I am wondering what I should adjust the threshold to in order to get the best results?

Image Analyst
Image Analyst on 10 Jan 2018
First thing should be to do a background correction. You have a lot of lens shading going on there and that will prevent a global threshold from working well. See attached demo.

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 10 Jan 2018
Use tilde:
bw = ~im2bw(I,threshold);
In your existing line, simply put ~ before the call to im2bw().

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!