opencv-071-形态学操作(击中击不中) 发表于 2019-04-22 | 分类于 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_HITMISS即表示使用击中击不中 代码(c++,python)123456789101112131415161718192021222324252627282930#include <iostream>#include <opencv2/opencv.hpp>using namespace std;using namespace cv;/* * 形态学操作(击中击不中) */int main() { Mat src = imread("../images/cross.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_INV | THRESH_OTSU); // 击中击不中 Mat se = getStructuringElement(MORPH_CROSS, Size(11,11)); morphologyEx(binary, result, MORPH_HITMISS, se); imshow("bit_and_miss", result); waitKey(0); return 0;} 123456789101112131415161718192021import cv2 as cvimport numpy as npsrc = cv.imread("D:/images/cross.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_INV | cv.THRESH_OTSU)# 击中击不中se = cv.getStructuringElement(cv.MORPH_CROSS, (11, 11), (-1, -1))binary = cv.morphologyEx(binary, cv.MORPH_HITMISS, se)cv.imshow("black hat", binary)cv.imwrite("D:/binary2.png", binary)cv.waitKey(0)cv.destroyAllWindows() 结果 代码地址github