在Python的OpenCV中查找图像类型

16

最近我在使用模板匹配时遇到了一些问题,我无法确定正在使用的模板图像类型。我使用的是OpenCV的Python版本,通过imread读取的图像似乎没有C++ OpenCV中的"type"属性。

我希望能够访问模板的类型,以创建一个大小和类型与模板相同的"dst"Mat

以下是代码:

template = cv2.imread('path-to-file', 1)
height, width = template.shape[:-1]
dst = cv2.cv.CreateMat(width,height, template.type) 
--->'Error :numpy.ndarray' object has no attribute 'type'

您对这个问题有什么想法吗?

非常感谢您的回答。


4
由于图像是numpy数组,因此其类型由“dtype”属性给出。 - David Zwicker
1个回答

25

虽然numpy数组类型可以使用template.dtype进行访问,但这不是您要传递给cv2.cv.CreateMat()的类型,例如。

In [41]: cv2.imread('abalone.jpg', cv2.IMREAD_COLOR).dtype         
Out[41]: dtype('uint8')

In [42]: cv2.imread('abalone.jpg', cv2.IMREAD_GRAYSCALE).dtype
Out[42]: dtype('uint8')
如果您将numpy数组的dtype传递给cv2.cv.CreateMat(),则会出现此错误,例如:
cv2.cv.CreateMat(500, 500, template.dtype)

类型错误:需要一个整数

正如您所看到的,对于灰度/彩色图像,dtype并不会改变。

In [43]: cv2.imread('abalone.jpg', cv2.IMREAD_GRAYSCALE).shape
Out[43]: (250, 250)

In [44]: cv2.imread('abalone.jpg', cv2.IMREAD_COLOR).shape
Out[44]: (250, 250, 3)

在这里,您可以看到img.shape对您更有用。

从模板创建numpy矩阵

因此,您想从模板创建一个对象,可以执行以下操作:

import numpy as np
dst = np.zeros(template.shape, dtype=template.dtype)

就 Python API 而言,那应该是可以使用的。

cv2.cv.CreateMat

如果您想以 C++ 创建矩阵的方式来使用它,您应该记住打开模板时使用的类型:

template = cv2.imread('path-to-file', 1) # 1 means cv2.IMREAD_COLOR 
height, width = template.shape[:-1]    
dst = cv2.cv.CreateMat(height, width, cv2.IMREAD_COLOR)

如果你坚持要猜测图像类型: 虽然并不完美,但是你可以通过阅读矩阵的维度长度来进行猜测,IMREAD_COLOR 类型的图像有3个维度,而 IMREAD_GRAYSCALE 则有2个。

In [58]: len(cv2.imread('abalone.jpg', cv2.IMREAD_COLOR).shape)
Out[58]: 3

In [59]: len(cv2.imread('abalone.jpg', cv2.IMREAD_GRAYSCALE).shape)
Out[59]: 2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接