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

วิธีนับจำนวนช่องสีของภาพใน OpenCV C++

บทนำ

OpenCV มีเมธอด channels() สำหรับดูจำนวนช่องสีของภาพ (Mat) คืนค่าเป็น integer: 1=Grayscale, 3=BGR/RGB, 4=BGRA/RGBA

ตัวอย่างโค้ด

#include <iostream>
#include <opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;

int main() {
    Mat img = imread("colors.jpg");
    
    if (img.empty()) {
        cout << "โหลดภาพไม่สำเร็จ" << endl;
        return -1;
    }
    
    int numChannels = img.channels();
    cout << "จำนวนช่องสี = " << numChannels << endl;
    
    // แสดงข้อมูลเพิ่มเติม
    cout << "ขนาดภาพ: " << img.cols << "x" << img.rows << endl;
    cout << "ชนิดข้อมูล: " << img.type() << endl;
    cout << "Depth: " << img.depth() << endl;
    
    system("pause");
    waitKey(0);
    return 0;
}

ค่าที่เป็นไปได้ของ channels()

การตรวจสอบชนิดภาพแบบสมบูรณ์

// ตรวจสอบทั้ง depth และ channels
cout << "Type: " << img.type() << endl; // เช่น 16 = CV_8UC3
cout << "Depth: " << img.depth() << endl; // 0 = CV_8U
cout << "Channels: " << img.channels() << endl; // 3

// Macro ตรวจสอบชนิด
if (img.type() == CV_8UC3) { /* ภาพสี 8-bit 3 ช่อง */ }
if (img.type() == CV_8UC1) { /* ภาพขาวดำ 8-bit */ }

ผลลัพธ์

วิธีนับจำนวนช่องสีของภาพใน OpenCV C++

สรุป

เมธอด channels() ให้ข้อมูลจำนวนช่องสีอย่างรวดเร็ว สำคัญสำหรับการเขียนโค้ดที่รองรับหลายชนิดภาพ (Generic code) เช่น ตรวจสอบก่อนใช้ at<Vec3b> หรือ at<uchar>

ค่าความหมายตัวอย่าง
1Single Channel (Grayscale)CV_8UC1, CV_32FC1
22 ChannelsOptical Flow (x,y), Complex numbers
33 Channels (BGR, RGB, HSV, Lab, YCrCb)CV_8UC3 - ภาพสีมาตรฐาน
44 Channels (BGRA, RGBA)CV_8UC3 - ภาพมี Alpha channel