drying to scale down image by factor of 2 using loops

4 vues (au cours des 30 derniers jours)
Freja
Freja le 10 Août 2023
Modifié(e) : DGM le 10 Août 2023
Hi, Ive been stuck trying to figure out how to scale down a greyscale image using loops and the mean function. This is what I am doing so far which I know is incorrect but Im just really struggling with getting the values from the 2D array input and seperating it into multiple smaller arrays to then take the mean of them.
function [HalfmyIm] = HalveImage(myIm)
%UNTITLED2 Summary of this function goes here
% Detailed explanation goes here
%myIm=uint8(myIm);
[rows, cols]=size(myIm);
mean_values = zeros(2,2);
for i= 1:rows
for j= 1:cols
% Half(i,j)=myIm(i:i+1, j:j+1)
% mean(Half(i,j))
r_idx = [i i+1]
c_idx = [j j+1]
smallA= myIm(r_idx, c_idx);
mean_values(i, j) = mean(smallA(:));
end
end
disp(mean_values);
end

Réponses (1)

DGM
DGM le 10 Août 2023
Modifié(e) : DGM le 10 Août 2023
I'm going to generalize a little bit. Scaling factor can be set as an internal parameter. The code supports any number of image channels. This can be turned into a function as needed.
inpict = imread('peppers.png');
% the main parameter
rsfactor = 4; % i'm using 4 so the change is noticeable on the forum
% the last output of size() is a product term, not strictly a size
[rows, cols, chans, ~] = size(inpict);
% make sure the size is compatible with the scaling factor
if any(mod([rows cols],rsfactor))
error('HALVEIMAGE: page geometry must be an integer multiple of %d',rsfactor)
end
% preallocate output image to the same class as the input
outpict = zeros(rows/rsfactor,cols/rsfactor,chans,class(inpict));
% increment in steps of rsfactor
for i = rsfactor:rsfactor:rows
for j = rsfactor:rsfactor:cols
% get sample region
r_idx = (i-rsfactor+1):i;
c_idx = (j-rsfactor+1):j;
smallA = inpict(r_idx, c_idx, :); % all channels
% average on first two dimensions only
outpict(i/rsfactor, j/rsfactor, :) = mean(smallA,1:2);
end
end
size(inpict)
ans = 1×3
384 512 3
size(outpict)
ans = 1×3
96 128 3
imshow(outpict)

Catégories

En savoir plus sur Green dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by