MATLAB: How to have automated thresholding to deal with disparities between images

automated thresholding gray levelstitching

Hi,
I have huge sets of images of some dark circles against a background, the darkness of the background can vary. What I am trying to do is load the image, threshold it, convert to B&W, then take centroids of the circles and set a crop rectangle to crop the image based on the average of the centroid positions, then I want to save that cropped image into a cell (or other if there's a better method) and then stitch the cropped images together in the sequence they were saved – e.g. image1 on the far left, image2 adjacent to its right.
So far my code is stumbling at the automated thresholding, I tried Otsu's method and received a similar error:
Index exceeds array bounds.
Error in crop_program_08 (line 14)
pic_testing=(files(k).name)
Code:
close all
clear all
clc
%%Get files
files=dir('/Users/imagexpertinc/Desktop/piccies/*.png');
N=numel(files)
ImageCell = cell(N,1);
%%************************************************************************
image1=imread(files(1).name);
%
for k=1:2
pic_testing=(files(k).name)
image=imread(files(k).name);
%%Show first Image
figure
image1=image;
imshow(image1)
title('1')
level = graythresh(image1)
threshold = 70; % custom threshold value
% image1_bw = image1 > threshold;
image1_bw = imbinarize(image1,level)
[centers,radii] = imfindcircles(image1_bw,[8 15],'ObjectPolarity','dark','Sensitivity',0.85)
figure
imshow(image1_bw)
% h = viscircles(centers,radii);
meanOfcenters=mean(centers(:,1));
MaxRadii=max(radii(:,1));
LimLow=meanOfcenters-(2*MaxRadii);
LimHI=meanOfcenters+(2*MaxRadii);
centersLimits={LimLow, LimHI};
centersLimits=cell2mat(centersLimits);
[HEIGHT,~]=size(image1_bw);
WIDTH=150;
XMIN= meanOfcenters-(WIDTH/2);
YMIN=1;
rect=[XMIN YMIN WIDTH HEIGHT];%where RECT is a 4-element vector with the form [XMIN YMIN WIDTH HEIGHT];
[x,y,I2,rect] = imcrop(image1_bw,rect);
% whos I2;
[CroppedImage] = imcrop(image1,rect);
ImageCell{k}=CroppedImage;
end
AA=ImageCell{:};
ImageCell = cat(2,ImageCell{:}) ;
hFig=figure('units','normalized','outerposition',[0 0 1 1]);
set(0,'CurrentFigure',hFig)
imshow(ImageCell);

Best Answer

Here is a demo that uses automatic multi-level thresholding to isolate the disks:
im_files={'https://www.mathworks.com/matlabcentral/answers/uploaded_files/122855/picture1.png' ...
'https://www.mathworks.com/matlabcentral/answers/uploaded_files/122854/picture2.png'};
figure
for i=1:2
% Get the image
im=imread(im_files{i});
% Partion image into 4 classes
[~,~,LUT,~]=FastFCMeans(im,4);
L=LUT2label(im,LUT);
% Isolate disks
bw=L==1;
bw=bwareaopen(bw,10,8); % remove 8-connected blobs (if any) with fewer than 10 pixels
% Visualize
subtightplot(2,2,2*i-1), imshow(im)
subtightplot(2,2,2*i), imshow(bw)
end
Segmentation functions used in this demo can be downloaded from here
'subtightplot' function can be found here