Select a random patch from an image using matlab
matlab
Solution
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 `if`s.
Problem
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); ```