I would like to add here a self-contained script using the PIL
library and another one using the cv2
library
CV2 Library script
import cv2
import numpy as np
img = cv2.imread("full_path_to_image")
img_np = np.asarray(img)
print("img_np.shape: ", img_np.shape)
The last column of the last print will show the number of channels, for example
img_np.shape: (1200, 1920, 4)
PIL Library script
from PIL import Image
import numpy as np
img = Image.imread("full_path_to_image")
img_np = np.asarray(img)
print("img_np.shape: ", img_np.shape)
The last column of the last print will show the number of channels, for example
img_np.shape: (1200, 1920, 4)
Note: from the scripts above you would be tempted (I was) to use img_np.shape[2]
to retrieve the number of channels. However, if your image contains 1 channel (e.g., grayscale), that line would give you a problem (IndexError: tuple index out of range
). Instead with just a simple print of shape (as I did in my script) you will get something like this
img_np.shape: (1200, 1920)