python 连通区域检测_python+opencv实现检测物体聚集区域

import cv2

import numpy as np

for n in open('list.txt'): # list.txt为目标文件列表

path = n[:-1] # 去除文件路径的换行符

img = cv2.imread(path)

gray =cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 图像转灰度

ret, binary = cv2.threshold(gray, 75, 255, cv2.THRESH_BINARY) # 灰度转二值图像

cv2.imwrite(path + 'abc.png', binary)

kernel = np.ones((21,21),np.uint8) # 给图像闭运算定义核

kernel_1 = np.ones((101,101),np.uint8) # 给图像开运算定义核

# 图像先闭运算再开运算可以过滤孤立的物体, 将密集物体区域形成一片连通区

closing = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel)

opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel_1)

# 给图像的边缘像素设定为255,否则下面连通区的检测无法识别贴在图像边缘的连通区

# 特别注意!!!,此操作会将整个图像也视为一个连通区域

opening_x = opening.shape[0]

opening_y = opening.shape[1]

opening[:,0] = 255

opening[:,opening_y-1] = 255

opening[0,:] = 255

opening[opening_x-1,:] = 255

# 检测图像连通区(输入为二值化图像)

image, contours, hierarchy = cv2.findContours(opening,1,2)

for n in range(len(contours)):

# 筛选面积较大的连通区,阈值为20000

cnt = contours[n]

area = cv2.contourArea(cnt)

if area > 20000:

x,y,w,h=cv2.boundingRect(cnt)

img_ = cv2.rectangle(img ,(x,y),(x+w,y+h),(0,0,255),4) # 画框

print('')

img__ = img[y-h:y+h,x-w:x+w,:]

cv2.imwrite(path + 'abc_open.png', opening)

cv2.imwrite(path + 'abc_close.png', closing)

cv2.imwrite(path + 'abc_close_range.png', img_)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值