zoukankan      html  css  js  c++  java
  • OpenCV图像处理:灰度化和二值化

    一、图像二值化基本原理:
    对灰度图像进行处理,设定阈值,在阈值中的像素值将变为1(白色部分),阈值为的将变为0(黑色部分)。

    二、图像二值化处理步骤:

    (1)先对彩色图像进行灰度化

    //img为原图,imgGray为灰度图
    cvtColor(img, imgGray, CV_BGR2GRAY);

    (2)对灰度图进行二值化

    //imgGray为灰度图,result为二值图像
    //100~255为阈值,可以根据情况设定
    //在阈值中的像素点将变为0(白色部分),阈值之外的像素将变为1(黑色部分)。
    threshold(imgGray, result, 100, 255, CV_THRESH_BINARY)

    三、demo

     1 #include<iostream>
     2 #include<opencv2highguihighgui.hpp>
     3 #include<opencv2corecore.hpp>
     4 #include <opencv2imgprocimgproc.hpp>
     5  
     6 using namespace std;
     7 using namespace cv;
     8  
     9 int main()
    10 {
    11     Mat img, imgGray,result;
    12     img = imread("test.jpg");
    13     if (!img.data) {
    14         cout << "Please input image path" << endl;
    15         return 0;
    16     }
    17     imshow("原图", img);
    18     cvtColor(img, imgGray, CV_BGR2GRAY);
    19     imshow("灰度图", imgGray);
    20     //blur(imgGray, imgGray, Size(3, 3));
    21     threshold(imgGray, result, 100, 255, CV_THRESH_BINARY);
    22     imshow("二值化后的图", result);
    23     imwrite("二值化的二维码.jpg", result);
    24     cout << "图片已保存" << endl;
    25     waitKey();
    26  
    27     return 0;
    28 }

    四、效果:

  • 相关阅读:
    codevs 1031 质数环
    codevs 1005 生日礼物
    codevs 1004 四子连棋
    codevs 2292 图灵机游戏
    1439 统计素数个数
    1675 大质数 2
    codevs 1462 素数和
    [NOIp2012提高组]借教室
    [NOIp2007提高组]矩阵取数游戏
    [TJOI2017]城市
  • 原文地址:https://www.cnblogs.com/ybqjymy/p/12801532.html
Copyright © 2011-2022 走看看