MATLAB: How to fill rectangle with same color in image

fill colorImage Processing Toolboxrecognitionrectangle

Hi,
I want to fill rectangle with same color such as bellow image. So, i recognition it to rectangle or square.
Please, let me know.
Thanks.

Best Answer

I = imread('target1.png') ;
I1 = rgb2gray(I) ;
[y,x] = find(I1) ;
R = I(:,:,1) ; G = I(:,:,2) ; B = I(:,:,3) ;
x0 = min(x) ; x1 = max(x) ;
y0 = min(y) ; y1 = max(y) ;
[X,Y] = meshgrid(x0:x1,y0:y1) ;
idx = sub2ind(size(I1),Y(:),X(:)) ;
I2 = I ;
C = [mean(R(idx)) mean(G(idx)) mean(B(idx))] ;
for i = 1:3
T2 = I2(:,:,i) ;
T2(idx) = C(i) ;
I2(:,:,i) = T2 ;
end
imshow(I2)