前言
這是我《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.等值;同義詞;