OpenCV获取图像RGB矩阵

2024-05-08 15:31:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个图像,我想得到它的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矩阵


Tags: 代码alphaimgsizetype矩阵rgbcv2
2条回答

如果您使用的是python3,那么将所有print语句替换为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)

print的语法随Python3而改变,现在需要括号。试一试

print(type(img))

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

相关问题 更多 >