Histogram
import matplotlib.pyplot as plt
from PIL import Image
# Grayscale Histogram
img = Image.open("test.png").convert("L")
hist = img.histogram()
plt.figure(figsize=(6, 4))
plt.bar(range(256), hist, color='gray')
plt.xlabel("Pixel value (0-255)")
plt.ylabel("Frequency")
plt.title("Grayscale Histogram")
plt.show()
# RGB Histogram
img = Image.open("test.png").convert("RGB")
hist = img.histogram()
plt.figure(figsize=(8, 4))
plt.plot(hist[0:256], color='r', label='Red')
plt.plot(hist[256:512], color='g', label='Green')
plt.plot(hist[512:768], color='b', label='Blue')
plt.xlabel("Pixel value (0-255)")
plt.ylabel("Frequency")
plt.title("RGB Histogram")
plt.legend()
plt.show()
Image processing
import numpy as np
from PIL import Image
img = Image.open("test.png")
arr = np.asarray(img)
arr.shape # (H, W) for gray, (H, W, 3) for RGB