# Random square sampling for single channel images

4 views (last 30 days)
len Bruce on 28 Dec 2020
Answered: len Bruce on 28 Dec 2020
For a single-channel image with random square sampling, Not a fixed sub-window，how to generate random squares usingMATLAB, an example is as follows，Thank you Subhadeep Koley on 28 Dec 2020
Hi, here is one working example.
Hope this helps!
[row, col, ~] = size(img);
imgSize = [row, col];
% Specify dimension of the random square
squareSize = [50, 50];
% Calculate crop rectangle
maximumPosValue = (imgSize - squareSize + 1);
initialRandomPos = [randi(maximumPosValue(1)), randi(maximumPosValue(2))];
cropRect = [initialRandomPos(2), initialRandomPos(1), squareSize(2)-1, squareSize(1)-1];
% Crop the image
imgCropped = imcrop(img, cropRect);
% Visualize results
out = imtile({img, imgCropped}, 'BackgroundColor', 'w');
figure
imshow(out)
title('Original image | Random cropped image');
##### 2 CommentsShowHide 1 older comment
Subhadeep Koley on 28 Dec 2020
@len Bruce you can randomize the sqare window size like below.
[row, col, ~] = size(img);
imgSize = [row, col];
% Specify dimension of the random square
val = randi(min(imgSize));
squareSize = [val, val];
% Calculate crop rectangle
maximumPosValue = (imgSize - squareSize + 1);
initialRandomPos = [randi(maximumPosValue(1)), randi(maximumPosValue(2))];
cropRect = [initialRandomPos(2), initialRandomPos(1), squareSize(2)-1, squareSize(1)-1];
% Crop the image
imgCropped = imcrop(img, cropRect);
% Visualize results
out = imtile({img, imgCropped}, 'BackgroundColor', 'w');
figure
imshow(out)
title('Original image | Random cropped image');

len Bruce on 28 Dec 2020
Generate the coordinates of the image square sampling based on random numbers，such as the upper left and the lower right co-ordinates of the ith random sub-window is denoted by （x1,y1）and (x2,y2)respectively. (image(x1:x2, y1:y2))