This script works by using intensity thresholding to choose how to color certain areas of the image. It intelligently divides the image into regions, and paints the regions with the average RGB values present there.
Initialize
clc ; clear ; close all
image = 'climb.jpg' ;
% There is a bit of hyperparameter tuning with this script. the
% smooth_factor represents how much to smooth the intensity histogram, and
% the peak_prom is the prominence of valleys in the intensity histogram to
% treat as a separate bin.
smooth_factor = 20 ;
peak_prom = 10000 ;
Load the Image
im = imread ( image );
% im = rot90(im,-1); % Some images need to be rotated
im_gray = rgb2gray ( im ); % Convert to grayscale
Histogram
Create a histogram of intensity values and smooth it.
[ counts , binLocations ] = imhist ( im_gray );
c = smooth ( counts , smooth_factor );
Identify Bins
symm = [ flipud ( c ); c ; flipud ( c )];
[ ~ , loc ] = findpeaks ( symm , 'MinPeakProminence' , peak_prom );
peaks = loc ( loc - 256 & gt ; 0 & amp ; loc - 256 & lt ; = 256 ) - 256 ;
symm = max ( symm ) - symm ;
[ ~ , loc ] = findpeaks ( symm , 'MinPeakProminence' , peak_prom );
valleys = loc ( loc - 256 & gt ; = 0 & amp ; loc - 256 & lt ; = 256 ) - 256 ;
if valleys ( 1 ) == 0
valleys ( 1 ) = 1 ;
endif valleys ( end ) ~= 256
valleys = [ valleys ; 256 ];
endif peaks ( 1 ) == 0
peaks ( 1 ) = 1 ;
endif peaks ( end ) ~= 256
peaks = [ peaks ; 256 ];
end
ind = valleys ;
Average RGB Values
new_im = im ;
r = new_im (:,:, 1 );
g = new_im (:,:, 2 );
b = new_im (:,:, 3 );
new_r = r ;
new_g = g ;
new_b = b ;
for i = 1 : length ( ind ) - 1
t1 = ( ind ( i ) - 1 );
t2 = ( ind ( i + 1 ) - 1 );
img = im_gray & gt ; t1 & amp ; im_gray & lt ; t2 ;
mask = not ( logical ( img ));
r_i = r ( mask );
g_i = g ( mask );
b_i = b ( mask );
cols = [ mean ( r_i ) mean ( g_i ) mean ( b_i )];
new_r ( mask ) = cols ( 1 );
new_g ( mask ) = cols ( 2 );
new_b ( mask ) = cols ( 3 );
end
new_im (:,:, 1 ) = new_r ;
new_im (:,:, 2 ) = new_g ;
new_im (:,:, 3 ) = new_b ;
Results
figure
imshow ( im );
figure
imshow ( new_im );
Warning : Image is too big to fit on screen ; displaying at 25 %
Warning : Image is too big to fit on screen ; displaying at 25 %
Published with MATLABĀ® R2018a