前言
这是我《OpenCV:从零到一》专栏的第十篇博客,想看跟多请戳这。
本文概要
开操作- open 先腐蚀后膨胀 可以去掉小的对象,假设对象是前景色,背景是黑色
闭操作- close 可以填充小的洞(fill hole),假设对象是前景色,背景是黑色
形态学梯度- Morphological Gradient 膨胀减去腐蚀 又称为基本梯度(其它还包括-内部梯度、方向梯度)
顶帽 – top hat
黑帽 – black hat
morphologyEx
案例代码
大概内容:黑帽 。
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
using namespace cv;
int main(int argc, char** argv) {
Mat src, dst;
src = imread("D:\\86186\\Documents\\opencv\\lena.jpg");
if (!src.data) {
printf("could not load image...\n");
}
namedWindow("input image", WINDOW_AUTOSIZE);
imshow("input image", src);
char output_title[] = "morphology demo";
namedWindow(output_title, WINDOW_AUTOSIZE);
Mat kernel = getStructuringElement(MORPH_RECT, Size(11, 11), Point(-1, -1));//开闭操作用的算子
morphologyEx(src, dst, MORPH_BLACKHAT, kernel);
imshow(output_title, dst);
waitKey(0);
return 0;
}
运行效果:
仅示范黑帽
解析及注意事项
- 这个函数比腐蚀和膨胀操作多了一个op参数,用来判断执行哪一个操作,其他参数都是一样的(甚至怀疑腐蚀和膨胀就是这个函数包装了一下而已)
- CV_MOP_BLACKHAT在opencv4里面被改了,和之前那些单纯去掉CV_的不一样,这个还需要把morphology补全一些,写成MORPH_BLACKHAT 情况比较特殊。
- 下面是所有op种类
- 注意这里的iteration,当他大于1的时候(比如2)执行复杂的操作的时候(比如开操作)的执行顺序是erode -> erode -> dilate -> dilate (and not erode -> dilate -> erode -> dilate).
全注释代码
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
using namespace cv;
int main(int argc, char** argv) {
Mat src, dst;
src = imread("D:\\86186\\Documents\\opencv\\lena.jpg");
if (!src.data) {
printf("could not load image...\n");
}
namedWindow("input image", WINDOW_AUTOSIZE);
imshow("input image", src);
char output_title[] = "morphology demo";
namedWindow(output_title, WINDOW_AUTOSIZE);
Mat kernel = getStructuringElement(MORPH_RECT, Size(11, 11), Point(-1, -1));//开闭操作用的算子
morphologyEx(src, dst, MORPH_BLACKHAT, kernel);
/*
InputArray src,
OutputArray dst,
int op,//Type of a morphological operation, see MorphTypes
InputArray kernel,//Structuring element. It can be created using getStructuringElement.
Point anchor = Point(-1,-1),
int iterations = 1,
int borderType = BORDER_CONSTANT,
const Scalar & borderValue = morphologyDefaultBorderValue()
The number of iterations is the number of times erosion or dilatation operation will be applied.
For instance, an opening operation (MORPH_OPEN) with two iterations is equivalent to apply successively:
erode -> erode -> dilate -> dilate (and not erode -> dilate -> erode -> dilate).
*/
imshow(output_title, dst);
waitKey(0);
return 0;
}
翻译笔记
iterations 迭代
equivalent n.等值;同义词;