MATLAB Answers


find out the percentage of pixels having value 1

Asked by Bhavini
on 17 Jun 2013

Hi all,

I have a binary image (with values 0 & 1) of the dimensions 497*597. I want to calculate the fraction (%) of pixels with value 1 in each array of 3*3 pixels out of the full image. can anybody help me in this regard?

Any help is highly appriciated.

Thanks in advance



Jan Simon
on 17 Jun 2013

Do you mean overlapping blocks, such that the first one goes from 1 to 3, the 2nd one from 2 to 4? Or should the block be mutually distinct?

on 17 Jun 2013

Dear Jan,

Yes the blocks must be overlapping, starting from 1 upto 595 horizontally and 1 to 495 vertically.


No products are associated with this question.

3 Answers

Answer by Andrei Bobrov
on 17 Jun 2013
Edited by Andrei Bobrov
on 17 Jun 2013

a = randi([0 1],497,597);
ones_frac = conv2(a,ones(3),'valid')/9*100;

or if you have Image Processing Toolbox

ones_frac = blockproc(a,[3 3],@(x)sum(*100);


Answer by Bhomik Luthra
on 17 Jun 2013

Lets take a random matrix of size 497*597. I have found the number of 1's in each 3*3 matrix in first horizontal row, u can do it for 497/3 rows by putting a for loop.

a = randint(497,597);

for i = 1:597/3

    p(i)= length(find (a(1:3,3*i-2:3*i)==1))

p(i) returns the number of 1's in each 3*3 matrix.

Bhomik Luthra


Answer by Jan Simon
on 17 Jun 2013

For a binary image the percentage of 1's is the mean value multiplied by 100.


Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!