OpenCV-形态学处理(膨胀腐蚀、开闭运算)

膨胀:取结构元领域内最大值作为该位置的输出像素值,总体亮度升高。
腐蚀:取结构元领域内最小值作为该位置的输出像素值,总体亮度降低。
开运算:先腐蚀后膨胀。
闭运算:先膨胀后腐蚀。

C++:

#include
#include
using namespace std;
using namespace cv;

Mat Morphology_ED(Mat image)
{
     
	Mat erode_image, dilate_image;
	//创建7x7矩形结构元
	Mat s = getStructuringElement(MORPH_RECT, Size(7, 7));
	//腐蚀;膨胀
	erode(image, erode_image, s);
	dilate(image, dilate_image, s);
	imshow("erode image", erode_image);
	imshow("dilate image", dilate_image);
	return s;
};

Mat Morpgology_OC(Mat image)
{
     
	Mat open_image, close_image;
	Mat s = getStructuringElement(MORPH_CROSS, Size(3, 3));
	//开运算;闭运算
	morphologyEx(image, open_image, MORPH_OPEN, s);
	morphologyEx(image, close_image, MORPH_OPEN, s);
	imshow("open image", open_image);
	imshow("close image", close_image);
	return s;

};
int main()
{
     
	Mat img;
	img = imread("D:/testimage/word.jpg", IMREAD_GRAYSCALE);
	Morphology_ED(img);
	Morpgology_OC(img);
	waitKey(0);
	return 0;
};

原图:OpenCV-形态学处理(膨胀腐蚀、开闭运算)_第1张图片膨胀:OpenCV-形态学处理(膨胀腐蚀、开闭运算)_第2张图片腐蚀:OpenCV-形态学处理(膨胀腐蚀、开闭运算)_第3张图片形态学梯度:OpenCV-形态学处理(膨胀腐蚀、开闭运算)_第4张图片开运算:OpenCV-形态学处理(膨胀腐蚀、开闭运算)_第5张图片闭运算:OpenCV-形态学处理(膨胀腐蚀、开闭运算)_第6张图片
Python:

import cv2 as cv
import numpy as np

def Morphology_image(image):
    #创建7x7矩形结构元
    s=cv.getStructuringElement(cv.MORPH_RECT,(7,7))
    #腐蚀操作
    erode_image=cv.erode(image,s)
    #膨胀操作
    dilate_image=cv.dilate(image,s)
    return erode_image,dilate_image

def Morphology_OC(image):
    s = cv.getStructuringElement(cv.MORPH_CROSS, (5, 5))
    #开运算
    open_image=cv.morphologyEx(image,cv.MORPH_OPEN,s)
    #闭运算
    close_image=cv.morphologyEx(image,cv.MORPH_CLOSE,s)
    #形态学梯度
    gradient_image=cv.morphologyEx(image,cv.MORPH_GRADIENT,s)
    #顶帽运算
    tophat_image=cv.morphologyEx(image,cv.MORPH_TOPHAT,s)
    #底帽运算
    blackhat_image=cv.morphologyEx(image,cv.MORPH_BLACKHAT,s)
    return open_image,close_image,gradient_image,tophat_image,blackhat_image

if __name__=="__main__":
    img=cv.imread("D:/testimage/word.jpg")
    gray_dst = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    erode_image,dilate_image=Morphology_image(gray_dst)
    #open_image,close_image,gradient_image,tophat_image,blackhat_image=Morphology_OC(gray_dst)
    cv.imshow("erode image",erode_image)
    cv.imshow("dilate image", dilate_image)
    cv.imwrite("D:/testimage/result-erode.jpg",erode_image)
    cv.imwrite("D:/testimage/result-dilate.jpg", dilate_image)
    cv.waitKey(0)
    cv.destroyAllWindows()

你可能感兴趣的:(OpenCV基础教程,opencv,计算机视觉,cv,图像识别)