How do I create a gradient border around an image?
4 views (last 30 days)
Show older comments
I need to create a border around an image that would gradually change it's color from the image's color to white (a gradient).
Thank you.
0 Comments
Accepted Answer
Walter Roberson
on 11 May 2017
borderwidth = 7; %for example
[R, C, P] = size(YourImage);
augmented_col_coords = [-borderwidth+1, 1:C, C+borderwidth];
augmented_row_coords = [-borderwidth+1, 1:R, R+borderwidth];
resample_col_coords = -borderwidth+1 : C + borderwidth;
resample_row_coords = -borderwidth+1 : R + borderwidth;
extra_line = repmat(255, 1, C+2);
augmented_red = [extra_line; 255*ones(R,1), double(YourImage(:,:,1)), 255*ones(R,1); extra_line];
gradiented_red = uint8( interp2(augmented_col_coords, augmented_row_coords, augmented_red, resample_col_coords, resample_row_coords.') );
augmented_green = [extra_line; 255*ones(R,1), double(YourImage(:,:,2)), 255*ones(R,1); extra_line];
gradiented_green = uint8( interp2(augmented_col_coords, augmented_row_coords, augmented_green, resample_col_coords, resample_row_coords.') );
augmented_blue = [extra_line; 255*ones(R,1), double(YourImage(:,:,3)), 255*ones(R,1); extra_line];
gradiented_blue = uint8( interp2(augmented_col_coords, augmented_row_coords, augmented_red, resample_col_coords, resample_row_coords.') );
gradiented_image = cat(3, gradiented_red, gradiented_green, gradiented_blue);
6 Comments
Walter Roberson
on 20 May 2017
gradiented_blue = uint8( interp2(augmented_col_coords, augmented_row_coords, augmented_blue, resample_col_coords, resample_row_coords.') );
More Answers (1)
DGM
on 16 Jul 2022
Edited: DGM
on 16 Jul 2022
You could also do this by using inpainting tools.
Using IPT regionfill():
A = imread('peppers.png');
padwidth = [30 30];
outercolor = 255; % must be scalar (black/gray/white)
% create a mask to define the transition region
mk = false([size(A,1) size(A,2)]);
mk = padarray(mk,padwidth-1,1,'both');
mk = padarray(mk,[1 1],0,'both');
% pad the image
B = padarray(A,padwidth,outercolor,'both');
% inpaint based on the mask
for c = 1:size(B,3)
B(:,:,c) = regionfill(B(:,:,c),mk);
end
imshow(B)

A = imread('peppers.png');
padwidth = [30 30];
outercolor = 255; % must be scalar (black/gray/white)
% pad the image, using NaNs to define the transition region
B = padarray(double(A),padwidth-1,NaN,'both');
B = padarray(B,[1 1],outercolor,'both');
% inpaint based on NaNs
for c = 1:size(B,3)
B(:,:,c) = inpaint_nans(B(:,:,c),2);
end
B = uint8(B); % cast back to uint8
imshow(B)

Note that both of these examples assume that input image is class uint8.
0 Comments
See Also
Categories
Find more on Read, Write, and Modify Image in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


