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# گرفتن تصویر از دوربین
12cap = cv2.VideoCapture(0)
13
14# Kalman Filter برای ردیابی دقیقتر
15kalman = cv2.KalmanFilter(4, 2)
16kalman.measurementMatrix = np.array([[1, 0, 0, 0], [0, 1, 0, 0]], np.float32)
17kalman.transitionMatrix = np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1]], np.float32)
18kalman.processNoiseCov = np.array([[1e-5, 0, 0, 0], [0, 1e-5, 0, 0], [0, 0, 1e-5, 0], [0, 0, 0, 1e-5]], np.float32)
19
20while True:
21 ret, frame = cap.read()
22 if not ret:
23 break
24
25 # تبدیل تصویر به خاکستری
26 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
27
28 # دریافت ماسک اشیاء متحرک
29 fg_mask = back_sub.apply(frame)
30
31 # حذف نویز پیشرفته با استفاده از GaussianBlur و MedianBlur
32 fg_mask = cv2.GaussianBlur(fg_mask, (5, 5), 0) # حذف نویز با بلور گوسی
33 fg_mask = cv2.medianBlur(fg_mask, 5) # حذف نویز با استفاده از MedianBlur
34
35 # اعمال عملیات مورفولوژیکی پیچیدهتر برای حذف نویز و سایهها
36 kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7)) # هسته بزرگتر
37 fg_mask = cv2.morphologyEx(fg_mask, cv2.MORPH_CLOSE, kernel, iterations=2) # استفاده از عملیات CLOSE
38 fg_mask = cv2.dilate(fg_mask, kernel, iterations=3) # افزایش سایز ماسک
39
40 # پیدا کردن کانتورها
41 contours, _ = cv2.findContours(fg_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
42
43 for cnt in contours:
44 area = cv2.contourArea(cnt)
45 if area > 500: # فقط اشیاء بزرگتر از این اندازه رو بررسی کن
46 x, y, w, h = cv2.boundingRect(cnt)
47 centroid = get_centroid(x, y, w, h)
48
49 # استفاده از Kalman Filter برای پیشبینی موقعیت شیء
50 kalman.correct(np.array([np.float32(centroid[0]), np.float32(centroid[1])]))
51 prediction = kalman.predict()
52
53 predicted_x, predicted_y = int(prediction[0]), int(prediction[1])
54
55 # رسم باکس و پیشبینی موقعیت
56 cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
57 cv2.circle(frame, centroid, 4, (0, 0, 255), -1)
58 cv2.putText(frame, "Moving Object", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
59 cv2.circle(frame, (predicted_x, predicted_y), 4, (255, 0, 0), -1) # پیشبینی موقعیت
60
61 # نمایش تصویر
62 cv2.imshow('Optimized Object Tracking', frame)
63
64 # خروج از برنامه با کلید ESC
65 if cv2.waitKey(1) & 0xFF == 27:
66 break
67
68cap.release()
69cv2.destroyAllWindows()
70 