บทนำ
การ Invert ภาพ Binary หมายถึงการกลับค่าพิกเซล: สีขาว (255) กลายเป็นสีดำ (0) และสีดำกลายเป็นสีขาว ใช้ฟังก์ชัน bitwise_not()
ขั้นตอนการทำงาน
- โหลดภาพต้นฉบับ
- แปลงเป็น Grayscale:
cvtColor(src, gray, COLOR_BGR2GRAY) - แปลงเป็น Binary:
threshold(gray, binary, 100, 255, THRESH_BINARY) - Invert:
bitwise_not(binary, inverted)
ตัวอย่างโค้ด
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv;
using namespace std;
int main() {
Mat original, gray, binary, inverted;
namedWindow("Binary Image");
namedWindow("Inverted Binary Image");
original = imread("mountain.jpg");
cvtColor(original, gray, COLOR_BGR2GRAY);
threshold(gray, binary, 100, 255, THRESH_BINARY);
bitwise_not(binary, inverted);
imshow("Binary Image", binary);
imshow("Inverted Binary Image", inverted);
waitKey(0);
return 0;
}
อธิบายฟังก์ชันสำคัญ
threshold()
threshold(src, dst, thresh, maxval, type);
- thresh=100: ค่าเกณฑ์ พิกเซล > 100 จะกลายเป็น maxval
- maxval=255: ค่าสูงสุดที่กำหนดให้
- THRESH_BINARY: โหมด Binary (มากกว่าเกณฑ์=maxval, น้อยกว่า=0)
bitwise_not()
bitwise_not(src, dst);
- กลับบิตทุกบิต: 0→255, 255→0 (สำหรับ 8-bit)
- เทียบเท่า: dst = 255 - src
ผลลัพธ์

การประยุกต์ใช้
- สร้าง Mask สำหรับ Background/Foreground
- Preprocessing สำหรับ OCR (ข้อความสีดำพื้นขาว)
- Morphological Operations ต้องการภาพ Binary ที่ถูกต้อง
- Invert เพื่อให้ Object เป็นสีขาวบนพื้นดำ (มาตรฐานบาง Library)