Search code examples
javaopencvpixel

Wrong value of pixels color when reading from a mat


Im having some problems lately about getting the color of a pixel using Open CV and java . This is what i did.

System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    Mat a = Imgcodecs.imread("C:\\Users\\User\\workspace\\OpenCv\\color.png",Imgcodecs.CV_LOAD_IMAGE_COLOR);
    System.out.println(Arrays.toString(getPixelColor(0, 0, a))); //top left
    System.out.println(Arrays.toString(getPixelColor(9, 0, a))); //top right
    System.out.println(Arrays.toString(getPixelColor(0, 9, a))); // bottom left 
    System.out.println(Arrays.toString(getPixelColor(9, 9, a))); // bottom right

So this code returns the following

[255.0, 255.0, 0.0] //top left
[0.0, 0.0, 255.0] //top right
[255.0, 0.0, 0.0] // bottom left 
[0.0, 255.0, 255.0]// bottom right

for this image enter image description here which is a 10*10 image.

This is the right values from photoshop for each color.

[0, 255.0, 255.0] Cyan //top left
[0.0, 0.0, 255.0] Blue //top right
[255.0, 0.0, 0.0] Red // bottom left 
[255.0, 255.0, 0] Yellow // bottom right

The image loads up as mat from type CV_8UC3 so its rbg.

Anyone knows why is this happening ? Also if im using cvtColor to change from bgr -> rbg im not getting the right output still

[0.0, 255.0, 255.0] Cyan ok //top left
[255.0, 0.0, 0.0] Should be blue  , is red //top right
[0.0, 0.0, 255.0] Should be red , is blue // bottom left
[255.0, 255.0, 0.0] Yellow ok // bottom right

Solution

  • First, OpenCV tends to use BGR instead of RGB if the ordering is not specified. It is accurate to use cvtColor to change it from BGR to RGB.

    Second, thegetPixelColor call parameters are not (x, y), but (row, column), which is equivalent to (y, x). This means what appears to be the top right is actually the bottom left, and vice versa.