如何使用此命令从图像中选择特定颜色?

时间:2014-03-11 13:33:05

标签: image matlab image-processing image-segmentation

我已经获得了一个图像,其中的单词已被正确分割并通过不同的颜色表示。

这是图片:

enter image description here

有人告诉我,即使没有源文件,我也可以从该图像中选择特定的单词/颜色并保存以供进一步处理。这可以通过创建新图像v来完成,例如

v=r+g*256+b*256*256+1

其中r,g和b分别是红色,蓝色和绿色通道。

我试图使用它,但它创建的只是一个白色的空白图像

img = imread('color_test.bmp');
r = img(:,:,1);
g = img(:,:,2);
b = img(:,:,3);

v=r+g*256+b*256*256+1;

我不明白上面的v图像如何让我选择单独的颜色?

2 个答案:

答案 0 :(得分:2)

您应用于创建矢量v的转换只是为所有可能的RGB颜色值创建唯一数值的方法。要了解其工作原理,请设想一个简化的RGB系统,其中每种颜色的值都限制在0到9之间。此外,我们通过将255替换为10来简化转换:

 v = r + g*10 + b*100

现在很容易看到每一个值 (1)v总是在0到999之间 (2)所有红色值都在其中编码 (3)所有绿色值都以十进制编码 (4)并且所有蓝色值都以数百个编码。

因此,不同的颜色总会在v中产生不同的值。

假设您的图片包含n种不同的颜色。然后,您的矩阵v将仅包含n个唯一值(即每种颜色一个),可使用命令unique

识别
 colorValues = unique(v); 

如果你现在想要识别图像中与特定颜色相对应的所有区域,例如,向量colorValues中的第一个值,则只需使用

v == colorValues(1)

将在包含指定颜色的所有单元格中为您提供。

如果要根据颜色将图像拆分为多个图像,可以使用

newImg = zeros(size(img)); 
newImg(repmat(v == colorValues(1), [1 1 3]) = 255; 

现在newImg应该只包含与colorValues(1)中的颜色相匹配的所有内容。

要查找不同的颜色,只需使用不同的索引,例如

 newImg(repmat(v == colorValues(2), [1 1 3]) = 255

答案 1 :(得分:1)

我可以从你的问题中收集的是,你需要以某种方式存储关于单独彩色文本的“信息”。因此,下面的代码可能会解决它,为此我必须记下6种不同颜色的文本中的每一种的颜色。得到的4D矩阵存储所有“信息”。请注意,我们可以通过挤出存储冗余数据的第三维来轻松制作3D,因为我们正在寻找完美的颜色匹配。

<强>代码

%// Read image
img = imread('color_test.bmp');

%%// Create a database of text colors
color1 = [236 3 104]; %%// text1
color2 = [57 228 2]; %%// text2
color3 = [147 190 131]; %%// text3
color4 = [5 107 106]; %%// text4
color5 = [254 223 188]; %%// text5
color6 = [19 98 13]; %%// text6
color = [color1;color2;color3;color4;color5;color6]; %%// all text colors in a Nx3 matrix

%%// Save all the individual colored images in a 4D matrix for later
img_all = false([size(img) size(color,1)]);
for k = 1:size(color,1)
    img_all(:,:,:,k) = bsxfun(@eq,img,permute(color(k,:),[1 3 2]));
end

%%// Show the images as black and white
figure,
for k = 1:size(color,1)
    subplot(size(color,1),1,k), imshow(uint8(255.*img_all(:,:,:,k)));
end

%%// Show the images in their original colors
figure,
for k = 1:size(color,1)
    subplot(size(color,1),1,k), imshow(uint8(bsxfun(@times,img_all(:,:,:,k),permute(color(k,:),[1 3 2]))));
end

<强>输出

enter image description here

enter image description here

请告诉我们这是否适合您!