% 2NBDG code

% images are first imported into Matlab with 

A = double(imread(location)); % where location is the location of the image on disk

bg = x; % bg is the background level of the image. This value must be emperically obtained and is based on imaging characteristics

A_sig = A - bg > 0; % A_sig contains all signal > background 

% morphologically dilate image to connect disparate areas
se = strel('disk',z); % z is a filter size which will change depending on the magnification of the image
A_sig_open = imdilate(A_sig,se);


stats = regionprops(A_sig_open,'Area','PixelList','PixelIdxList'); % returns all areas of regions above background

npix = n; % minimum number of pixels in a cell (use this as a way to filter out noise)

% use the following code to verify that the detection of cells is adequate
% - will vary with image filtering code above
figure;
imagesc(A_sig_open)
hold all
c = 1; % counter
for i = 1:length(stats)
    if stats(i).Area > npix
        plot(stats(i).PixelList(:,1),stats(i).PixelList(:,2),'rx')
        c = c+1;
    end
end

%% calculate fluorescence per cell
fl = zeros(1,c-1); % create vector to store cell fluorescence
c = 1;
for i = 1:length(stats)
    if stats(i).Area > npix
        fl(1,c) = sum(A(stats(i).PixelIdxList));
        c = c+1;
    end
end