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

Thread Subject:
Looping

Subject: Looping

From: Twilighter

Date: 10 Jun, 2011 23:03:02

Message: 1 of 6

is there a faster way to make this loop

i read a gray scale image & i convert it into binary image

and i need to replace every 0 value in the image by -1 & keep the 1s as it's

aslo i need to calculate the number of the zeros & ones in the original image

img = double(imread('abc.jpg'));
img = round(reshape(img ,256*256,1)./256);

numofZeros=0;
numofOnes=0;

for (KK=1:length(img ))
    if(img (KK,1)==0)
        img (KK,1)=-1
        numofZeros=numofZeros+1
    else
        numofOnes=numofOnes+1
    end
end

numofZeros;
numofOnes;

Subject: Looping

From: dpb

Date: 10 Jun, 2011 23:59:11

Message: 2 of 6

Twilighter wrote:

> is there a faster way to make this loop
...

> ... i need to replace every 0 value in the image by -1 ...


x(x==0) = -1;


>
> aslo i need to calculate the number of the zeros & ones in the original
> image
...



nZ=sum(x==0);
nO=length(x(:))-nZ;

==

Subject: Looping

From: dpb

Date: 11 Jun, 2011 12:31:58

Message: 3 of 6

dpb wrote:

> Twilighter wrote:
...


>> aslo i need to calculate the number of the zeros & ones in the
>> original image
>
> ...
>
>
>
> nZ=sum(x==0);
> nO=length(x(:))-nZ;
...


or, w/o the logical test,

nO=sum(x:));
nZ=length(x(:))-nZ;


--

Subject: Looping

From: dpb

Date: 11 Jun, 2011 18:08:17

Message: 4 of 6

dpb wrote:

> dpb wrote:
...


> or, w/o the logical test,
>
> nO=sum(x:));
...


typo, missing open paren around the :

--

Subject: Looping

From: Twilighter

Date: 11 Jun, 2011 21:45:20

Message: 5 of 6

Thank you
it worked this way

message_vector=round(message./256);
nZ=sum(sum(message_vector==0));
nO=sum(length(message_vector(:)))-nZ;
message_vector(message_vector==0) = -1;

Subject: Looping

From: dpb

Date: 11 Jun, 2011 22:32:59

Message: 6 of 6

Twilighter wrote:

> Thank you it worked this way
>
> message_vector=round(message./256);
> nZ=sum(sum(message_vector==0));
...


If you're doing this more than once and the size is very large I'd
suggest looking at the later suggestion of

nO = sum(message_vector);
nZ = length....

to see if it doesn't have a performance improvement by eliminating the
logical test.

--

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us