灰度腐蚀与膨胀
示例代码
createTrackbar("Element Size :", OUTPUT_WIN, &element_size, max_size, CallBack_Demo);//滑动条,参数1滑动条名字,参数2传入的窗口名字,参数4滑动条初始值,参数5滑动条最大值
CallBack_Demo(0, 0);
void CallBack_Demo(int, void*) {
int s = element_size * 2 + 1;
Mat structureElement = getStructuringElement(MORPH_RECT, Size(s, s), Point(-1, -1));
// dilate(src, dst, structureElement, Point(-1, -1), 1);灰度膨胀
erode(src, dst, structureElement);//灰度腐蚀
imshow(OUTPUT_WIN, dst);
return;
}
形态学操作
Mat kernel = getStructuringElement(MORPH_RECT, Size(11, 11), Point(-1, -1));//定义结构元素
morphologyEx(src, dst, CV_MOP_BLACKHAT, kernel);//黑帽操作
阈值操作
threshold binary
大于阈值线的赋值为255,小于的赋值为0
threshold binary Inverted
大于阈值线的赋值为0,小于的赋值为255
truncate
大于阈值线的直接赋值为阈值线大小
threshold to zero
小于阈值线的赋值为0,大于的保留原来值
threshold to zero inverted
大于阈值线的赋值为0,小于的保留原来的值
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
using namespace std;
using namespace cv;
Mat src, gray_src, dst;
int threshold_value = 127;
int threshold_max = 255;
int type_value = 2;
int type_max = 4;
void Threshold_Demo(int, void*);
int main(int argc, char** argv) {
src = imread("22.jpg");
if (!src.data) {
printf("could not load image...\n");
return -1;
}
namedWindow("input image", CV_WINDOW_AUTOSIZE);
imshow("input image", src);
namedWindow("output_title", CV_WINDOW_AUTOSIZE);
//参数1:滑块名 参数2:窗口
//参数3:滑块初始值 参数4:滑块最大值
//最后一个参数是函数,意思就是滑块变动,就调用该函数一次
createTrackbar("Threshold Value:", "output_title", &threshold_value, threshold_max, Threshold_Demo);
createTrackbar("Type Value:", "output_title", &type_value, type_max, Threshold_Demo);//切换阈值的模式,总共5种
Threshold_Demo(0, 0);
waitKey(0);
return 0;
}
void Threshold_Demo(int, void*) {
cvtColor(src, gray_src, CV_BGR2GRAY); //灰度化
threshold(gray_src, dst, threshold_value, 255, type_value);
imshow("output_title", dst);
}
参考文献
【OpenCV3】阈值化操作——cv::threshold()与cv::adaptiveThreshold()详解