python opencv實現檢測物體聚集區域

2022-06-13 07:21:13 字數 1528 閱讀 5431

內容涉及:二值影象轉換 / 檢測連通區域面積 / 在原圖上畫框等

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

Python OpenCV實現簡單的人臉檢測

匯入opencv庫 import cv2 載入特徵分類器 opencv自帶 face cascade cv2.cascadeclassifier haarcascade frontalface default.xml 開啟電腦攝像頭 capture cv2.videocapture 0 獲得攝像頭捕...

python opencv實現人臉和眼睛檢測

coding utf8 import cv2 import time defdetect 定義乙個檢測函式 face cascade cv2.cascadeclassifier d program files opencv opencv sources data haarcascades haarc...

python opencv 實現人臉檢測

可以用opencv 的庫函式來實現人臉檢測 coding utf 8 import numpy as np import cv2 import time import sys,getopt from video import create capture from common import clo...