使用matlab从图像中选择随机补丁

时间:2013-12-03 11:46:51

标签: matlab

我的尺寸为400 x 600的灰色图像。我想从这张图片中选择随机,这是一张尺寸为50 x 50的补丁。

顺便说一下,我试着为此编写一个代码,它运行正常。但根据我的下面的代码,还有另一种解决方案吗?换句话说,还有另一个代码可以比我自己的代码更性感吗?

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);

2 个答案:

答案 0 :(得分:15)

这就像它的“性感”一样。满意保证; - )

% 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));

如果使用不支持randi的Matlab版本,请用

替换最后一行
crop = image_gray(ceil(rand*(n-L+1))+(0:L-1),ceil(rand*(m-L+1))+(0:L-1));

对您的代码的评论:

  • 您不应将image用作变量名称。它覆盖了一个函数。
  • 您应该将round(rand(1)*n)更改为ceil(rand(1)*n)。或者使用randi(n)
  • 使用randi(n)而不是randi(n-L+1)。这样你就可以避免if了。

答案 1 :(得分:1)

对于那些努力使此代码适用于RGB图像的人来说,当您计算尺寸时,您需要为第三维添加额外的变量。即。

% 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), :);

超级简单,但最初并不一定明显。