5.轮廓检测 + 形状:利用opencv 进行轮廓新增,周长,面积
轮廓检测是工业视觉检测项目中超级重大的一个环节,本次使用opencv来演示一下最简单的轮廓检测方法。
原始图像1:

检测结果1:

#### 演示方法:
def cnt_detect(res, contours):
for i, cnt in enumerate(contours):
area = cv2.contourArea(cnt) ### 轮廓面积
if area > 200:
perimeter = cv2.arcLength(cnt,True) ### 轮廓周长,True--对象的形状是闭合的,否则False
M = cv2.moments(cnt) ### 矩
epsilon = 0.02 * cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,epsilon,True) ### 轮廓拟合
cx, cy = int(M['m10']/M['m00']), int(M['m01']/M['m00']) ### 质心坐标
res = cv2.drawContours(res, [cnt], -3, (0,255,), 3) ### 显示轮廓
cntTyple = shapeType(approx) ### 轮廓形成
text = f"{cntTyple},
面积:{int(area)},
周长:{int(perimeter)}"
res = cv2.circle(res, (cx,cy), 2, (255,0,0), 4)
res_pil = label_on_pilimg(cv2pil(res), text, (cx - 20, cy -30))
res = pil2cv(res_pil)
return res
原始图像2:
再来看一下稍微复杂的例子:

分割结果2:

6.轮廓凸包性检测
凸包与轮廓近似类似 , 可以使用函数 cv2.convexHull() 可以用来检测一个曲线是否具有凸性缺陷。

原始图像
对原始不规则图像进行轮廓检测。

检测效果:
轮廓凸性判断, 外接矩形,最小外接矩,最小外接圆, 椭圆拟合, 直线拟合,极点

具体方法如下:
def cntsShow(res, contours):
""" 轮廓凸性判断, 外接矩形,最小外接矩,
最小外接圆, 椭圆拟合, 直线拟合,极点
"""
rows,cols = res.shape[:2]
for cnt in contours:
area = cv2.contourArea(cnt)
hull = cv2.convexHull(cnt) ###
k = cv2.isContourConvex(cnt) ### 凸性判断
if not k and area > 100:
# if area > 100:
x,y,w,h = cv2.boundingRect(cnt) ### 外接矩形
rect = cv2.minAreaRect(cnt) ###最小外接矩:矩形的中心(x,y) 和 (宽,高), 旋转角度
box = cv2.boxPoints(rect) ### 最小外接矩4个脚坐标
(cx,cy), radius = cv2.minEnclosingCircle(cnt) ### 最小外接圆
ellipse = cv2.fitEllipse(cnt) ### 椭圆拟合
[vx,vy,x1,y1] = cv2.fitLine(cnt, cv2.DIST_L2, 0, 0.01,0.01) ###拟合直线
lefty = int((-x1*vy/vx) + y1)
righty = int(((cols-x1)*vy/vx)+y1)
center, radius = (int(cx),int(cy)), int(radius)
box = np.int0(box)
### 极点:
leftmost = tuple(cnt[cnt[:,:,0].argmin()][0])
rightmost = tuple(cnt[cnt[:,:,0].argmax()][0])
topmost = tuple(cnt[cnt[:,:,1].argmin()][0])
bottommost = tuple(cnt[cnt[:,:,1].argmax()][0])
cv2.drawContours(res, [hull], -1, (0,0,255), 2) ###显示凸性轮廓
cv2.rectangle(res, (x,y), (x+w,y+h),(255, 0, 0), 2 ) ###显示边界矩形
cv2.drawContours(res, [box], 0, (0, 255, 0), 2) ###显示最小外接矩
cv2.circle(res, center, radius, (120, 120, 120), 4 ) ### 显示最小外接圆
cv2.line(res,(cols-1,righty),(0,lefty),(0,0,200),10) ### 显示拟合直线
for c in [leftmost, rightmost, topmost, bottommost]: ###显示极点
cv2.circle(res, c, 5, (0, 0, 255), 5)
return res
© 版权声明
文章版权归作者所有,未经允许请勿转载。
哇,python原来还可以做这些事情
收藏了,感谢分享