opencv图像轮廓检测

效果展示:

代码部分:

python 复制代码
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()
相关推荐
知舟不叙5 小时前
基于OpenCV实现实时颜色检测
人工智能·opencv·计算机视觉·颜色检测
whoarethenext11 小时前
使用 C/C++的OpenCV 裁剪 MP4 视频
c语言·c++·opencv
jndingxin19 小时前
OpenCV CUDA 模块光流计算------稀疏光流算法类SparsePyrLKOpticalFlow
人工智能·opencv·算法
jndingxin20 小时前
OpenCV CUDA模块图像变形------对图像进行GPU加速的透视变换函数warpPerspective()
人工智能·opencv·计算机视觉
吴声子夜歌21 小时前
OpenCV——图像平滑
人工智能·opencv·计算机视觉
吴声子夜歌21 小时前
OpenCV——图像的几何变化
人工智能·opencv·计算机视觉
終不似少年遊*2 天前
机器学习方法实现数独矩阵识别器
人工智能·python·opencv·机器学习·计算机视觉·矩阵
jndingxin2 天前
OpenCV CUDA模块图像变形------对图像进行 尺寸缩放(Resize)操作函数resize()
人工智能·opencv·计算机视觉
luofeiju2 天前
数字图像处理与OpenCV初探
c++·图像处理·python·opencv·计算机视觉
清醒的兰2 天前
OpenCV 多边形绘制与填充
图像处理·人工智能·opencv·计算机视觉