c++ - 如何在 OpenCV 中对图像进行阈值处理?
问题描述
我在 OpenCV 中有一个表示掩码的二进制图像。这个蒙版有一定程度的几何噪声,我想平滑,所以我使用模糊来实现这个效果。
现在我有一个灰度图像。我想将高于某个阈值的所有像素设为白色,而所有其他像素必须变为黑色。
在opencv中有没有简单的方法来做到这一点?
解决方案
就在这里:
ret,thresh1 = cv.threshold(img,127,255,cv.THRESH_BINARY)
我从这个链接得到。
在 C++ 上,我们有
threshold( src_gray, dst, threshold_value, max_BINARY_value,threshold_type );
最后一个链接的完整代码(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 );
}
推荐阅读
- bash - 一行中的 bash 脚本中文件名的扩展名列表
- android - 在使用 asyncStorage 和 json.parse() 时,我的公共变量不会自行更新
- keras - 多类预测的多个命题
- django - 在 jinja 模板中使用 set 标签时出错('set'。您是否忘记注册或加载此标签?)
- ios - 空属性字符串的属性
- moqui - 在 Moqui 框架中设置排序规则
- google-app-maker - 如何优雅地处理试图访问他们没有权限的页面的用户?
- r - lmer 花费太多时间来运行大数据集
- c++ - 构造函数可以更改默认成员类型吗?
- javascript - 弹出内容取决于 AJAX 结果