使用平均4个像素缩小图像



我刚刚开始学习图像处理和Matlab,我正在尝试使用平均4像素缩小图像。这意味着对于每4个原始像素,我计算平均值并产生1个输出像素。到目前为止,我有以下代码:

img = imread('bird.jpg');
row_size = size(img, 1);
col_size = size(img, 2);
res = zeros(floor(row_size/2), floor(col_size/2));
figure, imshow(img);
for i = 1:2:row_size
    for j = 1:2:col_size
        num = mean([img(i, j), img(i, j+1), img(i+1, j), img(i+1, j+1)]);
        res(round(i/2), round(j/2)) = num;
    end
end
figure, imshow(uint8(res));

这段代码设法缩小图像,但它将其转换为灰度。我知道我可能必须计算输出像素的RGB组件的平均值,但我不知道如何访问它们,计算平均值并将它们插入结果矩阵。

在Matlab中,RGB图像被视为3D数组。你可以用:

depth_size = size(img, 3)
depth_size =
     3

循环解决方案,正如您所做的那样,在Sardar_Usama的答案中进行了解释。然而,在Matlab中,每当您想要获得速度时,建议避免循环。

这是一个矢量化的解决方案,按n的系数缩小RGB图像:

img = imread('bird.jpg');
n = 2; % n can only be integer
[row_size, col_size] = size(img(:, :, 1));
% getting rid of extra rows and columns that won't be counted in averaging:
I = img(1:n*floor(row_size / n), 1:n*floor(col_size / n), :);
[r, ~] = size(I(:, :, 1));
% separating and re-ordering the three colors of image in a way ...
% that averaging could be done with a single 'mean' command:
R = reshape(permute(reshape(I(:, :, 1), r, n, []), [2, 1, 3]), n*n, [], 1);
G = reshape(permute(reshape(I(:, :, 2), r, n, []), [2, 1, 3]), n*n, [], 1);
B = reshape(permute(reshape(I(:, :, 3), r, n, []), [2, 1, 3]), n*n, [], 1);
% averaging and reshaping the colors back to the image form:
R_avg = reshape(mean(R), r / n, []);
G_avg = reshape(mean(G), r / n, []);
B_avg = reshape(mean(B), r / n, []);
% concatenating the three colors together:
scaled_img = cat(3, R_avg, G_avg, B_avg); 
% casting the result to the class of original image
scaled_img = cast(scaled_img, 'like', img); 

基准:

如果你想知道为什么矢量化解决方案更受欢迎,看看用这两种方法处理RGB 768 x 1024图像需要多长时间:

------------------- With vectorized solution:
Elapsed time is 0.024690 seconds.
------------------- With nested loop solution:
Elapsed time is 6.127933 seconds.

所以两个解的速度差大于2个数量级

另一个可能的解决方案是使用此链接中提到的blockproc函数。这也将避免for循环。

您可以使用下面修改的代码来处理:

img = imread('bird.jpg');
row_size = size(img, 1);
col_size = size(img, 2);
figure, imshow(img);
res = zeros(floor(row_size/2), floor(col_size/2), 3); %Pre-allocation
for p = 1:2:row_size
    for q = 1:2:col_size
        num = mean([img(p, q,:), img(p, q+1,:), img(p+1, q,:), img(p+1, q+1,:)]);
        res(round(p/2), round(q/2),:) = num;
    end
end
figure, imshow(uint8(res));

我用上面的代码将1200x1600x3 uint8转换为600x800x3 uint8的样本图像,这是正确的,因为(1200*1600)/4 = 480000600*800 = 480000

p。S:我将变量名ij分别改为pq,因为ij是为 imaginary numbers 保留的。

最新更新