|
|
|
|
|
""" |
|
Created on Sat Aug 3 21:09:27 2024 |
|
|
|
@author: ysnrfd |
|
""" |
|
|
|
|
|
|
|
""" |
|
Created on Sat Aug 3 21:01:48 2024 |
|
|
|
@author: ysnrfd |
|
""" |
|
|
|
import cv2 |
|
import numpy as np |
|
|
|
def main(): |
|
|
|
cap = cv2.VideoCapture(0) |
|
|
|
if not cap.isOpened(): |
|
print("Error: Unable to open camera.") |
|
return |
|
|
|
|
|
backSub = cv2.createBackgroundSubtractorKNN(history=10, dist2Threshold=15.0, detectShadows=True) |
|
|
|
try: |
|
while True: |
|
|
|
ret, frame = cap.read() |
|
|
|
if not ret: |
|
print("Error: Unable to read frame.") |
|
break |
|
|
|
|
|
fgMask = backSub.apply(frame) |
|
|
|
|
|
kernel = np.ones((1, 1), np.uint8) |
|
fgMask = cv2.morphologyEx(fgMask, cv2.MORPH_CLOSE, kernel) |
|
fgMask = cv2.morphologyEx(fgMask, cv2.MORPH_OPEN, kernel) |
|
|
|
|
|
blurred = cv2.GaussianBlur(fgMask, (1, 1), 0) |
|
|
|
|
|
contours, _ = cv2.findContours(blurred, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) |
|
|
|
|
|
for contour in contours: |
|
if cv2.contourArea(contour) > 10: |
|
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 |
|
|
|
finally: |
|
|
|
cap.release() |
|
cv2.destroyAllWindows() |
|
|
|
if __name__ == "__main__": |
|
main() |
|
|