gpt4 book ai didi

image - Matlab - 使用四个像素的平均值缩小图像

转载 作者:行者123 更新时间:2023-12-02 20:56:48 26 4
gpt4 key购买 nike

我刚刚开始学习图像处理和 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's answer中进行了解释。 。但是,在 Matlab 中,建议您在想要提高速度时避免循环。

这是一种矢量化解决方案,可将 RGB 图像缩小 n 倍:

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 个数量级。

关于image - Matlab - 使用四个像素的平均值缩小图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39975720/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com