I have a gray image of size 400 x 600 . And i want to select randomly from this image, a patch of size 50 x 50.
By the way, i tried to write a code for this, and it worked fine. But according to my code below, there is another solution ? In other words, is there another code which can be more sexy than my own code ?
clear all;
close all;
clc;
image=imread('my_image.jpg');
image_gray=rgb2gray(image);
[n m]= size(image_gray); % 400 x600
L=50;
x=round(rand(1)*n); % generate a random integer between 1 and 400
y=round(rand(1)*m); % generate a random integer between 1 and 600
%verify if x is > than 400-50 , because if x is equal to 380 for example, so x+50 become %equal to 430, it exceeds the matrix dimension of image...
if(x<=n-L)
a=x:x+(L-1);
else
a=x-(L-1):x;
end
if(y<=m-L)
b=y:y+(L-1);
else
b=y-(L-1):y;
end
crop=image_gray(a,b);
figure(1);
imshow(crop);
This is as "sexy" as it gets. Satisfaction guaranteed ;-)
% Data
img=imread('my_image.jpg');
image_gray=rgb2gray(img);
[n m]= size(image_gray);
L = 50;
% Crop
crop = image_gray(randi(n-L+1)+(0:L-1),randi(m-L+1)+(0:L-1));
If using a Matlab version that doesn't support randi
, substitute last line by
crop = image_gray(ceil(rand*(n-L+1))+(0:L-1),ceil(rand*(m-L+1))+(0:L-1));
Comments to your code:
image
as a variable name. It overrides a function.round(rand(1)*n)
to ceil(rand(1)*n)
. Or use randi(n)
.randi(n)
, use randi(n-L+1)
. That way you avoid the if
s. For anyone struggling to get this code to work for RGB images, when you compute the size you'll want to add an extra variable for the third dimension. i.e.
% Data
img=imread('my_image.jpg');
% Not making anything gray anymore
[n, m, ~]= size(img);
L = 50;
% Crop - add a : in order to get 3 or more dimensions at the end
crop = img(randi(n-L+1)+(0:L-1),randi(m-L+1)+(0:L-1), :);
Super simple but not necessarily obvious at first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With