Python OpenCV获取图像RGB矩阵

Python OpenCV获取图像RGB矩阵,python,syntax-error,Python,Syntax Error,我有一个图像,我想得到它的RGB矩阵,因为我对OpenCV和Python有点陌生,所以我在研究如何实现它,我发现了以下代码: 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.IMR

我有一个图像,我想得到它的RGB矩阵,因为我对OpenCV和Python有点陌生,所以我在研究如何实现它,我发现了以下代码:

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
在阅读了代码并理解了它之后,我得到了以下错误:

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

有人能解释一下这个错误吗?或者是否有其他更好的方法来获取RGB矩阵?

Python3更改了打印的语法,现在需要括号。试一试

print(type(img))

此外,您很快就会发现OpenCV/cv2订购的是BGR层,而不是您所期望的RGB层。

如果您使用的是python3,则将所有打印语句替换为print()


嗯,我明白了,非常感谢,但是现在我在运行程序时遇到了这个问题,我没有得到任何信息,只有空白。RGB shape:ARGB shape:Gray shape:img.dtype:img.size:有什么原因吗?您使用的是Python 2还是Python 3?该代码是Python 2中的。这是:,,的副本。这是否回答了您的问题?
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)