What is the difference between two matrices?

Viewed 72

Recently I got a script from GitHub which provides user an opportunity to select several ROIs in an image of color checker. Then the script computes a correction matrix 3x4 (cc_mat) where first three columns contain RGB coefficients and the last one contains coefficients to keep proper white balance:

[[ 1.85740626e+00 -3.61503768e-01 -3.23657397e-01 -1.76378977e+02]
 [-3.87633414e-01  2.09003773e+00 -5.27259304e-01 -1.79348491e+02]
 [ 8.14513011e-02 -1.07566732e+00  2.13731634e+00 -1.46534728e+02]] 

My goal is to adjust this code the way it would change the image according to the matrix. I googled how to change color channels of an image and there was such a recommendation (How to Access and Change Color Channels using PIL?):

from PIL import Image 

# Open image 
im = Image.open('image.jpg') 

# Make transform matrix, to multiply R by 1.1, G by 0.9 and leave B unchanged
# newRed   = 1.1*oldRed  +  0*oldGreen    +  0*oldBlue  + constant
# newGreen = 0*oldRed    +  0.9*OldGreen  +  0*OldBlue  + constant
# newBlue  = 0*oldRed    +  0*OldGreen    +  1*OldBlue  + constant
Matrix = ( 1.1,   0,  0, 0, 
           0,   0.9,  0, 0, 
           0,     0,  1, 0) 

# Apply transform and save 
im = im.convert("RGB", Matrix) 
im.save('result.png') 

First I gave this script a try by inserting input values instead of 1.1, 0.9 and 1. It worked OK.

r_chmult = float( input( 'Multiply Red channel by \n' ))
g_chmult = float( input( 'Multiply Green channel by \n' ))
b_chmult = float( input( 'Multiply Blue channel by \n' ))
img2 = im.open ('D:/Python/Checker.jpg')
Matrix = [r_chmult, 0, 0, 0,
          0, g_chmult, 0, 0,
          0, 0, b_chmult, 0]
img3 = img2.convert( "RGB", Matrix )
img3.save( 'D:/Python/result.jpg' )
img3.show()

Then I tried to put cc_mat in place of Matrix in im = im.convert("RGB", Matrix). This time it didn't work and the error said:

Traceback (most recent call last):
  File "C:/Users/studi/PycharmProjects/pythonProject/venv/Checker.py", line 144, in <module>
    img3 = img2.convert( "RGB", cc_mat )
  File "C:\Users\studi\PycharmProjects\pythonProject\venv\lib\site-packages\PIL\Image.py", line 912, in convert
    if not mode or (mode == self.mode and not matrix):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

What's my problem? What is the difference between these two matrices?

2 Answers

The error is because cc_mat is two dimensional. The matrix you should at the top has an extra set of brackets that give it an extra dimension so PIL gets confused. You need to reshape this matrix into a shape of just 12. You can do this like this

cc_mat.reshape(12).tolist()

"Matrix" type is tuple, but type of "cc_mat" is somewhat similar to 2D list.
Please convert the type of "cc_mat" to tuple.

Related