matlab白底换红底

白底换红底

局部阈值调整

边界高斯滤波

function demo

global R
global threshold
global img
global dstColor
global rect
global mask
global biasStep


biasStep = 5;
dstColor = [255 0 0]; %% background color
img = imread('g.jpg'); %% load photo
R = img(:,:,1);
[mm, nn] = size(R);
rect = [1 1 nn, mm];

threshold = 200 * ones(mm, nn); %% init threshold
figure('KeyReleaseFcn',@processCMD);
mask = R < threshold;  %% init mask
processImg(img, mask, rect, dstColor);
text(20, 20, sprintf('Threshold : %d', threshold(1)))


function processCMD(src, evnt)
global R
global threshold
global img
global dstColor
global rect
global mask
global biasStep

if strcmp(evnt.Key, 'uparrow')   
    threshold = changeThreshold(threshold, rect, biasStep);
    mask = R < threshold;   
    processImg(img, mask, rect, dstColor);    
    
elseif strcmp(evnt.Key, 'downarrow')    
    threshold = changeThreshold(threshold, rect, - biasStep);
    mask = R < threshold;
    processImg(img, mask, rect, dstColor);  
    
elseif strcmp(evnt.Key, 'leftarrow')    
    if biasStep > 2
        biasStep = biasStep - 1;
        processImg(img, mask, [], dstColor);    
    end
elseif strcmp(evnt.Key, 'rightarrow')    
    biasStep = biasStep + 1;   
    processImg(img, mask, [], dstColor);    
elseif strcmp(evnt.Key, 'space')        
    %% select rect
    processImg(img, mask, [], dstColor);    
    rect = floor(getrect());    
    processImg(img, mask, rect, dstColor);
elseif strcmp(evnt.Key, 'g')    
    I = processImg(img, mask, [], dstColor);        
    %% gaussian filter
    G = fspecial('gaussian',[5 5],2);
    Ig = imfilter(I,G,'same');
    eg = repmat(imdilate(edge(mask), strel('diamond', 5)), [1 1 3]);    
    I(eg) = Ig(eg);
    imshow(I, []);  
    imwrite(I, 'output.jpg')
    
else
    disp('unkown command')
    disp(evnt.Key)
    
end
tmp = threshold(rect(2) : rect(2) + rect(4) - 1, rect(1) : rect(1) + rect(3) - 1);    
text(20, 20, sprintf('Threshold : %f, step : %d', tmp(1), biasStep));

function newImg = processImg(img, mask, rect, dstColor)
[mm, nn, pp] = size(img);
newImg = zeros(mm, nn, pp);
for i = 1 : 3    
    tmp = ones(mm, nn) * dstColor(i);
    tmpImg = img(:, :, i);
    tmp(mask) = tmpImg(mask);       
    newImg(:,:,i) = tmp;
end
newImg = uint8(newImg);

imshow(newImg);
if ~ isempty(rect)
    rectangle('Position', rect, 'LineWidth', 2)
end



function threshold = changeThreshold(threshold, rect, bias)
threshold(rect(2) : rect(2) + rect(4) - 1, rect(1) : rect(1) + rect(3) - 1) = mean(mean(threshold(rect(2) : rect(2) + rect(4) - 1, rect(1) : rect(1) + rect(3) - 1)));
threshold(rect(2) : rect(2) + rect(4) - 1, rect(1) : rect(1) + rect(3) - 1) = bias + threshold(rect(2) : rect(2) + rect(4) - 1, rect(1) : rect(1) + rect(3) - 1);

 

posted @ 2013-09-06 20:36  goooooooooo  阅读(1259)  评论(1编辑  收藏  举报