How would find the average within each region?
Show older comments
This code generates regions within a user defined image. I want to find the average value within each region and save it as a new image.
clc,clear, close all
% Load the grayscale image
img = imread('peppers.png'); % Replace with your file path
img = rgb2gray(img);
img = mat2gray(img);
threshold = 0.05; % Adjust this value for different levels of similarity
% Ensure the dimensions are a power of 2 by padding
[m, n] = size(img);
M = 2^nextpow2(m); % Nearest power of 2 greater than or equal to m
N = 2^nextpow2(n); % Nearest power of 2 greater than or equal to n
paddedImg = padarray(img, [M-m, N-n], 'post');
% Initialize the quadtree decomposition
quadtreeDecomp(paddedImg, threshold);
function quadtreeDecomp(img, threshold)
% Display the image
imshow(img, 'InitialMagnification', 'fit');
hold on;
% Call recursive function for quadtree decomposition
recursiveSplit(img, [1, 1], size(img, 1), threshold);
hold off;
end
function recursiveSplit(img, origin, sizeBlock, threshold)
% Extract the current block
x = origin(1);
y = origin(2);
block = img(x:x+sizeBlock-1, y:y+sizeBlock-1);
% Check homogeneity (using variance)
if std2(block) > threshold && sizeBlock > 4
% Split into four sub-blocks
halfSize = sizeBlock / 2;
% Recursively process each sub-block
recursiveSplit(img, [x, y], halfSize, threshold); % Top-left
recursiveSplit(img, [x, y+halfSize], halfSize, threshold); % Top-right
recursiveSplit(img, [x+halfSize, y], halfSize, threshold); % Bottom-left
recursiveSplit(img, [x+halfSize, y+halfSize], halfSize, threshold); % Bottom-right
else
% Draw rectangle for this block
rectangle('Position', [y, x, sizeBlock, sizeBlock], 'EdgeColor', 'r', 'LineWidth', 0.5);
end
end

Accepted Answer
More Answers (0)
Categories
Find more on Neighborhood and Block Processing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!