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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM