Chuyển đổi không gian màu RGB → Grayscale thường dùng làm tiền xử lý để giảm độ phức tạp, tách độ sáng (luminance).
Công thức luminance chuẩn (ITU-R BT.601)
Y = 0.2125 * R + 0.7154 * G + 0.0721 * B
Trọng số phản ánh độ nhạy mắt người: xanh lá > đỏ > xanh dương.
Ví dụ với scikit-image
from skimage import io, color
import matplotlib.pyplot as plt
path = "path/to/puppy_1.JPG"
orig_img = io.imread(path)
grayscale_img = color.rgb2gray(orig_img)
fig, axes = plt.subplots(1, 2, figsize=(8, 4))
ax = axes.ravel()
ax[0].imshow(orig_img); ax[0].set_title("Ảnh gốc RGB")
ax[1].imshow(grayscale_img, cmap=plt.cm.gray); ax[1].set_title("Ảnh xám")
fig.tight_layout()
plt.show()
Giải thích
color.rgb2grayáp dụng công thức luminance, trả về mảng float [0,1].cmap=plt.cm.grayhiển thị thang xám.- Mất thông tin màu (hue, saturation), chỉ giữ độ sáng.
Lưu ý
Nếu ảnh đã là grayscale (2D), rgb2gray sẽ báo lỗi. Kiểm tra img.ndim trước khi chuyển.