Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a random patch from an image using matlab

Tags:

matlab

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);
like image 917
Christina Avatar asked Dec 03 '13 11:12

Christina


2 Answers

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:

  • You shouldn't use image as a variable name. It overrides a function.
  • You should change round(rand(1)*n) to ceil(rand(1)*n). Or use randi(n).
  • Instead of randi(n), use randi(n-L+1). That way you avoid the ifs.
like image 66
Luis Mendo Avatar answered Oct 03 '22 02:10

Luis Mendo


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.

like image 23
Luke Murray Avatar answered Oct 03 '22 00:10

Luke Murray