How to convert black and white image to array with 3 dimensions in python?

computer-vision, image, image-processing, numpy, python

Solution

You can always add "empty" dimensions using `np.expand_dims`:

>>> a2d = np.ones((100, 200))
>>> a3d = np.expand_dims(a2d, axis=2)
>>> a3d.shape
(100, 200, 1)

or by slicing with `None` or `np.newaxis`:

>>> a2d[..., None].shape  # instead of "..." (Ellipsis) you could also use `[:, :, None]`
(100, 200, 1)

I prefer `np.expand_dims` because it's a bit more explicit about what happens than slicing.

If you need it conditionally, check for `arr.ndim` first:

if arr.ndim == 2:
    arr = np.expand_dims(arr, axis=2)

Problem

I have image in either RGB format or grayscale format (I converted it through Gimp, let's say), now everytime I load the image in grayscale, or just transform it to grayscale format, the shape always says [height, width] without the third dimension (number of color channels). I know that usually b/w images are stored in such format, but I specifically need the `[height, width, 1]` image shape, the one you would get with, let's say: ``` numpy.zeros(shape=[400, 400, 1]) ```

Original source