Skip to content

Instantly share code, notes, and snippets.

@liuhh02
Last active June 30, 2023 15:51
Show Gist options
  • Save liuhh02/ade48d822139006f98d8f05681209ab6 to your computer and use it in GitHub Desktop.
Save liuhh02/ade48d822139006f98d8f05681209ab6 to your computer and use it in GitHub Desktop.
Find number of channels in your image
"""
num_channels.py
Find number of channels in your image.
Author: liuhh02 https://machinelearningtutorials.weebly.com/
"""
from PIL import Image
import numpy as np
# name of your image file
filename = './directory/to/image/file/image.tif'
# open image using PIL
img = Image.open(filename)
# convert to numpy array
img = np.array(img)
# find number of channels
if img.ndim == 2:
channels = 1
print("image has 1 channel")
else:
channels = image.shape[-1]
print("image has", channels, "channels")
@hchen98
Copy link

hchen98 commented Feb 12, 2022

On line 25 where you have image.shape[-1], I believe it should be img.shape[-1] because shape is part of NumPy's attribute, not PIL image object.

@pradoz
Copy link

pradoz commented Jul 28, 2022

@hchen98 thanks!

@vmirea
Copy link

vmirea commented Dec 21, 2022

I needed to change the image to img = cv2.imread(filename) because the img in your code has no attribute ndim

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment