2

I encountered this puzzling situation when trying to get rid of the third dimension (the RGB dimension) of my images in order to feed them to a Knn classifier for face recognition.

I took one colored face image from the Labeled-face-in-the-wild database as an example. It is saved locally.

I first imported the image, then converted it to grayscale, then checked dimension (time1), then exported with "imwrite", then imported the gray scale image again, then checked its dimension again (time2).

At (time1), the dimension was 2: (250, 250). However, at (time2), the dimension became 3: (250, 250, 3). Why would exporting and importing change the dimension of the gray scale picture? What should I specify when importing the gray scale picture to keep it 2 dimensional?

Here is my python code:

import cv2

import matplotlib.pyplot as plt

imgBGR = cv2.imread("path/filename")

gray = cv2.cvtColor(imgBGR, cv2.COLOR_BGR2GRAY)

gray.shape  # this gives me (250, 250)

cv2.imwrite("path/newname", gray)

gray2 = cv2.imread("path/newname")

gray2.shape  # this gives me (250, 250, 3)
Community
  • 1
  • 1
X. Liu
  • 21
  • 1
  • 4
  • 1
    Possible duplicate of [In OpenCV (Python), why am I getting 3 channel images from a grayscale image?](https://stackoverflow.com/questions/18870603/in-opencv-python-why-am-i-getting-3-channel-images-from-a-grayscale-image) – LeKhan9 Nov 05 '18 at 18:42
  • 2
    I believe this may be answered above. Try this: `img = cv2.imread('gray.jpg',0)` – LeKhan9 Nov 05 '18 at 18:43
  • If you use `cv2.IMREAD_UNCHANGED` instead of `0`, future readers of your code will thank you. – Dave W. Smith Nov 06 '18 at 04:41
  • Not to take this too far, but you can always diminish 0 being a magic var by declaring it as such: `READ_GRAYSCALE_ONLY_FLAG = 0` before you pass it :) – LeKhan9 Nov 06 '18 at 04:48
  • ^ That's taking it too far. Don't make up new constants; use the constants that are already there. – Dave W. Smith Nov 06 '18 at 21:45

1 Answers1

3

Try gray2 = cv2.imread("path/newname" , cv2.IMREAD_GRAYSCALE)

As Opencv imread documentaion, the default is cv2.IMREAD_COLOR, so with setting the flag the default setting of cv2.imread is reading image in colour, so it will split a greyscale image into 3 channels.

By specific cv2.imread("path/newname" , cv2.IMREAD_GRAYSCALE), the function will read in image in grayscale.

Echan
  • 1,395
  • 14
  • 15