2

我正在使用 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 中的循环,有什么方法可以做到这一点?

提前致谢。

4

3 回答 3

6

我建议采用更面向矩阵的方法。使用循环时,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中学习更多关于矩阵操作、算术和寻址的知识。我包含了示例的原始图像和结果图像以供参考。 原始图像 结果图像

于 2010-11-01T21:02:25.090 回答
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)
    } 
}

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

于 2010-11-01T07:43:09.773 回答
0

你需要告诉我们做什么classRGB。否则没有人可以帮助你。如果classRGB可以一次计算值矩阵,则可以直接传递矩阵im(:,:,1:3)

于 2010-11-14T20:13:07.050 回答