บทนำ
ภาพดิจิタルประกอบด้วยพิกเซล ใน OpenCV การอ่านค่าพิกเซลง่าย แต่ภาพหลายช่องสีต้องจัดการแยกช่อง สำหรับภาพ Single Channel (Grayscale) การเข้าถึงตรงไปตรงมากกว่า
ตัวอย่างโค้ด: อ่านค่าพิกเซลทั้งภาพ
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main() {
int pixelValue;
Mat colorImg = imread("colors.jpg");
Mat grayImg;
// แปลง BGR เป็น Grayscale
cvtColor(colorImg, grayImg, COLOR_BGR2GRAY);
// วนลูปอ่านค่าพิกเซลทุกจุด
for (int i = 0; i < grayImg.rows; i++) {
for (int j = 0; j < grayImg.cols; j++) {
pixelValue = (int)grayImg.at<uchar>(i, j);
cout << "ค่าพิกเซล(" << i << "," << j << ") = " << pixelValue << endl;
}
}
imshow("Show", grayImg);
waitKey();
return 0;
}
จุดสำคัญ
- cvtColor(..., COLOR_BGR2GRAY): แปลงภาพสี 3 ช่องเป็น Grayscale 1 ช่อง
- grayImg.at<uchar>(i, j): เข้าถึงพิกเซลแบบ single channel (uchar = 0-255)
- i = row (แถว), j = col (คอลัมน์): OpenCV ใช้ (row, col) = (y, x)
- CV_8UC1: ชนิดข้อมูลของภาพ Grayscale (8-bit unsigned, 1 channel)
วิธีที่เร็วกว่า: Pointer Access
for (int i = 0; i < grayImg.rows; i++) {
uchar* rowPtr = grayImg.ptr<uchar>(i);
for (int j = 0; j < grayImg.cols; j++) {
pixelValue = rowPtr[j];
// ประมวลผล...
}
}
ผลลัพธ์

สรุป
การอ่านพิกเซลภาพ Single Channel ใช้ at<uchar>(row, col) สำหรับความปลอดภัย หรือ Pointer method สำหรับความเร็ว สำคัญคือต้องแปลงภาพสีเป็น Grayscale ก่อนด้วย cvtColor()