Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

วิธี Invert ภาพ Binary ใน OpenCV C++

บทนำ

การ Invert ภาพ Binary หมายถึงการกลับค่าพิกเซล: สีขาว (255) กลายเป็นสีดำ (0) และสีดำกลายเป็นสีขาว ใช้ฟังก์ชัน bitwise_not()

ขั้นตอนการทำงาน

  1. โหลดภาพต้นฉบับ
  2. แปลงเป็น Grayscale: cvtColor(src, gray, COLOR_BGR2GRAY)
  3. แปลงเป็น Binary: threshold(gray, binary, 100, 255, THRESH_BINARY)
  4. 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

ผลลัพธ์

วิธี Invert ภาพ Binary ใน OpenCV C++

การประยุกต์ใช้

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