|
import cv2 |
|
import numpy as np |
|
|
|
def main(): |
|
|
|
cap = cv2.VideoCapture(0) |
|
|
|
|
|
backSub = cv2.createBackgroundSubtractorMOG2(history=500, varThreshold=16, detectShadows=True) |
|
|
|
if not cap.isOpened(): |
|
print("خطا در باز کردن دوربین") |
|
return |
|
|
|
while True: |
|
|
|
ret, frame = cap.read() |
|
|
|
if not ret: |
|
print("خطا در خواندن فریم") |
|
break |
|
|
|
|
|
fgMask = backSub.apply(frame) |
|
|
|
|
|
kernel = np.ones((5, 5), np.uint8) |
|
fgMask = cv2.morphologyEx(fgMask, cv2.MORPH_CLOSE, kernel) |
|
fgMask = cv2.morphologyEx(fgMask, cv2.MORPH_OPEN, kernel) |
|
|
|
|
|
contours, _ = cv2.findContours(fgMask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) |
|
|
|
|
|
for contour in contours: |
|
if cv2.contourArea(contour) > 500: |
|
x, y, w, h = cv2.boundingRect(contour) |
|
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) |
|
|
|
|
|
cv2.imshow('Frame', frame) |
|
cv2.imshow('Foreground Mask', fgMask) |
|
|
|
|
|
if cv2.waitKey(1) & 0xFF == ord('q'): |
|
break |
|
|
|
|
|
cap.release() |
|
cv2.destroyAllWindows() |
|
|
|
if __name__ == "__main__": |
|
main() |
|
|