2013-02-28 43 views
4

我試圖從Mat對象中獲取像素。爲了測試,我嘗試在一個正方形上繪製一條對角線,並期望從左上角到右下角獲得完美的直線。通過Mat獲取像素::在

for (int i =0; i<500; i++){ 
    //I just hard-coded the width (or height) to make the problem more obvious 

    (image2.at<int>(i, i)) = 0xffffff; 
    //Draw a white dot at pixels that have equal x and y position. 
} 

但是,結果並不如預期。 這是在彩色照片上繪製的對角線。 enter image description here 這是一張灰度圖。 enter image description here 任何人都看到問題?

+0

哦,是的,每個人都看到了問題。 – qPCR4vir 2013-02-28 08:27:21

+0

@ qPCR4vir圖像不是500x500? – 2013-02-28 08:29:46

+0

其700 * 700,但結果與任何數字保持不變。 – 2013-02-28 08:30:38

回答

3
(image2.at<int>(i, i)) = 0xffffff; 

它看起來像你的彩色圖像是24位,但你的尋址像素在整數似乎是32位。

+0

那也是爲什麼當你切換到8bit時錯誤增加 – sean3k 2013-02-28 08:32:58

+0

哦,傻了。 因此,我無法直接設置像素值,而無需通過所有紅色,綠色和藍色通道? (我相信比設置一個值慢3倍) – 2013-02-28 08:34:42

+0

也許image2.at (i,i)= 0xffffff;我不確定,因爲我不知道你使用的這個圖形框架。我只是根據Riccardi的回答來猜測。 – sean3k 2013-02-28 08:37:03

6

問題是,您試圖以int(每像素32位)的方式訪問每個像素,而您的圖像是3通道無符號字符(每像素24位)或1通道無符號字符每像素8位圖像)爲灰度級。 您可以嘗試訪問每個像素喜歡本作的灰階一個

for (int i =0; i<image2.width; i++){ 
    image2.at<unsigned char>(i, i) = 255; 
} 

或喜歡本作的顏色一個

for (int i =0; i<image2.width; i++){  
     image2.at<Vec3b>(i, i)[0] = 255; 
     image2.at<Vec3b>(i, i)[1] = 255; 
     image2.at<Vec3b>(i, i)[2] = 255; 
} 
+0

很酷,謝謝。 我以爲我可以通過使用'int'一次設置所有通道來加速它。 – 2013-02-28 08:36:46