How to Get Negative of an Image in MATLAB
This tutorial will discuss finding the negative of an image by changing the intensity levels of the pixels present in the image in Matlab.
Get Negative of an Image in MATLAB
A picture is composed of pixels that contain different intensity levels. For example, a 200 by 200 image means 200 pixels on the horizontal axis and 200 only vertical axis. Each pixel is composed of intensity levels. For example, an 8-bit image is composed of 256 intensity levels which start from 0 to 256. To get the negative of an image, we need to reverse these values of the image. For example, we need to convert 0 to 256 and 256 to 0. The formula to take negative of an image would be the max intensity level - the pixel value. For example, in the case of an 8-bit image, the max intensity level is 256, so we can subtract each pixel value from 256 and store that value back into the specific pixel. In Matlab, we can read an image file using the imread()
function and store it into a variable. The algorithm for this function would be to read the image and store it in a variable and then subtract each pixel value from 256 and store it back in the original variable and show the image using the function imshow()
. In the output, the image colors will be reversed. For example, if the color is white, it will be converted to black. For example, let’s get the negative of an image in Matlab. See the code below.
OriginalImg = imread('cat.jpg');
NImg = 256 - OriginalImg;
subplot(1,2,1)
imshow(OriginalImg)
title('Original image')
subplot(1,2,2)
imshow(NImg)
title('Negative Image')
Output:
In the above output, the colors of the image have reversed. The light colors have converted to dark and the dark colors to light. In the case of color images, the red color becomes cyan, the green color becomes magenta, the blue color becomes yellow, and vice versa. In the case of binary images, zeros will be replaced by ones and ones with zeros. We can also use Matlab’s built-in function imcomplement()
to find the negative of an image. The function imcomplement()
subtracts the pixel value from the maximum pixel value of the image class.