美文网首页
opencv(NoneAPI100例---3)--二值化

opencv(NoneAPI100例---3)--二值化

作者: SeatonLv | 来源:发表于2021-12-07 09:48 被阅读0次

    把图像进行二值化吧。

    二值化是将图像使用黑和白两种颜色表示的方法。

    我们将灰度的阈值设置为$128$来进行二值化,即: $$ y= \begin{cases} 0& (\text{if}\quad y < 128) \ 255& (\text{else}) \end{cases} $$

    先灰度化---->二值化

    灰度化:https://www.jianshu.com/p/902a38a39aa6

    Mat Binarize(Mat gray, int th)

    {

        int width = gray.cols;

        int height = gray.rows;

        // prepare output

        cv::Mat out = cv::Mat::zeros(height, width, CV_8UC1);

        // each y, x

        for (int y = 0; y < height; y++) 

        {

                for (int x = 0; x < width; x++) 

                {

                // Binarize

                        if (gray.at<uchar>(y, x) > th)

                         {

                                out.at<uchar>(y, x) = 255;

                        }

                    else {

                        out.at<uchar>(y, x) = 0;

                        }

                    }

            }

            return out;

    }

    cv::Mat img = cv::imread("D:/chat.png", cv::IMREAD_COLOR);

    cv::imshow("old", img);

    // BGR -> Gray

    cv::Mat gray = BGR2GRY1(img);

    cv::imshow("gray", gray);

    // Gray -> Binary

    cv::Mat out = Binarize(gray, 128);

    //cv::imwrite("out.jpg", out);

    cv::imshow("sample", out);

    相关文章

      网友评论

          本文标题:opencv(NoneAPI100例---3)--二值化

          本文链接:https://www.haomeiwen.com/subject/vxggxrtx.html