Search code examples
matlabimage-processingpng

Convert RGB image into indexed image and save it


I have an RGB image. So when I do [image2, map] = imread('image.png') in Matlab I get [] for map as expected. I want to convert that RGB image to an indexed image. I want to save it as an indexed image with one channel and see colours like here.

Referring here I used the following code in Matlab.

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

But what is saved is a grey-scale image. And when I read it back still the map is []. I want to write it so that it will be a colour image and when I use [image2, map] = imread('image.png') next time, map won't be []. Can someone please help?


Solution

  • You can do the following:

    • Convert image from RGB to indexed image with 2 color:

      [X, cmap] = rgb2ind(RGB, 2);
      
    • Replace indices of color map to black and white:

      cmap(1, 1:3) = [0, 0, 0]; %Fist color is black
      cmap(2, 1:3) = [1, 1, 1]; %Second color is white
      
    • Write indexed image (and map) to PNG file:

      imwrite(X, cmap, 'K.png');
      

    Pay attention: you need to write the matrix and the color map, when writing and indexed image to file.

    • Read image (and map) from PNG file, and convert it to RGB image:

      [I, cmap2] = imread('K.png');
      L = ind2rgb(I, cmap2);
      

    Here is a code sample:

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

    For completion, here is an example using your reference:

    [webX, web_cmap] = imread('https://i.sstatic.net/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);
    

    Result:
    enter image description here