Convert RGB image into indexed image and save it
我有一个RGB图像。因此,当我在Matlab中执行
在这里引用我在Matlab中使用了以下代码。
但是保存的是灰度图像。当我读回它时,地图仍然是
您可以执行以下操作:
-
将图像从RGB转换为具有2种颜色的索引图像:
1[X, cmap] = rgb2ind(RGB, 2); -
将彩色图的索引替换为黑白:
1
2cmap(1, 1:3) = [0, 0, 0]; %Fist color is black
cmap(2, 1:3) = [1, 1, 1]; %Second color is white -
将索引图像(和地图)写入PNG文件:
1
注意:将图像和索引图像写入文件时,需要写入矩阵和颜色图。
-
从PNG文件读取图像(和地图),并将其转换为RGB图像:
这是一个代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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); figure;imshow(K); imwrite(X, cmap, 'K.png'); [I, cmap2] = imread('K.png'); L = ind2rgb(I, cmap2); figure;imshow(L); |
为完成此操作,请参考以下示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | [webX, web_cmap] = imread('https://i.stack.imgur.com/zuIra.png'); %Read input image and color map. RGB = ind2rgb(webX, web_cmap); %Convert image to indexed image with 4 colors. [X, cmap] = rgb2ind(RGB, 4); %Collect histogram H = histogram(X, 4); H = H.Values'; %Replace indices of color map: set the color with minimal pixels to white, and other to black. cmap(H == min(H), :) = 1; %Fist color is black cmap(H ~= min(H), :) = 0; %Set other three colors to black %Convert to RGB bwRGB = ind2rgb(X, cmap); %Convert to indexed image with only 2 colors: [X, cmap] = rgb2ind(bwRGB, 2); imwrite(X, cmap, 'K.png'); [I, cmap2] = imread('K.png'); L = ind2rgb(I, cmap2); figure;imshow(L); |
结果: