Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the number of channels from an image, in OpenCV 2?

The answers at Can I determine the number of channels in cv::Mat Opencv answer this question for OpenCV 1: you use the Mat.channels() method of the image.

But in cv2 (I'm using 2.4.6), the image data structure I have doesn't have a channels() method. I'm using Python 2.7.

Code snippet:

cam = cv2.VideoCapture(source) ret, img = cam.read() # Here's where I would like to find the number of channels in img. 

Interactive attempt:

>>> img.channels() Traceback (most recent call last):   File "<interactive input>", line 1, in <module> AttributeError: 'numpy.ndarray' object has no attribute 'channels' >>> type(img) <type 'numpy.ndarray'> >>> img.dtype dtype('uint8') >>> dir(img) ['T',  '__abs__',  '__add__', ...  'transpose',  'var',  'view'] # Nothing obvious that would expose the number of channels. 

Thanks for any help.

like image 491
LarsH Avatar asked Sep 28 '13 03:09

LarsH


People also ask

What is number of channels in OpenCV?

There are three channels in an RGB image- red, green and blue. The color space where red, green and blue channels represent images is called RGB color space. In OpenCV, BGR sequence is used instead of RGB. This means the first channel is blue, the second channel is green, and the third channel is red.

How do you extract the ROI from an image in Python?

Python OpenCV – selectroi() Function With this method, we can select a range of interest in an image manually by selecting the area on the image. Parameter: window_name: name of the window where selection process will be shown. source image: image to select a ROI.

How do you count contours in OpenCV?

To find the number of contours, we use the len() function. This gives us the number of contours (or objects) in the image. We then print out the number of objects in this image. So this how we can count the number of objects in an image in Python using OpenCV.


2 Answers

Use img.shape

It provides you the shape of img in all directions. ie number of rows, number of columns for a 2D array (grayscale image). For 3D array, it gives you number of channels also.

So if len(img.shape) gives you two, it has a single channel.

If len(img.shape) gives you three, third element gives you number of channels.

For more details, visit here

like image 147
Abid Rahman K Avatar answered Sep 20 '22 08:09

Abid Rahman K


I'm kind of late but there is another simple way out there:

Use image.ndim Source, will give your right number of channels as below:

 if image.ndim == 2:      channels = 1 #single (grayscale)  if image.ndim == 3:      channels = image.shape[-1] 

Edit: In one-liners:

channels = image.shape[-1] if image.ndim == 3 else 1 

Since a image is a nothing but a numpy array. Checkout OpenCV docs here: docs

like image 22
abhiTronix Avatar answered Sep 24 '22 08:09

abhiTronix