objcolor.m

来自「彩色图像纹理提取的一种算法」· M 代码 · 共 62 行

M
62
字号
%Written by Adam Meadows
%test function to find color or an object in an image
function color = objcolor(img, lightback, thresh)

% Object Color, (Adam Meadows: ameadows@cs.ucr.edu)
% color = objcolor(img, lightback)
% 
% IMG is the input image
% LIGHTBACK is a flag specifying that the background is lighter than the foreground
% THRESH is the threshold for computing BW image (if 0, compute it)
%
% COLOR returns the average color for the object in IMG
%

%convert to binary image
I = rgb2gray(img);
if thresh == 0
    thresh = graythresh(I);
end
bw = im2bw(I, thresh);

%if a light background, swap the values of bw
if(lightback == 1)
    bw = swap(bw);
end %end of if it was a light background

%variables to hold RGB info for all background pixels, and count
R = uint32(0);
G = uint32(0);
B = uint32(0);
numPixels = 0;

%now loop through the binary image, only considering coordinates == 1
[r c] = size(bw);
while (numPixels < 1000)
        
    i = floor(rand * r);
    if(i == 0)
        i = 1;
    end
    j = floor(rand * c);
    if(j == 0)
        j = 1;
    end
    
    if(bw(i,j) == 1)
        numPixels = numPixels + 1;
        R = R + uint32(img(i,j,1));
        G = G + uint32(img(i,j,2));
        B = B + uint32(img(i,j,3));
    end %end of if it's a background pixel

end %end of outer loop

R = floor(R / numPixels);
G = floor(G / numPixels);
B = floor(B / numPixels);

%return the color
color = [ R G B ];

%end %end of find_color function

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?