简体   繁体   中英

Interior.Color Property inverts colors?

I have written a piece of code that allows me to retrieve the shading color of a specific cell inside a sheet of an excel workbook. I have successfully retrieved the RGB integer value by starting a COM server using MATLAB's actxserver , and then accessing the Color Property of the Interior Object of that particular Cell Object. Then I obtain the equivalent RGB triplet of that integer, so I can use it later for plotting in MATLAB.

In order to test that my code works properly I designed the following test: I created an Excel workbook called colorTest.xlsx with 8 different colors:

在此输入图像描述

Then I run my MATLAB code, which extracts the color information on each cell of the B column. I should get a plot with the colors on the same vertical order and a table with the int value and the RGB triplet of each color.

However something unexpected happens! Look at the results:

在此输入图像描述

Notice that the integer value that is obtained from the Color Property does not always match the color of the original cell, for black, white, green and magenta the integer values are correct, but this is not true for all the other colors. You can see, for example, that for red color on the Excel, the output int and RGB triplet correspond to blue color.

I have added the following table with the correct results I should get, for reference:

Color        Int         R G B
--------     --------    -----
Black               0    0 0 0
White        16777215    1 1 1
Red          16711680    1 0 0
Green           65280    0 1 0
Blue              255    0 0 1
Cyan            65535    0 1 1
Magenta      16711935    1 0 1
Yellow       16776960    1 1 0

I obtained the correct integer values for each color using this RGB Int Calculator .

If we compare the two tables, we can deduce that the Red and Blue channels are inverted .

The code:

The function that I execute to run the test is called getCellColor . Have a look at the code:

function getCellColor()
clear all;
clc;

% Excel
filename = 'colorTest.xlsx';

% Start Excel as ActiveX server process on local host
Excel = actxserver('Excel.Application');

% Handle requested Excel workbook filename
path = validpath(filename);

% Cleanup tasks upon function completion
cleanUp = onCleanup(@()xlsCleanup(Excel, path));

% Open Excel workbook.
readOnly = true;
[~, workbookHandle] = openExcelWorkbook (Excel, path, readOnly);

% Initialise worksheets object
workSheets = workbookHandle.Worksheets;

% Get the sheet object (sheet #1)
sheet = get(workSheets,'item',1);

% Print table headers
fprintf('Color   \t Int     \t R G B\n');
fprintf('--------\t --------\t -----\n');

% Create figure
figure;
hold on;

% Loop through every color on the Excel file
for row = 1:8
    % Get the cell object with name of color
    cell = get(sheet, 'Cells', row, 1);
    cName = cell.value;

    % Get the cell object with colored background
    cell = get(sheet, 'Cells', row, 2);

    % Get the interior object
    interior = cell.Interior;

    % Get the color integer property
    cInt = get(interior, 'Color');  % <-- Pay special attention here(*)

    % Get the RGB triplet from its integer value
    cRGB = int2rgb(cInt);

    % Plot the color
    patch([0 0 1 1], [8-row 9-row 9-row 8-row], cRGB);

    % Print row with color data
    fprintf('%-8s\t %8d\t %d %d %d\n', cName, cInt, cRGB);
end

% Turn off axes
set(findobj(gcf, 'type','axes'), 'Visible','off')

end

(*) This instruction is responsible of recovering the color integer.


Note: The functions described next, do not cause the problem since they do not take part in the obtaining of the color integer (they are only used for secondary tasks). I have included this information only for completeness.

During this process I use three private functions from the MATLAB's iofun folder, which are: validpath , xlsCleanup and openExcelWorkbook . I simply copied them into a folder called private inside the project folder.

Finally, to obtain the RGB triplet from the color integer, I use a function which I adapted from this other function that I found on the net.

Here is the code for my int2rgb function:

function[RGB] = int2rgb(colorInt)
% Returns RGB triplet of an RGB integer.

if colorInt > 16777215 || colorInt < 0
    error ('Invalid int value. Valid range: 0 <= value <= 16777215')
end
R = floor(colorInt / (256*256));
G = floor((colorInt - R*256*256)/256);
B = colorInt - R*256*256 - G*256;

RGB = [R, G, B]/255;
end

I am trying to make some sense out of this, but I really have no idea of what is happening. I have done some research, without much luck, but this post and this other post caught my attention. Maybe it has something to do with my problem.

So does the Interior.Color Property really inverts colors?

If this is the case, should I consider this as normal behavior or is this a bug?


Link to download:

I have packed the entire project on a .zip file and uploaded it, so you can run this test on your machine straight away. Download the file and unpack.

getCellColor.zip

There is no "right" or "wrong" here, Matlab and Excel just encode color differently. You need to account for that in your code.

The closest I can find to an official source is this MSDN article, about half way down see the example of encoding of "blue"

MSDN article

The following examples set the interior of a selection of cells to the color blue. Selection.Interior.Color = 16711680
Selection.Interior.Color = &HFF0000
Selection.Interior.Color = &O77600000
Selection.Interior.Color = RGB(0, 0, 255)

My first thought is check the channels order RGB vs. BGR.

You could probably simplify that int2rgb function by using typecast instead. Here's an example using the values you posted:

clrs = [0; 16777215; 16711680; 65280; 255; 65535; 16711935; 16776960]
for i=1:numel(clrs)
    bgra = typecast(int32(clrs(i)), 'uint8')
end

The output:

clrs =
           0
    16777215
    16711680
       65280
         255
       65535
    16711935
    16776960

bgra =
    0    0    0    0
bgra =
  255  255  255    0
bgra =
    0    0  255    0
bgra =
    0  255    0    0
bgra =
  255    0    0    0
bgra =
  255  255    0    0
bgra =
  255    0  255    0
bgra =
    0  255  255    0

Your int2rgb method inverts R and B. Replace them and you'll get the right conversion. The Interior.Color property uses the convention where R is the least significant, while the FileExchange function you used uses the opposite convention.

To convert from int to RGB:

B = floor(colorInt / (256*256));
G = floor((colorInt - B*256*256)/256);
R = colorInt - B*256*256 - G*256;
colorRGB = [R G B];

To convert from RGB to int:

colorInt = colorRGB * [1 256 256*256]';

From the MSDN article on RGB Color Model:

The RGB color model is used for specifying colors. This model specifies the intensity of red, green, and blue on a scale of 0 to 255, with 0 (zero) indicating the minimum intensity. The settings of the three colors are converted to a single integer value by using this formula:

RGB value = Red + (Green*256) + (Blue*256*256)

As it was suggested in chris neilsen answer , there is no "right" or "wrong" in terms of color encoding. Microsoft has chosen this particular way to encode colors for reasons only they know, and I should stick to it.

So the RGB values that I get are totally correct.

In the following table, I have included the RGB values provided in the MSDN article next to the ones that I get in MATLAB, and they are a perfect match.

Color        Int         RGB values from MSDN
--------     --------    --------
Black               0           0
White        16777215    16777215
Red               255         255
Green           65280       65280
Blue         16711680    16711680
Cyan         16776960    16776960
Magenta      16711935    16711935
Yellow          65535       65535

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM