opencv图像轮廓检测

效果展示:
opencv图像轮廓检测_第1张图片

代码部分:

import cv2 
import numpy as np
img = cv2.imread('C:/Users/ibe/Desktop/picture.PNG',cv2.IMREAD_UNCHANGED)
# 类型转换
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 结构元
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
# 腐蚀
img = cv2.erode(img, kernel)
# 膨胀
img = cv2.dilate(img, kernel)
# 中值滤波
img = cv2.medianBlur(img, 3)

# 二值化
ret, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
# 计算轮廓
contours, hierarchy = cv2.findContours(thresh , cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# 类型转换
img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
# 绘制轮廓
# 1. 一般轮廓
cv2.drawContours(img, contours, -1, (0, 255, 0), 2)
# 2. 边界矩形轮廓
for c in contours:
	x, y, w, h = cv2.boundingRect(c)
	cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
# 3. 最小矩形轮廓
for c in contours:
	rect = cv2.minAreaRect(c)
	box = cv2.boxPoints(rect)
	box = np.int0(box)
	cv2.drawContours(img, [box], 0, (0, 0, 255), 2)
# 4. 最小闭圆
for c in contours:
	(x, y), radius = cv2.minEnclosingCircle(c)
	center = (int(x), int(y))
	radius = int(radius)
	cv2.circle(img, center, radius, (255, 0, 0), 2)

# 显示图像
cv2.imshow("img", img)
# 保存图像
cv2.imwrite("img2.png", img)
# 触发等待延时
cv2.waitKey(0)
# 销毁所有窗口
cv2.destroyAllWindows()


你可能感兴趣的:(opencv)