如何使用C++在OpenCV中獲取特定畫素的值?
要讀取特定畫素的值,我們可以使用“at”方法或“直接訪問”方法。在這裡,我們將學習這兩種方法。
讓我們從“at”方法開始。下面的程式讀取RGB影像中(10, 29)位置的畫素值。
示例
#include<iostream>
#include<opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;
int main() {
Mat image;//taking an image matrix//
image = imread("sky.jpg");//loading an image//
int x = image.at<Vec3b>(10, 29)[0];//getting the pixel values//
int y = image.at<Vec3b>(10, 29)[1];//getting the pixel values//
int z = image.at<Vec3b>(10, 29)[2];//getting the pixel values//
cout << "Value of blue channel:" << x << endl;//showing the pixel values//
cout << "Value of green channel:" << x << endl;//showing the pixel values//
cout << "Value of red channel:" << x << endl;//showing the pixel values//
system("pause");//pause the system to visualize the result//
return 0;
}輸出

程式的結果將顯示在控制檯視窗中。在這裡,我們使用下面的三行程式碼獲取三個不同通道的畫素值。
int x = image.at<Vec3b>(10, 29)[0]; int y = image.at<Vec3b>(10, 29)[1]; int z = image.at<Vec3b>(10, 29)[2];
第一行讀取第一個通道(藍色)中(10, 29)位置的畫素值,並將值儲存在變數'x'中。第二行和第三行分別儲存第2個和第3個通道的值。現在讓我們學習如何使用“直接訪問”方法讀取畫素值。
下面的程式直接讀取(10, 29)位置的畫素值:
示例
#include<iostream>
#include<opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;
int main() {
Mat_<Vec3b>image;//taking an image matrix//
image = imread("sky.jpg");//loading an image//
Vec3b x = image(10, 29);//getting the pixel values//
cout << x << endl;//showing the pixel values//
system("pause");//pause the system to visualize the result//
return 0;
}輸出

廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP