|
|
|
|
|
""" |
|
Created on Sun Aug 4 16:08:30 2024 |
|
|
|
@author: ysnrfd |
|
""" |
|
|
|
import cv2 |
|
import numpy as np |
|
|
|
def detect_anomalies(frame1, frame2, min_contour_area=1, threshold_value=7): |
|
""" |
|
Detects anomalies between two frames and highlights them. |
|
|
|
Parameters: |
|
- frame1: The previous frame. |
|
- frame2: The current frame. |
|
- min_contour_area: Minimum area for a contour to be considered an anomaly. |
|
- threshold_value: Threshold value for binary conversion. |
|
|
|
Returns: |
|
- The frame with anomalies highlighted. |
|
""" |
|
|
|
gray1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY) |
|
gray2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY) |
|
|
|
|
|
diff = cv2.absdiff(gray1, gray2) |
|
|
|
|
|
blurred = cv2.GaussianBlur(diff, (5, 5), 0) |
|
|
|
|
|
_, thresh = cv2.threshold(blurred, threshold_value, 255, cv2.THRESH_BINARY) |
|
|
|
|
|
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) |
|
|
|
|
|
for contour in contours: |
|
if cv2.contourArea(contour) > min_contour_area: |
|
x, y, w, h = cv2.boundingRect(contour) |
|
cv2.rectangle(frame1, (x, y), (x+w, y+h), (0, 255, 0), 1) |
|
|
|
return frame1 |
|
|
|
def main(): |
|
|
|
cap = cv2.VideoCapture(0) |
|
|
|
|
|
if not cap.isOpened(): |
|
print("Error: Could not open video capture.") |
|
return |
|
|
|
|
|
ret, prev_frame = cap.read() |
|
if not ret: |
|
print("Error: Could not read initial frame.") |
|
cap.release() |
|
return |
|
|
|
while True: |
|
|
|
ret, curr_frame = cap.read() |
|
if not ret: |
|
print("Error: Could not read frame.") |
|
break |
|
|
|
|
|
result_frame = detect_anomalies(prev_frame, curr_frame) |
|
|
|
|
|
cv2.imshow('Anomalies Detected', result_frame) |
|
|
|
|
|
prev_frame = curr_frame |
|
|
|
|
|
if cv2.waitKey(1) & 0xFF == ord('q'): |
|
break |
|
|
|
|
|
cap.release() |
|
cv2.destroyAllWindows() |
|
|
|
if __name__ == "__main__": |
|
main() |
|
|