Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

matlab
communitycreator

# How to complement colors in a grayscale image in MATLAB

Rohan Mishra

In MATLAB, a grayscale image is a 2D, $M$x$N$, image array of color pixels. If we add colors in a grayscale image, the gray pixel in the grayscale image is replaced with a complementary color pixel.

### Complement a grayscale image

A grayscale image has a pixel value in the range 0-255. We can complement a grayscale image by subtracting each pixel value from 255. The difference is used as the pixel value in the complemented grayscale image.

For example:

• If an image pixel has a value of 110, then in the complemented grayscale image, the same pixel will have a value of 145 (255 – 110 = 145).

• If a grayscale image pixel’s value is 0, then in the complemented grayscale image, the same pixel’s value will be 255 (255 – 0 = 255).

• Similarly, if the grayscale image pixel has a value of 255, then in the complemented grayscale image, the same pixel will have a value of 0 (255 – 255 = 0).

The following function will take a grayscale image and will complement the colors in it.

function [complement] = complementGray(img)


To determine the number of rows and columns in the grayscale image array:

[x, y]=size(img);


### Method

1. Create an array of the same number of rows and columns as the original grayscale image array.
complement=zeros(x, y);

1. Loop to subtract 255 from each pixel.
for i=1:x
for j=1:y
complement(i, j) = 255-img(i, j);
end
end

end

1. Read a grayscale image in the MATLAB environment.
img=imread('Corn.jpg');


You can replace Corn.jpg, with the image you wish to import.

1. Complement the colors of a grayscale image using.
comp=complementGray(img);

1. Display the complemented grayscale image.
imshow(comp);


### Code

[x, y]=size(img);

for i=1:x
for j=1:y
complement(i, j) = 255-img(i, j);
end
end

end

img=imread('corn.jpg');

comp=complementGray(img);

imshow(comp);


### Output

adding image, corn.jpg
imshow(comp)-after complementing colors, image will be something like this

RELATED TAGS

matlab
communitycreator

CONTRIBUTOR

Rohan Mishra
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time

Copyright ©2022 Educative, Inc. All rights reserved.