在MATLAB中,灰度图像是彩色像素的二维图像阵列(M * N)。当我们对灰度图像中的颜色进行补色时,灰度图像中的每个颜色像素都将被其互补色像素替换。
补全的结果是,灰度图像中的暗区域变亮,而亮区域变暗。
使用MATLAB库函数补充灰度图像的颜色:
% read a Grayscale Image in MATLAB Environment
img=imread('apple.jpg');
% complement colors of a Grayscale image
% using imcomplement() function
comp=imcomplement(img);
% Display Complemented grayscale Image
imshow(comp);
在不使用MATLAB库函数的情况下补充灰度图像的颜色:
灰度图像的像素值在0到255之间。我们可以通过从灰度图像像素可以具有的最大可能像素值(即255)中减去每个像素值来补充灰度图像,并且将差值用作补充的灰度图像。
It means if an image pixel have value 100 then, in complemented Grayscale image same pixel will have value ( 255 – 100 ) = 155.
And if Grayscale image pixel have value 0 then, in complemented grayscale image same pixel will have value ( 255 – 0 ) = 255.
Similarly, if Grayscale image pixel have value 255 then, in complemented grayscale image same pixel will have value ( 255 – 255 ) = 0.
以下是上述想法的实现:
% This function will take a Grayscale image as input
% and will complement the colors in it.
function [complement] = complementGray(img)
% Determine the number of rows and columns
% in the Grayscale image array
[x, y]=size(img);
% create a array of same number rows and
% columns as original Grayscale image array
complement=zeros(x, y);
% loop to subtract 255 to each pixel.
for i=1:x
for j=1:y
complement(i, j) = 255-img(i, j);
end
end
end
% Driver Code
% read a Grayscale Image in MATLAB Environment
img=imread('apple.jpg');
% call complementGray() function to
% complement colors in the Grayscale Image
comp=complementGray(img);
% Display complemented Grayscale image
imshow(comp);
或者 –
而不是使用两个循环将灰度图像的每个像素减去255。我们可以直接将其写为comp = 255-image
。上面的代码将从255中减去图像数组的每个值。
下面的代码还将补充灰度图像:
% read a Grayscale Image in MATLAB Environment
img=imread('apple.jpg');
% complement each pixel by subtracting it from 255.
comp=255-img;
% Display Complemented Grayscale Image
imshow(comp);
输入:
输出: