ysn-rfd/text-dataset-tiny-code-script-py-format
USED of tahamajs/medicine_ds_persian for .parquet file USED of Alijafarixcs2/persian-it-llama2-2k for .parquet file USED of Abirate/english_quotes for .jsonl file NEW FILES (05/12/2025) NEW FILES (12/26/2025) NEW FILES (02/15/2026)
31.7k
1import cv2
2import numpy as np
3
4# استفاده از الگوریتم پیشرفته KNN برای background subtraction
5back_sub = cv2.createBackgroundSubtractorKNN(history=500, dist2Threshold=400, detectShadows=True)
6
7# تابع برای محاسبه مرکز (centroid)
8def get_centroid(x, y, w, h):
9 return (int(x + w / 2), int(y + h / 2))
10
11# ایجاد یک فیلتر کالمن برای پیگیری حرکت شیء
12kalman = cv2.KalmanFilter(4, 2)
13kalman.transitionMatrix = np.array([[1, 0, 1, 0],
14 [0, 1, 0, 1],
15 [0, 0, 1, 0],
16 [0, 0, 0, 1]], np.float32)
17kalman.measurementMatrix = np.array([[1, 0, 0, 0],
18 [0, 1, 0, 0]], np.float32)
19kalman.processNoiseCov = np.array([[1e-2, 0, 0, 0],
20 [0, 1e-2, 0, 0],
21 [0, 0, 1, 0],
22 [0, 0, 0, 1]], np.float32)
23kalman.errorCovPost = np.eye(4, dtype=np.float32)
24kalman.statePost = np.zeros((4, 1), np.float32)
25
26# گرفتن تصویر از دوربین
27cap = cv2.VideoCapture(0)
28
29while True:
30 ret, frame = cap.read()
31 if not ret:
32 break
33
34 # تبدیل تصویر به خاکستری
35 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
36
37 # دریافت ماسک اشیاء متحرک
38 fg_mask = back_sub.apply(frame)
39
40 # اعمال عملیات مورفولوژیکی برای حذف سایهها و نویز
41 kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
42 fg_mask = cv2.morphologyEx(fg_mask, cv2.MORPH_OPEN, kernel, iterations=1)
43 fg_mask = cv2.dilate(fg_mask, kernel, iterations=1)
44
45 # پیدا کردن کانتورها
46 contours, _ = cv2.findContours(fg_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
47
48 for cnt in contours:
49 area = cv2.contourArea(cnt)
50 if area > 100: # فقط اشیاء بزرگتر از این اندازه رو بررسی کن
51 x, y, w, h = cv2.boundingRect(cnt)
52 centroid = get_centroid(x, y, w, h)
53 cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
54 cv2.circle(frame, centroid, 4, (0, 0, 255), -1)
55 cv2.putText(frame, "Moving Object", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
56
57 # اندازهگیری موقعیت شیء و پیشبینی با فیلتر کالمن
58 kalman.correct(np.array([x + w / 2, y + h / 2], np.float32))
59 prediction = kalman.predict()
60
61 # استخراج مقادیر پیشبینی شده
62 predicted_x, predicted_y = int(prediction[0, 0]), int(prediction[1, 0])
63
64 # رسم موقعیت پیشبینی شده
65 cv2.circle(frame, (predicted_x, predicted_y), 4, (255, 0, 0), -1)
66
67 # نمایش تصویر پردازش شده
68 cv2.imshow('Real-Time Object Tracking with Kalman Filter', frame)
69
70 # خروج از برنامه با کلید ESC
71 if cv2.waitKey(1) & 0xFF == 27:
72 break
73
74cap.release()
75cv2.destroyAllWindows()
76 