inverting an image in a preexisting code
Show older comments
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
Rik
on 10 Jan 2018
You didn't attach the example image. Also, if this already works for white on black, can't you just invert the image with bw=~bw;? (You might have to adjust your threshold to 1-threshold)
Miranda Raven
on 10 Jan 2018
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.
Accepted Answer
More Answers (0)
Categories
Find more on MATLAB in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!