Blockproc not working as I expected
Mostra commenti meno recenti
Hello, I am having problems with blockproc.
I have an black image with white spots that I want to basic threshold locally rather than globally - that is to perform a basic threshold on tiles.

IM=double(getimage(handles.axes4)); [rows,cols]=size(IM); %Get image from axes component
IM=IM-min(IM(:)); %Background subtract
% Number of tiles or chunks you want it divide up into.
xtiles =4; ytiles= 4;
%Numbers pixels per tile to maintain integer number of tiles
nx=floor(cols/xtiles); ny=floor(rows/ytiles);
Call my "LocallythresholdImage" function to define a level for binarising the image where
level = average + 2* standard deviations of the image
centroids=LocallythresholdImage(IM,nx,ny,f) %f=2 i.e. number of standard deviatins above the average
function centroids=LocallythresholdImage(IM,m,n,f)
%Uses the thresh function below and then creates a binary image using local
%threshold of size mxn. I
IM=double(IM); %make sure its a double
%Use blockproc uses my "thresh" function
myfun = @(block_struct) thresh3(block_struct.data,f); % myfun = @(block_struct) thresh2(block_struct.data,f);
%I2 = blockproc(Orig,[200 200],myfun,'BorderSize', [3 3], 'TrimBorder', true);
centroids = blockproc(IM,[m n],myfun,'BorderSize', [3 3], 'TrimBorder', true);
function [centroids]=thresh3(IM,f)
%n=str2num(get(handles.editThreshn,'String'));
%Thresholds image based on mean and S.D.
image=double(IM)-min(IM(:));
threshold=mean(image(:)) + f*std(image(:));
lessThanThreshold = image < threshold;
imageThresholded = image;
imageThresholded(lessThanThreshold) = 0;
regmax = imregionalmax(imageThresholded);
s = regionprops(regmax,double(image), 'WeightedCentroid');
format bank
centroids = cat(1, s.WeightedCentroid);
for each tile, the centroids are calculated correctly, but in my top level function "centroid=LocallythresholdImage(IM,nx,ny,f) ", centroids is empty
1 Commento
Jason
il 8 Gen 2019
Risposta accettata
Più risposte (1)
Image Analyst
il 9 Gen 2019
"The aim is to plot the coordinates from each block on the original image."
Then don't complicate it. You can use a global threshold.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
% clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 18;
folder = pwd; % Current folder.
baseFileName = 'index.png';
% % Have user browse for a file, from a specified "starting folder."
% % For convenience in browsing, set a starting folder from which to browse.
% startingFolder = pwd; % or 'C:\wherever';
% if ~exist(startingFolder, 'dir')
% % If that folder doesn't exist, just start in the current folder.
% startingFolder = pwd;
% end
% % Get the name of the file that the user wants to use.
% defaultFileName = fullfile(startingFolder, '01.png');
% [baseFileName, folder] = uigetfile(defaultFileName, 'Select a file');
% if baseFileName == 0
% % User clicked the Cancel button.
% return;
% end
fullFileName = fullfile(folder, baseFileName)
%===============================================================================
% Check if file exists.
if ~exist(fullFileName, 'file')
% The file doesn't exist -- didn't find it there in that folder.
% Check the entire search path (other folders) for the file by stripping off the folder.
fullFileNameOnSearchPath = baseFileName; % No path this time.
if ~exist(fullFileNameOnSearchPath, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
rgbImage = imread(fullFileName);
% Get the dimensions of the image.
% numberOfColorChannels should be = 1 for a gray scale image, and 3 for an RGB color image.
[rows, columns, numberOfColorChannels] = size(rgbImage)
if numberOfColorChannels > 1
% It's not really gray scale like we expected - it's color.
% Use weighted sum of ALL channels to create a gray scale image.
% grayImage = rgb2gray(rgbImage);
% ALTERNATE METHOD: Convert it to gray scale by taking only the green channel,
% which in a typical snapshot will be the least noisy channel.
grayImage = rgbImage(:, :, 3); % Take blue channel.
else
grayImage = rgbImage; % It's already gray scale.
end
% Now it's gray scale with range of 0 to 255.
% Display the image.
subplot(1, 2, 1);
imshow(grayImage, []);
title('Original Image', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
hp = impixelinfo();
%------------------------------------------------------------------------------
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0.04, 1, 0.96]);
% Get rid of tool bar and pulldown menus that are along top of figure.
% set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
drawnow;
% Threshold.
mask = grayImage == 255;
% Take the largest blobs only
mask = bwareaopen(mask, 100);
% Display the mask.
subplot(1, 2, 2);
imshow(mask);
hp = impixelinfo();
axis('on', 'image'); % Make sure image is not artificially stretched because of screen's aspect ratio.
title('Mask', 'FontSize', fontSize);
% Find the centroids
props = regionprops(mask, 'Centroid', 'Area');
allCentroids = vertcat(props.Centroid)
hold on;
plot(allCentroids(:, 1), allCentroids(:, 2), 'r+', 'MarkerSize', 30, 'LineWidth', 2);

You could do a little better if you worked on the image without the number annotation on it so that you didn't get the 6 and 16.
2 Commenti
Image Analyst
il 9 Gen 2019
Modificato: Image Analyst
il 9 Gen 2019
Jason, my code worked with your original example because you had well separated blobs that were all saturated (255), so global thresholding was sufficient. If your blobs are not saturated, then it wouldn't work.
There is no bwareaclose(), unless you wrote one. You can use bwareafilt() to explude larger blobs:
smallBlobs = bwareafilt(binaryImage, [1, maxAllowableBobSize]);
I'm attaching a program that cleans up a document by doing a local Otsu thresholding. It may be just what you want (at least the thresholding part of the program).
It looks like you could benefit by a higher resolution camera since some of those blobs are pretty blocky and only 3 pixels across.
There is an option to shrink your images. When you browse to it, turn the black twisty that says "display" downwards and select 25% or 50%, or type in something like 33%.
Categorie
Scopri di più su Neighborhood and Block Processing in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
