Team Ai
Datasetpublic

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)

sourceHugging Faceapache-2.0updated 4mo agoView on Hugging Face
3likes1.7kdownloads
untitled6.py101 linesDownload Raw Back to opencv_test
1import cv2
2import numpy as np
3from sklearn.neighbors import KNeighborsClassifier
4
5# استفاده از الگوریتم پیشرفته KNN برای background subtraction
6back_sub = cv2.createBackgroundSubtractorKNN(history=500, dist2Threshold=400, detectShadows=True)
7
8# تابع برای محاسبه مرکز (centroid)
9def get_centroid(x, y, w, h):
10    return (int(x + w / 2), int(y + h / 2))
11
12# تابع برای کاهش نویز
13def apply_noise_reduction(fg_mask):
14    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
15    fg_mask = cv2.morphologyEx(fg_mask, cv2.MORPH_OPEN, kernel, iterations=2)
16    fg_mask = cv2.dilate(fg_mask, kernel, iterations=1)
17    return fg_mask
18
19# تابع برای تشخیص جهت حرکت
20def detect_direction(prev, curr):
21    dx = curr[0] - prev[0]
22    dy = curr[1] - prev[1]
23    if abs(dx) > abs(dy):
24        return "Right" if dx > 0 else "Left"
25    else:
26        return "Down" if dy > 0 else "Up"
27
28# گرفتن تصویر از دوربین
29cap = cv2.VideoCapture(0)
30
31# مدل KNN
32knn = KNeighborsClassifier(n_neighbors=3)
33
34# داده‌های آموزشی و برچسب‌ها
35object_features = []
36object_labels = []
37
38# تنظیمات آموزش دوره‌ای
39learning_interval = 30
40frame_count = 0
41
42# نگه‌داری آخرین موقعیت centroid برای دنبال‌ کردن مسیر
43prev_centroids = []
44
45while True:
46    ret, frame = cap.read()
47    if not ret:
48        break
49
50    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
51    fg_mask = back_sub.apply(frame)
52    fg_mask = apply_noise_reduction(fg_mask)
53    contours, _ = cv2.findContours(fg_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
54
55    current_centroids = []
56
57    for cnt in contours:
58        area = cv2.contourArea(cnt)
59        if area > 100:
60            x, y, w, h = cv2.boundingRect(cnt)
61            centroid = get_centroid(x, y, w, h)
62            current_centroids.append(centroid)
63
64            # استخراج ویژگی‌ها
65            features = [w, h, centroid[0], centroid[1], area]
66            object_features.append(features)
67            object_labels.append(1)
68
69            # رسم باکس و مرکز
70            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
71            cv2.circle(frame, centroid, 4, (0, 0, 255), -1)
72
73            # اگر centroid قبلی موجود است، جهت را تشخیص بده
74            if len(prev_centroids) > 0:
75                closest_prev = min(prev_centroids, key=lambda p: np.linalg.norm(np.array(p) - np.array(centroid)))
76                direction = detect_direction(closest_prev, centroid)
77                cv2.putText(frame, f"Dir: {direction}", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 0), 2)
78
79    # به‌روزرسانی centroid های قبلی
80    prev_centroids = current_centroids.copy()
81
82    # آموزش دوره‌ای مدل
83    frame_count += 1
84    if frame_count % learning_interval == 0 and len(object_features) > 5:
85        knn.fit(object_features, object_labels)
86        print("Model updated!")
87
88    if len(object_features) > 5 and frame_count % learning_interval == 0:
89        predicted_label = knn.predict([features])[0]
90        cv2.putText(frame, f"Predicted: {predicted_label}", (x, y - 30), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
91
92    # نمایش تصویر
93    cv2.imshow('Object Tracking with Direction', frame)
94
95    # خروج با کلید ESC
96    if cv2.waitKey(1) & 0xFF == 27:
97        break
98
99cap.release()
100cv2.destroyAllWindows()
101