我有一张尺寸为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);
Run Code Online (Sandbox Code Playgroud)
Lui*_*ndo 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));
Run Code Online (Sandbox Code Playgroud)
如果使用不支持的Matlab版本randi,请替换最后一行
crop = image_gray(ceil(rand*(n-L+1))+(0:L-1),ceil(rand*(m-L+1))+(0:L-1));
Run Code Online (Sandbox Code Playgroud)
对您的代码的评论:
image用作变量名称.它覆盖了一个函数.round(rand(1)*n)改为ceil(rand(1)*n).或者使用randi(n).randi(n),使用randi(n-L+1).那样你就避开了ifs.