如何区分二进制和灰度图像?

时间:2017-06-13 12:13:05

标签: c++ opencv

我正在使用灰度图像。我正在寻找一种方法来过滤主要靠近黑色和近白色像素的图像,这些图像主要是灰色像素。

目前,我在做:

  1. 应用阈值从灰色过滤B / W像素。
  2. 将黑色的数量加上白色的数量与图像的总像数进行比较。
  3. 有没有其他方法可以解决这个问题?也许是现有的OpenCV方法?

    编辑以下是我对上述内容的实现。

    bool isBinary(cv::Mat img)
    {
        cv::Mat whites, blacks;
        unsigned int count_whites=0, count_blacks=0, count_pixels=0;
    
        // White enough goes to full white (255)
        cv::threshold(img, whites, 250, 255, THRESH_BINARY);
        // Not black enough goes to full white (255)
        cv::threshold(img, blacks, 5, 255, THRESH_BINARY);
    
        cv::MatIterator_<unsigned char> it_whites = whites.begin<unsigned char>(), it_whites_end = whites.end<unsigned char>();
        cv::MatIterator_<unsigned char> it_blacks = blacks.begin<unsigned char>();
    
        for (; it_whites != it_whites_end; ++it_whites, ++it_blacks) {
            unsigned char current_white=*it_whites, current_black=*it_blacks;
            // Checking white
            if ((int)*it_whites == 255)
                count_whites++;
            // Checking black
            if ((int)*it_blacks == 0)
                count_blacks++;
            count_pixels++;
        }
    
        // Let's say 80% its predominantly binary for me
        return (count_blacks + count_whites) > 0.8*count_pixels;
    }
    

1 个答案:

答案 0 :(得分:0)

你只需要决定你在做什么。

图像可以是全灰度 - 0-255范围内的像素,表示大多数数字,全二进制 - 所有像素0或255,具有抗锯齿的二进制 - 像素0或255,边界除外,其中允许中间值,本质上是二进制 - 大多数值接近0或255但不完全是0或255.可能还有其他可能性。

查找Otsu阈值处理,这将是一种将图像分离为前景和背景的有用技术。然后决定你会打电话给什么&#34;黑白&#34;你会称之为&#34;灰度&#34;。

相关问题