2010-10-31 93 views
1

我正在使用Octave分析一些圖像。現在我使用兩個嵌套的for-loops來訪問每個像素,但這非常慢。快速訪問Octave中的像素

我的代碼是類似的東西:

for i = 1:size(im,1) 
    for j = 1:size(im,2) 
    p = im(i,j,1:3); 
     if (classRGB(class, [p(1),p(2),p(3)]) > 0) 
      ## Apply some function to that pixel here 
     endif 
    endfor 
endfor 

有沒有辦法做到這一點,而不在八度的循環?

在此先感謝。

回答

0

我在Octave中沒有知識,但在其他語言中,最快的方法是獲取指向表示圖像像素的字節數組的指針並進行迭代。例如一些僞代碼,假設UINT8顏色尺碼:

 
uint8 *ptr = getBytes(image); 
foreach row{ 
    for each pixel{ 
     Red = *ptr; ptr++; 
     Green = *ptr; ptr++; 
     Blue = *prr; ptr++; 
     do something with Red, Green, Blue (or Alpha) 
    } 
} 

你必須小心知道你填充圖像數據類型使用在每一行的末尾。

+0

據我所知,這不能在Octave中完成。不過謝謝。 – OctaveNoob 2010-11-01 09:55:35

+0

出於性能原因,您總是可以與C++代碼進行交互。 – Ross 2010-11-01 13:26:31

+0

抱歉,該項目必須在Octave中完成。我目前的解決方案效果很好,但速度很慢。我認爲我必須做一些代碼向量化,但我只是不知道如何。 – OctaveNoob 2010-11-01 20:05:47

4

我建議採取更面向矩陣的方法。使用循環時,MATLAB/Octave非常慢。

例如,讓我們說,我想創建RGB圖像,其中其灰度轉換值的像素(0.3 * R + 0.6 * G + 0.1 * B)小於或等於128被設置爲零:

# Read a 512x512 RGB image. 
# Resulting matrix size is [512 512 3] 
im = imread('lena_rgb.png'); 

# Compute grayscale value (could be done more accurately with rgb2gray). 
# Resulting matrix size is [512 512 1] (same as [512 512]) 
grayval = 0.3*im(:,:,1) + 0.6*im(:,:,2) + 0.1*im(:,:,3); 

# Create a bitmask of grayscale values above 128 
# Contains 0 if less than or equal than 128, 1 if greater than 128 
# Resulting matrix size is [512 512 1] (same as [512 512]) 
mask = (grayval > 128); 

# Element-wise multiply the mask with the input image to get the new RGB image 
# Resulting matrix size is [512 512 3] 
result = im.* repmat(mask, [1 1 3]); 

我建議在Octave中學習更多關於矩陣操作,算術和尋址的知識。我包含了我的示例的原始和結果圖像以供參考。 Original Image Result Image

+0

這正是我所需要的。謝謝 – OctaveNoob 2010-11-01 21:06:36

+0

[此前一個問題](http://stackoverflow.com/q/2470844/448455)爲MATLAB/Octave性能改進提供了有用的鏈接:[代碼矢量化指南](http://www.mathworks.com/support/ tech-notes/1100/1109.html)和[提高性能的技巧](http://www.mathworks.com/help/techdoc/matlab_prog/f8-784135.html)。 – 2010-11-01 21:11:40

0

您需要告訴我們什麼classRGB會做什麼。否則,沒有人可以幫助你。如果classRGB可以一次計算值的矩陣,您可以直接通過矩陣im(:,:,1:3)

+0

我已經實現了Jaime的答案,並且工作得很好。但是,謝謝你的興趣 – OctaveNoob 2010-11-19 10:07:04