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

后端 未结 3 1327
情话喂你
情话喂你 2020-12-30 23:34

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.

相关标签:
3条回答
  • 2020-12-30 23:37

    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]
    

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

    0 讨论(0)
  • 2020-12-30 23:49

    As i know, u should use image.shape[2] to determine number of channels, not len(img.shape), the latter gives the dimensions of the array.

    0 讨论(0)
  • 2020-12-31 00:04

    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

    0 讨论(0)
提交回复
热议问题