【问题标题】:Convert RGB image into indexed image and save it将RGB图像转换为索引图像并保存
【发布时间】:2020-03-04 04:25:05
【问题描述】:

我有一个 RGB 图像。因此,当我在 Matlab 中执行 [image2, map] = imread('image.png') 时,我得到了 [] 的预期地图。我想将该 RGB 图像转换为索引图像。我想将其另存为具有一个通道的索引图像,并查看像 here 这样的颜色。

引用here我在Matlab中使用了以下代码。

image2 = imread('image.png');
IND = rgb2ind(image2,256);
imwrite(IND, 'imageIndexed.png')

但保存的是灰度图像。当我读回来时,地图仍然是[]。我想把它写成彩色图像,当我下次使用[image2, map] = imread('image.png')时,地图不会是[]。有人可以帮忙吗?

【问题讨论】:

    标签: matlab image-processing png


    【解决方案1】:

    您可以执行以下操作:

    • 将图像从 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);
    figure;imshow(K);
    
    imwrite(X, cmap, 'K.png');
    
    [I, cmap2] = imread('K.png');
    L = ind2rgb(I, cmap2);
    figure;imshow(L);
    

    为了完成,这里是一个使用你的reference的例子:

    [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);
    

    结果:

    【讨论】:

    • 非常感谢,它有效 ^_^ 我提供该链接只是为了显示我想要的。如果我有两种以上的颜色,我可以做“bwRGB = ind2rgb(X, cmap);”在“H = H.Values';”之后对吗?
    • 对,histogram的部分也可以跳过,我只是玩了一下。
    猜你喜欢
    • 2017-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 2011-07-10
    • 1970-01-01
    • 2015-11-17
    相关资源
    最近更新 更多