您可以执行以下操作:
将图像从RGB转换为2种颜色的索引图像:[X, cmap] = rgb2ind(RGB, 2);
将彩色图的索引替换为黑白:cmap(1, 1:3) = [0, 0, 0]; %Fist color is black cmap(2, 1:3) = [1, 1, 1]; %Second color is white
将索引图像(和地图)写入PNG文件:imwrite(X, cmap, 'K.png');
注意:将图像和索引图像写入文件时,需要写入矩阵和颜色图。
从PNG文件读取图像(和地图),并将其转换为RGB图像:[I, cmap2] = imread('K.png'); L = ind2rgb(I, cmap2);
这是一个代码示例:
RGB = imresize(imread('peppers.png'), 0.5); %Read input RGB image.
%Convert image to indexed image with 2 color.
[X, cmap] = rgb2ind(RGB, 2);
J = ind2rgb(X, cmap);
%Replace indices of color map:
cmap(1, 1:3) = [0, 0, 0]; %Fist color is black
cmap(2, 1:3) = [1, 1, 1]; %Second color is white
K = ind2rgb(X, cmap);
figure;imshow(RGB);
figure;imshow(J);