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