MATLAB: I need to randomly add k = 1, 2, 3, . . . boxes of random gray color, each of size 50 × 50 at the image. Can you help please

boxes

I need to randomly add k = 1, 2, 3, . . . boxes of random gray color, each of size 50 × 50 at the image. Can you help please?Снимок экрана 2018-11-29 в 3.16.41.png

Best Answer

I = imread('peppers.png') ;
I = rgb2gray(I) ;
L = 50. ; % length of the box
B = 50. ; % breadth of the box
R = [0. 0. ; L 0. ; L B ; 0. B] ;
% random boxes at locations
N = 25 ; % number of boxes
idx = randsample(1:numel(I),N) ; % ten boxes
% get center
[idx,idy] = ind2sub(size(I),idx) ;
% draw coordinates
imshow(I)
hold on
for i = 1:N
patch(idx(i)+R(:,1),idy(i)+R(:,2),'k')
end