我有一张二进制图像,需要将所有黑色像素转换为白色像素,反之亦然。然后,我需要将新图像保存到文件中。是否有一种方法可以在不循环每个像素并翻转其值的情况下完成这项任务?
如果你有一个仅包含0和1的二值图像binImage
,有很多简单的方法可以将其反转:
binImage = ~binImage;
binImage = 1-binImage;
binImage = (binImage == 0);
然后,只需使用函数IMWRITE保存反转图像即可。
imcomplement
。假设您有一个二进制图像b,那么:bc = imcomplement(b); % gives you the inverted version of b
b = imcomplement(bc); % returns it to the original b
imwrite(bc,'c:\...'); % to save the file in disk
not
,我们可以将1转换为0,0转换为1。inverted_binary_image = not(binary_image)
[filename, pathname] = uigetfile({'*.bmp'},'Text as image');
img=imread(filename);
img=im2double(img);
[r,c,ch]=size(img);
%imshow(img);
invert_img=img;
if(ch==1)
for i=1:r
for j=1:c
if(invert_img(i,j)==0)
invert_img(i,j)=1;
else
invert_img(i,j)=0;
end
end
end
end