In OpenCV (Python), why am I getting 3 channel images from a grayscale image?

后端 未结 3 1578
心在旅途
心在旅途 2021-01-31 08:15

I am using Python (2.7) and bindings for OpenCV 2.4.6 on Ubuntu 12.04

I load an image

    image = cv2.imread(\'image.jpg\')

I then chec

3条回答
  •  有刺的猬
    2021-01-31 08:31

    Your code is correct, it seems that cv2.imread load an image with three channels unless CV_LOAD_IMAGE_GRAYSCALE is set.

    >>> import cv2
    >>> image = cv2.imread('foo.jpg')
    >>> print image.shape
     (184, 300, 3)
    >>> gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    >>> print gray_image.shape 
     (184, 300)
    >>> cv2.imwrite('gray.jpg', gray_image)
    

    Now if you load the image:

    >>> image = cv2.imread('gray.jpg')
    >>> print image.shape
     (184, 300, 3)
    

    It seems that you have saved the image as BGR, however it is not true, it is just opencv, by default it reads the image with 3 channels, and in the case it is grayscale it copies its layer three times. If you load again the image with scipy you could see that the image is indeed grayscale:

    >>> from scipy.ndimage import imread
    >>> image2 = imread('gray.jpg')
    >>> print image2.shape
     (184, 300)
    

    So if you want to load a grayscale image you will need to set CV_LOAD_IMAGE_GRAYSCALE flag:

    >>> image = cv2.imread('gray.jpg', cv2.CV_LOAD_IMAGE_GRAYSCALE)
    >>> print image.shape
     (184, 300)
    

提交回复
热议问题