Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find image type in python openCV

Tags:

python

opencv

I recently had some issues finding the type of a template image i'm using for pattern matching purposes. I use the python version of OpenCV, and the image returned by imread does not seem to have a "type" property like in the C++ OpenCV implementation.

I would like to access the type of the template to create a "dst" Mat having the same size and type of the template.

Here is the code :

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'

Do you have any thoughts about this issue ?

Thanks a lot for your answers.

like image 256
Alexandre Rozier Avatar asked May 10 '16 12:05

Alexandre Rozier


1 Answers

While it's true that the numpy array type can be accessed using template.dtype, that's not the type you want to pass to cv2.cv.CreateMat() , e.g.

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')

If you pass the numpy array's dtype to cv2.cv.CreateMat() you will get this error, e.g.

cv2.cv.CreateMat(500, 500, template.dtype)

TypeError: an integer is required

And as you can see, the dtype doesn't change for grayscale/color, however

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)

Here you can see that it's the img.shape that is more useful to you.

Create a numpy matrix from the template

So you want to create a object from your template you can do :

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

That should be useable as far as Python API goes.

cv2.cv.CreateMat

If you want this using the C++ way of creating matrices, you should remember the type with which you opened your template:

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)

If you insist on guessing the type: While it's not perfect, you can guess by reading the length of the dimensions of the matrix, an image of type IMREAD_COLOR has 3 dimensions, while IMREAD_GRAYSCALE has 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
like image 144
bakkal Avatar answered Nov 12 '22 10:11

bakkal