c++ - 如何在 OpenCV 中对图像进行阈值处理?

标签 c++ opencv image-processing

我在 OpenCV 中有一个表示掩码的二值图像。这个蒙版有一定程度的几何噪声,我想消除,所以我使用模糊来达到这种效果。

现在我有了一张灰度图像。我想让所有像素都超过某个阈值并使它们变白,而所有其他像素必须变黑。

在 opencv 中有没有简单的方法来做到这一点?

最佳答案

是的,有:

ret,thresh1 = cv.threshold(img,127,255,cv.THRESH_BINARY)

我从 this link .

在 C++ 上,我们有

threshold( src_gray, dst, threshold_value, max_BINARY_value,threshold_type );

Here if you want further information

来自最后一个链接的完整代码(C++ 教程)

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdlib.h>
#include <stdio.h>

using namespace cv;

/// Global variables

int threshold_value = 0;
int threshold_type = 3;;
int const max_value = 255;
int const max_type = 4;
int const max_BINARY_value = 255;

Mat src, src_gray, dst;
char* window_name = "Threshold Demo";

char* trackbar_type = "Type: \n 0: Binary \n 1: Binary Inverted \n 2: Truncate \n 3: To Zero \n 4: To Zero Inverted";
char* trackbar_value = "Value";

/// Function headers
void Threshold_Demo( int, void* );

/**
 * @function main
 */
int main( int argc, char** argv )
{
  /// Load an image
  src = imread( argv[1], 1 );

  /// Convert the image to Gray
  cvtColor( src, src_gray, CV_BGR2GRAY );

  /// Create a window to display results
  namedWindow( window_name, CV_WINDOW_AUTOSIZE );

  /// Create Trackbar to choose type of Threshold
  createTrackbar( trackbar_type,
                  window_name, &threshold_type,
                  max_type, Threshold_Demo );

  createTrackbar( trackbar_value,
                  window_name, &threshold_value,
                  max_value, Threshold_Demo );

  /// Call the function to initialize
  Threshold_Demo( 0, 0 );

  /// Wait until user finishes program
  while(true)
  {
    int c;
    c = waitKey( 20 );
    if( (char)c == 27 )
      { break; }
   }

}


/**
 * @function Threshold_Demo
 */
void Threshold_Demo( int, void* )
{
  /* 0: Binary
     1: Binary Inverted
     2: Threshold Truncated
     3: Threshold to Zero
     4: Threshold to Zero Inverted
   */

  threshold( src_gray, dst, threshold_value, max_BINARY_value,threshold_type );

  imshow( window_name, dst );
}

关于c++ - 如何在 OpenCV 中对图像进行阈值处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54695467/

相关文章:

C++ 运算符重载 << 并返回字符串 getMonthName 方法

c++ - MFC visual c++ LNK2019链接错误

python - Python 中的 OpenCV 无法扫描像素

python - 将 1 channel 骨架图像叠加到 3 channel RGB 图像上

python - 将所有非黑色像素转换为一种颜色不会产生预期的输出

python - OCR应用前图像清洗

c++ - Qt,在构造函数之外修改小部件属性的问题

c++ - 使用 offsetof() 从成员变量中获取所有者对象

python-3.x - 如何在 Python3 中从图像中删除矩形形状,保留文本?

c++ - 通过检测图像中的特定大对象或 Blob 来裁剪图像?