2014-09-30 51 views
0

我想讀取RGB圖像。但是,我只能使用Vec3b類型訪問,而不是每個頻道。 我相信是什麼問題。想幫助我擺脫苦難嗎?如何訪問RGB圖像的每個像素值?

imgMod = imread("rgb.png"); 

for (int iter_x = 0; iter_x < imgMod.cols; ++iter_x) 
{ 
    for (int iter_y = 0; iter_y < imgMod.rows; ++iter_y) 
    { 
     cout << imgMod.at<cv::Vec3b>(iter_y, iter_x) << "\t"; 
     cout << imgMod.at<cv::Vec3b>(iter_y, iter_x)[0] << "\t"; 
     cout << imgMod.at<cv::Vec3b>(iter_y, iter_x)[1] << "\t"; 
     cout << imgMod.at<cv::Vec3b>(iter_y, iter_x)[2] << endl; 
    } 
} 

這是RGB圖像的像素值的結果。

[153, 88, 81]   X  Q 
[161, 94, 85] 。 ^ T 
... 

回答

3

您的訪問沒有問題。
[]運算符返回的類型爲char,因此該值將打印爲char - 一個文本字符。只需將它轉換爲int看到的灰度值作爲一個整數:

cout << int(imgMod.at<cv::Vec3b>(iter_y, iter_x)[0]) << "\t"; 

A(更具可讀性和明確的)C++的方式做這將是這樣的:

static_cast<int>(imgMod.at<cv::Vec3b>(iter_y, iter_x)[0]) << "\t"; 

更冷靜是這個(obscure?) little trick - 注意+

cout << +imgMod.at<cv::Vec3b>(iter_y, iter_x)[0] << "\t"; 
// ^
+0

謝謝!有效。順便說一下,int(imgMod.at (iter_y,iter_x)[0])和(int)imgMod.at (iter_y,iter_x)[0]之間有什麼區別嗎? – 2014-09-30 08:17:00

+0

很酷,那麼你可以將答案標記爲已回答。我不確定會有什麼區別。 (更可讀和明確的)C++方法是:'static_cast (imgMod.at (iter_y,iter_x)[0])''。 – 2014-09-30 08:34:38

+0

哦,我明白了!再次感謝:) – 2014-10-01 09:12:59