Morphological study notes -opencv-

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/aaron1996123456/article/details/102742941

Morphological study notes -opencv-

Common morphological operations include: erosion, dilation, opening operation and closing operation, the top-hat operation, operation other bottom cap, wherein the expansion is the most basic method of corrosion.

corrosion

Analytical principle

Corrosion of the image is selected for each seat position of the minimum output value of the neighborhood location. Neighborhood may be a rectangular structure, may be an elliptical structure, crisscross configuration, most of the structural element is defined.

Selecting a minimum value for each neighborhood, the image brightness will decrease corrosion, the lighter areas in the image area will be reduced or even disappear. Image the I , structuring element S of the etching operation referred to as:
E = I S E = I⊝S
of the image area of reduced brightness etching operation area, is a binary random white after thresholding for FIG foreground, by I E IE operation to extract the border.

Implementation code

For the image opencv provide corrosion function:

erode(src, element[,dst[,iterations[,borderType[,borderValue]]]])
    //src			输入矩阵
    //element		结构元
    //anchor		结构元的锚点
    //iterations	迭代的次数
    //borderType	边界扩充类型
    //borderValue	边界扩充值

For out of bounds, the need to expand the image boundary, the best way mirror. Represents the structure element parametric element, opencv provides functions:

getStructuringElement(shape, ksize[,anchor])
    //shape			MORPH_RECT:产生矩形结构元
    //				MORPH_ELLIPSEM:产生椭圆结构元
    //				MORPH_CROSS:产生十字交叉结构元
    //ksize			结构元尺寸
    //anchor		结构元锚点

GetStrcturingElement functions using erode and etching operation:

if __name__ =='__main__':
	#loading image
	image=cv2.imread("G:\\blog\\OpenCV_picture\\chapter6\\img7.jpg",cv2.IMREAD_GRAYSCALE)
	cv2.imshow("image",image)
	#Entropy threshold
	thresh,out=threshEntroy(image)

	#show thresh
	print(thresh)
	out=np.round(out)
	out.astype(np.uint8)

	#erode
	#create element
	element = cv2.getStructuringElement(cv2.MORPH_RECT,(3,3))
	#erode image, iterations set 1
	erodeImg = cv2.erode(out, element)
	#border extraction
	bordeExtractionImg = out - erodeImg

	cv2.imshow("out",out)
	cv2.imshow("erodeImage", erodeImg)
	cv2.imshow("border extraction image", bordeExtractionImg)
	cv2.waitKey(0)
	cv2.destroyAllWindows()

operation result:

[Image dump the chain fails, the source station may have security chain mechanism, it is recommended to save the picture down uploaded directly (img-7h40f80j-1571986151633) (C: \ Users \ huangxin \ Desktop \ affine transformation \ OpenCV algorithm succinctly -7 \ 1.png)]

C ++ etching operation:

	//创建结构元
	Mat element = getStructuringElement(MORPH_RECT, Size(3, 3));
	
	//进行2次腐蚀操作
	Mat erodeImage1, erodeImage2;
	erode(OtsuMat, erodeImage1, element, Point(-1, -1), 2);
	erode(threshByEntroyMat, erodeImage2, element, Point(-1, -1), 2);
	
	//显示图片
	imshow("src", src);
	imshow("dst", thresh_out_dst);
	imshow("threshByEntroy", threshByEntroyMat);
	imshow("Otsu", OtsuMat);
	imshow("erode after Otsu", erodeImage1);
	imshow("erode after threshByEntroy", erodeImage2);

operation result:

[Image dump the chain fails, the source station may have security chain mechanism, it is recommended to save the picture down uploaded directly (img-y6V1KLkY-1571986151634) (C: \ Users \ huangxin \ Desktop \ affine transformation \ OpenCV algorithm succinctly -7 \ 2.png)]

Structuring element size is increased, the white region of the target object is smaller; etching operation is repeated, a white area will be smaller.

Swell

Corrosion was similar, but the maximum value of the neighborhood is acquired, after expansion, will increase the brightness of the image, lighter areas will be increased. The image I and structuring element S expansion operation referred to as:
D = I S D = I⊕S

Code

open'c'v provided dilate function ()

dilate(src, element[,dst[,iterations[,borderType[,borderValue]]]])
//src			输入矩阵
//element		结构元
//anchor		结构元的锚点
//iterations	迭代的次数
//borderType	边界扩充类型
//borderValue	边界扩充值
if __name__=="__main__":
	image=cv2.imread("G:\\blog\\OpenCV_picture\\chapter6\\img7.jpg",cv2.IMREAD_GRAYSCALE)
	cv2.imshow("init iamge", image)

	#结构元半径,迭代次数
	radius, iterationsNum = 1, 1
	MAX_R, MAX_Iter = 20, 20
	
	#显示膨胀窗口
	cv2.namedWindow("dilate", 1)

	def nothing(*arg):
		pass

	#调节结构圆半径
	cv2.createTrackbar("radius", "dilate", radius, MAX_R, nothing)
	cv2.createTrackbar("iterations", "dilate", iterationsNum, MAX_Iter, nothing)
	while True:

		#获得当前的半径值
		radius = cv2.getTrackbarPos("radius", 'dilate')
		iterationsNum = cv2.getTrackbarPos("iterations", "dilate")
		#创建结构元
		element = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2*radius+1, 2*radius+1))

		#膨胀图像
		dilateImg = cv2.dilate(image, element, iterations=iterationsNum)

		#显示膨胀效果
		cv2.imshow("dilate", dilateImg)
		ch = cv2.waitKey(5)
		
		#按下Esc键退出
		if ch ==  27:
			break
	cv2.destroyAllWindows()

Note that in this code "S = cv2.getStructuringElement (cv2.MORPH_OPEN, (2 R & lt 1,2 + R & lt +. 1))" which the error will be given cv2.cv2.MORPH_ELLIPSE in which another program is displayed "error: (-215: Assertion failed) anchor.inside ( Rect (0, 0, ksize.width, ksize.height)) in function 'cv :: normalizeAnchor'

Find out where the problem because my cv2.destroyAllWindows () in a while loop to write inside, causing the radius value and can not get back iteration.

element minimum size of 3 * 3, than this size must be large, or will an error

int radius = 1;
int MAX_R = 20;
Mat image, outImg;


//回调函数,调节半径
void callBack(int, void *)
{
	//创建只有垂直方向上的矩形结构元
	Mat element = getStructuringElement(MORPH_RECT, Size(1, 2 * radius + 1));

	dilate(image, outImg, element);

	imshow("dilate", outImg);
	
}

int main()
{

	//输入图像
	std::string imagePath = "G:\\blog\\OpenCV_picture\\chapter6\\img7.jpg";
	Mat src = imread(imagePath, 0);
	
	if (!src.data)
	{
		std::cout << "load image error!" << std::endl;
		return -1;
	}

	Mat thresh_out_dst;
	int ret = 0;

	ret = threshTwoPeaks(src, thresh_out_dst);
	if (!ret)
	{
		return -1;
	}
	cout << ret << endl;


	Mat threshByEntroyMat;
	ret = threshByEntroy(src, threshByEntroyMat);
	if (!ret)
	{
		return -1;
	}
	cout << ret << endl;

	
	Mat OtsuMat;
	ret = Otsu(src, OtsuMat);
	if (!ret)
	{
		return -1;
	}
	cout << ret << endl;

	imshow("Otsu", OtsuMat);
	waitKey(0);
	OtsuMat.copyTo(image);
	//image=OtsuMat.clone();
	imshow("img", image);
	namedWindow("dilate", WINDOW_AUTOSIZE);
	createTrackbar("radius", "dilate", &radius, MAX_R, callBack);
	callBack(0, 0);

	waitKey(0);


	return 0;
}

operation result:

[Image dump the chain fails, the source station may have security chain mechanism, it is recommended to save the picture down uploaded directly (img-Jilr78rT-1571986151636) (C: \ Users \ huangxin \ Desktop \ affine transformation \ OpenCV algorithm succinctly -7 \ 4.png)]

The foregoing is where OstuMat Ostu obtained image thresholding.

Opening operation and closing operation

Opening operation to be expanded during the corrosion.

Eliminating higher brightness in a small area, the separation object at a thin point, for larger objects, can smoothly change the boundary inconspicuous in the case of the area and so on.

Closing operation is performed by etching the first expansion.

It may be filled with a black fine white object within cavity region, adjacent to the connection object, the same structure elements, multiple treatments may be a case where the boundary significantly altering its smooth area and so on.

opencv provides functions norphologyEx () function

norphologyEx(src, op, element[,dst[, anchor[iterations[,borderType[,borderValue]]]]])
//src			输入矩阵
//op			形态学处理的各种运算
//				NORPH_OPEN		开运算
//				NORPH_CLOSE		闭运算
//				NORPH_GRADIENT	形态梯度
//				NORPH_TOPHAT	顶帽运算
//				NORPH_BLACKHAT	底帽运算
//element		结构元
//iterations	迭代次数
//anchor		结构元锚点
if __name__ == "__main__":
	image = cv2.imread("G:\\blog\\OpenCV_picture\\chapter7\\img1.jpg", 0)
	cv2.imshow("InitImage", image)

	#结构元半径
	radius, iter = 1, 1
	MAX_R, MAX_Iter = 20, 20

	#
	cv2.namedWindow("morphology", 1)
	def nothing(*arg):
		pass

	cv2.createTrackbar("radius", "morphology", radius, MAX_R, nothing)
	cv2.createTrackbar("iterations", "morphology", iter, MAX_Iter, nothing)

	while True:
		radius = cv2.getTrackbarPos("radius", "morphology")
		iter = cv2.getTrackbarPos("iterations", "morphology")

		element = cv2.getStructuringElement(cv2.MORPH_RECT,(2*radius+1, 2*radius +1))

		photoMorphology = cv2.morphologyEx(image, cv2.MORPH_OPEN,element,iterations=iter)

		cv2.imshow("morphology", photoMorphology)
		
		ch = cv2.waitKey(5)
		if ch  == 27:
			break

	cv2.destroyAllWindows()

Operating results [Pictures dump outside the chain fails, the source station may have a security chain mechanism, it is recommended to save the pictures uploaded directly down (img-vBQSaH8w-1571986151637) (C: \ Users \ huangxin \ Desktop \ affine transformation \ opencv algorithm succinctly -7 \ 5.png)]

Opening operation eliminates the lighter areas of the dark background, does not change significantly in the case of the area, to eliminate white bright area. Closing operation is to remove a dark region within the lighter areas

Top hat transformation

Defining an image of the top-hat transform to the result of subtracting opening operation

Open operator can remove the lighter areas in the dark background. Picture obtained by subtracting the way open operator lighter gray areas, one of the more positive effect uneven illumination. Also known as white top hat transform

Bottom hat transformation

The end cap defining an image arithmetic operation result of subtracting the closing

Opening operation can be eliminated in the dark areas lighter background. Picture obtained by subtracting the way open operator darker the gray area, also known as black top hat transform

Morphological Gradient

Morphological gradient is defined by subtracting a result of corrosion of the expansion, the expansion neighborhood maximum value, a minimum value of the rain corrosion, high luminance is obtained by subtracting the low luminance object boundaries.

MorphologyEx opencv function provided in the modified value of op can be achieved top cap, a bottom cap operation, the gradient morphology

//输入图像
Mat I;
//输出图像
Mat d;
//结构元
Mat element;
string window = "形态学处理";
//结构元半径
int r = 1;
int MAX_R = 20;
//迭代次数
int i = 1;
int MAX_I = 20;
//回调函数,调节r和i
void callBack(int, void*)
{
	//创建结构元
	element = getStructuringElement(MORPH_RECT, Size(2 * r + 1, 2 * r + 1));
	//形态学处理
	morphologyEx(I, d, cv::MORPH_TOPHAT, element, Point(-1, -1), i);
	//显示形态处理的效果
	imshow(window, d);
}
int main(int argc, char*argv[])
{
	//输入图像
	I = imread("G:\\blog\\OpenCV_picture\\chapter7\\open.jpg", 0);
	if (!I.data)
		return 0;
	//显示原图
	imshow("原图", I);
	//创建显示形态学结果显示窗口
	namedWindow(window, 1);
	//创建调节r的进度条
	createTrackbar("半径", window, &r, MAX_R, callBack);
	//创建调节i的进度条
	createTrackbar("迭代次数", window, &i, MAX_I, callBack);
	callBack(0, 0);
	waitKey(0);
	return 0;
}

Run Pictures:

{
// input image
the I = imread ( "G: \ Blog \ OpenCV_picture \ chapter7 \ open.jpg", 0);
IF (I.Data!)
Return 0;
// display picture
imshow ( "artwork", I );
// create a display window displays the results of the morphological
namedWindow (window,. 1);
// Create a progress bar adjustment of r
createTrackbar ( "radius", window, & r, MAX_R, callBack);
// create a progress bar of adjustable i
createTrackbar ( "iterations", window, & I, MAX_I, callBack);
callBack (0, 0);
waitKey (0);
return 0;
}


运行图片:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qG5oqqdk-1571986151638)(C:\Users\huangxin\Desktop\仿射变换\opencv算法精讲-7\6.png)]

Guess you like

Origin blog.csdn.net/aaron1996123456/article/details/102742941