数组或图像中的唯一值数字

fee*_*ree 2 c++ stl image-processing

我现在正在从磁盘读取图像.图像可以是灰度图像或二值图像.但是,我无法从图像的头文件中分辨出来.我现在要做的是告诉唯一像素的数量.如果唯一像素数大于2,则图像为灰度; 否则它是黑白图像.我正在使用以下功能来完成这项工作:

  bool is_binary_image(  std::vector<unsigned char> &memory)
{
    std::set<unsigned char> myset;
    for(  std::vector<unsigned char>::iterator  it = memory.begin();
        it!= memory.end(); 
        it++)
    {
        myset.insert(*it);
        if (myset.size()>2)
            return false;
    }

    return true;

}
Run Code Online (Sandbox Code Playgroud)

如果候选图像是灰度图像,则该功能可以很好地完成.但是,如果候选图像是二进制的,则该功能是耗时的.关于改进功能的任何想法?

gaw*_*awi 5

您可以使用数组而不是map来加快速度:

bool is_binary_image(  std::vector<unsigned char> &memory)
{
    int counter = 0;
    int pixels[256] = {};

    for(  std::vector<unsigned char>::iterator  it = memory.begin();
        it!= memory.end(); 
        it++)
    {
        pixels[*it]++;
        if (pixels[*it]==1)
          counter++;
        if (counter>2)
            return false;
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)

编辑

这是优化版本(但可能不太可读),thx TemplateRex:

bool is_binary_image(  std::vector<unsigned char> &memory)
{
    int counter = 0;
    int pixels[256] = {};

    for(  std::vector<unsigned char>::iterator  it = memory.begin();
        it!= memory.end(); 
        it++)
    {
        if ((counter += (++pixels[*it] == 1))>2)
            return false;
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,你需要一个`std :: array <int,256>`让所有的计数从零开始,这不会发生在`int pixels [256];` (2认同)