การเข้าถึงค่า Pixel ของภาพเป็นขั้นตอนพื้นฐานใน Image Processing ภาพ RGB มี 3 Channels (R,G,B) หรือ 4 Channels (RGBA) เก็บใน 3D Array (Height, Width, Channels)
ใช้ flatten() แปลง 3D Array → 1D Array แล้วใส่ DataFrame เพื่อวิเคราะห์/แสดงผล
ตัวอย่างโค้ด
from skimage import io
import pandas as pd
import matplotlib.pyplot as plt
# Path ของไฟล์ภาพ (ปรับตามจริง)
path = "puppy.png"
# อ่านภาพ
img = io.imread(path)
print("Image shape:", img.shape)
print("Image dtype:", img.dtype)
# แสดงภาพ
plt.imshow(img)
plt.title("Original Image")
plt.axis('off')
plt.show()
# แปลงเป็น DataFrame
# flatten(): (H, W, C) → (H*W*C,)
pixel_df = pd.DataFrame(img.flatten(), columns=['Pixel_Value'])
print("Pixel DataFrame shape:", pixel_df.shape)
print("\nFirst 10 pixels:")
print(pixel_df.head(10))
print("\nStatistics:")
print(pixel_df.describe())
# หากเป็น RGB แยก Channel
if img.ndim == 3 and img.shape[2] >= 3:
# Reshape เป็น (H*W, C)
pixels_2d = img.reshape(-1, img.shape[2])
pixel_df_rgb = pd.DataFrame(pixels_2d, columns=['R', 'G', 'B'])
print("\nRGB Channels Statistics:")
print(pixel_df_rgb.describe())
ผลลัพธ์ตัวอย่าง
Image shape: (397, 558, 4)
Image dtype: uint8
Pixel DataFrame shape: (886104, 1)
First 10 pixels:
Pixel_Value
0 123
1 145
2 167
...
Statistics:
Pixel_Value
count 886104.0
mean 128.5
std 45.2
min 0.0
25% 95.0
50% 130.0
75% 165.0
max 255.0
คำอธิบาย
io.imread()อ่านภาพคืน NumPy Array (H, W, C)img.shapeแสดง Resolution และ Channelsimg.flatten()แปลงเป็น 1D Array (H×W×C Elements)สร้าง DataFrame เพื่อวิเคราะห์สถิติ, Histogram, Filtering ฯลฯ
สำหรับ RGB: ใช้
reshape(-1, 3)แทน flatten เพื่อแยก Channel
ข้อมูลเพิ่มเติม: โครงสร้างภาพ
| ประเภทภาพ | Shape | Channels | Dtype ปกติ |
|---|---|---|---|
| Grayscale | (H, W) | 1 | uint8 (0-255) |
| RGB | (H, W, 3) | 3 | uint8 / float (0-1) |
| RGBA | (H, W, 4) | 4 (Alpha) | uint8 |
การเข้าถึง Pixel เฉพาะจุด
# Pixel ที่ (row=100, col=200)
pixel = img[100, 200] # Array([R, G, B]) หรือ Scalar (Grayscale)
red = img[100, 200, 0] # Channel R
green = img[100, 200, 1] # Channel G
blue = img[100, 200, 2] # Channel B
# Region of Interest (ROI)
roi = img[50:150, 100:200] # Crop 100x100 pixels
หมายเหตุ: ตัวอย่างต้นฉบับใช้ Path "path to puppy.PNG" ต้องเปลี่ยนเป็น Path จริงของไฟล์