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

2021-12-07  本文已影响0人  SeatonLv

把图像进行二值化吧。

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

我们将灰度的阈值设置为$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);

上一篇下一篇

猜你喜欢

热点阅读