Search code examples
pythonsyntax-error

OpenCV getting an image RGB matrix


I have an image which I want to get the RGB matrix for, and since I'm kinda new to OpenCV and Python I was looking how to do it, and I found the following code:

img_file = 'baboon.png'

img = cv2.imread(img_file, cv2.IMREAD_COLOR)           # rgb
alpha_img = cv2.imread(img_file, cv2.IMREAD_UNCHANGED) # rgba
gray_img = cv2.imread(img_file, cv2.IMREAD_GRAYSCALE)  # grayscale


print type(img)
print 'RGB shape: ', img.shape        # Rows, cols, channels
print 'ARGB shape:', alpha_img.shape
print 'Gray shape:', gray_img.shape
print 'img.dtype: ', img.dtype
print 'img.size: ', img.size

After reading the code, and kinda understanding it, I'm getting the following error:

File "vision.py", line 10
    print type(img)
             ^
SyntaxError: invalid syntax

Could someone explain that error? Or if there is another better way to get the RGB matrix?


Solution

  • if you are using python3 then replace your all print statements to print()

    img_file = 'baboon.png'
    img = cv2.imread(img_file,cv2.IMREAD_COLOR) 
    alpha_img = cv2.imread(img_file,cv2.IMREAD_UNCHANGED) # rgba   
    gray_img = cv2.imread(img_file, cv2.IMREAD_GRAYSCALE) # grayscale
    
    print(type(img))
    print('RGB shape: ', img.shape) # Rows, cols, channels
    print('ARGB shape:', alpha_img.shape)
    print('Gray shape:', gray_img.shape)   
    print('img.dtype: ', img.dtype)
    print('img.size: ', img.size)