在Octave中快速访问像素

时间:2010-10-31 20:27:33

标签: image pixel octave

我使用Octave来分析一些图像。现在我使用两个嵌套的for循环来访问每个像素,但这确实很慢。

我的代码是这样的:

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

如果没有Octave中的循环,有没有办法做到这一点?

提前致谢。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)
    } 
}

您必须小心了解图像数据类型在每行末尾使用的填充。

答案 2 :(得分:0)

您需要告诉我们classRGB的作用。否则没有人可以帮助你。如果可以同时为值矩阵计算classRGB,则可以直接传递矩阵im(:,:,1:3)