0

I have a binary image and I need to randomly select a pixel with value 1 (a white pixel) from it. I've written a while/if loop to do the job, This is my code:

Clear all
clc

%  I have defined matrix A  as an example of a given bw image

A=[0 0 1 0 0;0 0 0 1 0;0 1 0 0 0;0 0 0 1 0;1 0 0 0 0];
bwImage=mat2gray(A);
Number_Of_Pixls = numel(bwImage)
Number_Of_Interest_Points=numel(find(bwImage))

% randomly select a pixel

condition=0;
while ~(condition)                      
    RandomPixel = randi(Number_Of_Pixls)
    bwImage(RandomPixel)      % to show the value of the selected pixel
    if bwImage(RandomPixel) == 1
        condition = 1;  break
    else
        continue
    end
end
SelectedPixel =RandomPixel  % show which pixel had been selected

this code works, but when it comes to real images with large number of pixels, this search process becomes very exhaustive, and computationally expensive, which makes it actually useless. Is there any way to do this job in a faster way?

2
  • Sorry to make an edit to your code -- that's usually a no-no -- but with % I've defined , the ' broke syntax highlighting for the rest of the code. MATLAB support at SO is still not too good. Commented Oct 28, 2013 at 18:48
  • @ chappjc, thanks... you corrected my lines :) Commented Oct 30, 2013 at 20:07

3 Answers 3

2

You can do it easily without loops:

A = [0 0 1 0 0;0 0 0 1 0;0 1 0 0 0;0 0 0 1 0;1 0 0 0 0]; % data
ind = find(A); % linear indices of nonzero values
ind_sel = ind(randi(length(ind))); % randomly select one, in linear index...
[ row_sel col_sel ] = ind2sub( size(A), ind_selected); % ...or in subindices
Sign up to request clarification or add additional context in comments.

1 Comment

I thank you very much @Luis Mendo, it works great :)
1

Why are you iterating though all points in first place, if you are only interested in ones???

idx = find(bwImage==1); %only choose points that are 1
RandomPixel = randi(length(idx));

idx[RandomPixel] would be an index into random pixel of bw image with value of 1.

2 Comments

I think you need to edit the first line to idx=find(bwImage) otherwise you'll still get a vector of zeros and ones...
Looks good now, but you have converged on Luis' solution. :)
-1

My guess would be that mat2gray is the problem. First, you don't need it, because you already have A which only has values 0 or 1. If anything, you may want to convert it to a logical.

I am guessing that when mat2gray tries to re-scale the values, you get back something close to 1, but not exactly 1, because of the floating point weirdness.

Essentially, your problem boils down to the fact that you cannot compare floating point numbers for exact equality.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.