opencv-068-图像形态学(黑帽操作) 发表于 2019-04-21 | 分类于 opencv 知识点形态学的黑帽操作是闭操作与输入图像之间的差异,黑帽操作可以表示如下:黑帽操作 = 闭操作 – 输入图像 API 1234567891011121314151617void cv::morphologyEx( InputArray src, OutputArray dst, int op, InputArray kernel, Point anchor = Point(-1,-1), int iterations = 1, int borderType = BORDER_CONSTANT,)src 输入图像dst 输出图像op 形态学操作kernel 结构元素anchor 中心位置锚定iterations 循环次数borderType 边缘填充类型其中op指定为MORPH_BLACKHAT即表示使用顶帽操作 代码(c++,python)12345678910111213141516171819202122232425262728293031#include <iostream>#include <opencv2/opencv.hpp>using namespace std;using namespace cv;/* * 图像形态学(黑帽操作) */int main() { Mat src = imread("../images/morph.png"); if (src.empty()) { cout << "could not load image.." << endl; } imshow("input", src); // 二值图像 Mat gray, binary, result; cvtColor(src, gray, COLOR_BGR2GRAY); threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU); // 黑帽操作 Mat se = getStructuringElement(MORPH_RECT, Size(15, 15), Point(-1, -1)); morphologyEx(binary, result, MORPH_CLOSE, se); imshow("close_op", result); morphologyEx(binary, result, MORPH_BLACKHAT, se); imshow("blackhat_op", result); waitKey(0); return 0;} 123456789101112131415161718192021import cv2 as cvimport numpy as npsrc = cv.imread("D:/images/morph.png")cv.namedWindow("input", cv.WINDOW_AUTOSIZE)cv.imshow("input", src)# 图像二值化gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)# 黑帽操作se = cv.getStructuringElement(cv.MORPH_RECT, (9, 9), (-1, -1))binary = cv.morphologyEx(binary, cv.MORPH_BLACKHAT, se)cv.imshow("black hat", binary)cv.imwrite("D:/binary2.png", binary)cv.waitKey(0)cv.destroyAllWindows() 结果 代码地址github