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_)

  

posted @ 2019-10-17 13:44  牛郎  阅读(2788)  评论(0编辑  收藏  举报