Datasets:
Upload 31 files
Browse filesFiles changed (31)
- opencv_test/Untitled.ipynbAdded+261
- opencv_test/Untitled1.ipynbAdded+174
- opencv_test/Untitled2.ipynbAdded+78
- opencv_test/Untitled3.ipynbAdded+141
- opencv_test/Untitled4.ipynbAdded+194
- opencv_test/Untitled5.ipynbAdded+126
- opencv_test/Untitled6.ipynbAdded+297
- opencv_test/Untitled7.ipynbAdded
- opencv_test/object_memory.ptAdded+3
- opencv_test/untitled.pyAdded
- opencv_test/untitled1.pyAdded+69
- opencv_test/untitled10.pyAdded+153
- opencv_test/untitled11.pyAdded+147
- opencv_test/untitled12.pyAdded+157
- opencv_test/untitled13.pyAdded+172
- opencv_test/untitled14.pyAdded+114
- opencv_test/untitled15.pyAdded+147
- opencv_test/untitled16.pyAdded+86
- opencv_test/untitled17.pyAdded+100
- opencv_test/untitled18.pyAdded+99
- opencv_test/untitled2.pyAdded+75
- opencv_test/untitled21.pyAdded+99
- opencv_test/untitled22.pyAdded+5
- opencv_test/untitled23.pyAdded+31
- opencv_test/untitled24.pyAdded+32
- opencv_test/untitled3.pyAdded+80
- opencv_test/untitled5.pyAdded+86
- opencv_test/untitled6.pyAdded+100
- opencv_test/untitled7.pyAdded+138
- opencv_test/untitled8.pyAdded+140
- opencv_test/untitled9.pyAdded+153
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "9991fa5b-c41f-4117-a81f-75727fa4a74d", "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "a77abb8840a9407ebf60f186551f64d4", "version_major": 2, "version_minor": 0 }, "text/plain": [ "pytorch_model.bin: 0%| | 0.00/485M [00:00<?, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "* Running on local URL: http://127.0.0.1:7860\n", "* To create a public link, set `share=True` in `launch()`.\n" ] }, { "data": { "text/html": [ "<div><iframe src=\"http://127.0.0.1:7860/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>" ], "text/plain": [ "<IPython.core.display.HTML object>" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import gradio as gr\n", "from transformers import AutoTokenizer, AutoModelForCausalLM\n", "import torch\n", "\n", "# بارگذاری مدل و توکنایزر\n", "tokenizer = AutoTokenizer.from_pretrained(\"HooshvareLab/gpt2-fa\")\n", "model = AutoModelForCausalLM.from_pretrained(\"HooshvareLab/gpt2-fa\")\n", "\n", "# تابع تولید متن\n", "def generate_text(prompt):\n", " input_ids = tokenizer.encode(prompt, return_tensors=\"pt\")\n", " output = model.generate(\n", " input_ids,\n", " max_new_tokens=120,\n", " do_sample=True,\n", " temperature=0.7,\n", " top_k=40,\n", " top_p=0.9,\n", " repetition_penalty=1.3,\n", " pad_token_id=tokenizer.eos_token_id\n", " )\n", " return tokenizer.decode(output[0], skip_special_tokens=True)\n", "\n", "# رابط گرافیکی\n", "gr.Interface(\n", " fn=generate_text,\n", " inputs=gr.Textbox(label=\"متن ورودی (پرامپت)\", placeholder=\"مثلاً: در یک روز بهاری،\"),\n", " outputs=gr.Textbox(label=\"متن تولید شده\"),\n", " title=\"تولید متن فارسی با GPT2\",\n", " description=\"مدل: bolbolzaban/gpt2-persian - تولید خودکار متن طبیعی به زبان فارسی\"\n", ").launch()\n" ] }, { "cell_type": "code", "execution_count": 1, "id": "c4d50353-c26f-45a9-9962-da748dc618f4", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "* Running on local URL: http://127.0.0.1:7860\n", "* To create a public link, set `share=True` in `launch()`.\n" ] }, { "data": { "text/html": [ "<div><iframe src=\"http://127.0.0.1:7860/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>" ], "text/plain": [ "<IPython.core.display.HTML object>" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import gradio as gr\n", "from transformers import AutoTokenizer, AutoModelForCausalLM\n", "import torch\n", "\n", "# بارگذاری مدل و توکنایزر\n", "tokenizer = AutoTokenizer.from_pretrained(\"HooshvareLab/gpt2-fa\")\n", "model = AutoModelForCausalLM.from_pretrained(\"HooshvareLab/gpt2-fa\")\n", "\n", "# تابع تولید متن با تنظیمات دقیق\n", "def generate_text(prompt):\n", " input_ids = tokenizer.encode(prompt, return_tensors=\"pt\")\n", " output = model.generate(\n", " input_ids,\n", " max_new_tokens=150,\n", " do_sample=True,\n", " temperature=0.7,\n", " top_k=50,\n", " top_p=0.92,\n", " repetition_penalty=1.3,\n", " no_repeat_ngram_size=3,\n", " pad_token_id=tokenizer.eos_token_id,\n", " eos_token_id=tokenizer.eos_token_id\n", " )\n", " return tokenizer.decode(output[0], skip_special_tokens=True)\n", "\n", "# ساخت رابط گرافیکی با Gradio\n", "gr.Interface(\n", " fn=generate_text,\n", " inputs=gr.Textbox(label=\"📝 متن ورودی (پرامپت)\", placeholder=\"مثلاً: در یک روز بهاری،\", lines=3),\n", " outputs=gr.Textbox(label=\"📄 متن تولید شده\"),\n", " title=\"💬 تولید متن فارسی دقیق با GPT2\",\n", " description=\"این ابزار از مدل bolbolzaban/gpt2-persian استفاده میکند و متن روان و طبیعی به زبان فارسی تولید میکند.\",\n", " theme=\"soft\"\n", ").launch()\n" ] }, { "cell_type": "code", "execution_count": 1, "id": "eba7eda5-f61f-434c-b500-58a8b33c6f0e", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "* Running on local URL: http://127.0.0.1:7860\n", "* To create a public link, set `share=True` in `launch()`.\n" ] }, { "data": { "text/html": [ "<div><iframe src=\"http://127.0.0.1:7860/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>" ], "text/plain": [ "<IPython.core.display.HTML object>" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import gradio as gr\n", "from transformers import AutoTokenizer, AutoModelForCausalLM\n", "import torch\n", "\n", "# بارگذاری مدل و توکنایزر\n", "tokenizer = AutoTokenizer.from_pretrained(\"HooshvareLab/gpt2-fa\")\n", "model = AutoModelForCausalLM.from_pretrained(\"HooshvareLab/gpt2-fa\")\n", "\n", "# تابع تولید متن با دستور\n", "def generate_with_instruction(instruction):\n", " prompt = f\"دستور: {instruction}\\nپاسخ:\"\n", " input_ids = tokenizer.encode(prompt, return_tensors=\"pt\")\n", " output = model.generate(\n", " input_ids,\n", " max_new_tokens=150,\n", " do_sample=True,\n", " temperature=0.7,\n", " top_k=50,\n", " top_p=0.92,\n", " repetition_penalty=1.3,\n", " no_repeat_ngram_size=3,\n", " pad_token_id=tokenizer.eos_token_id,\n", " eos_token_id=tokenizer.eos_token_id\n", " )\n", " return tokenizer.decode(output[0], skip_special_tokens=True)\n", "\n", "# رابط گرافیکی\n", "gr.Interface(\n", " fn=generate_with_instruction,\n", " inputs=gr.Textbox(label=\"📝 دستور وارد کنید\", placeholder=\"مثلاً: دربارهی تاثیر ورزش بر ذهن بنویس\", lines=3),\n", " outputs=gr.Textbox(label=\"📄 پاسخ مدل\"),\n", " title=\"💬 دستور به مدل GPT2 فارسی\",\n", " description=\"با وارد کردن دستور در قالب فارسی، مدل شروع به تولید متن میکند. مثل: نوشتن، خلاصهسازی یا ترجمه.\",\n", " theme=\"soft\"\n", ").launch()\n" ] }, { "cell_type": "code", "execution_count": null, "id": "b83582e3-9740-46a5-8a1b-6329acb9ef16", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python [conda env:base] *", "language": "python", "name": "conda-base-py" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.7" } }, "nbformat": 4, "nbformat_minor": 5}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "6bfa65e2-6aa7-45d3-a52d-8d6339f75501", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "* Running on local URL: http://127.0.0.1:7860\n", "* To create a public link, set `share=True` in `launch()`.\n" ] }, { "data": { "text/html": [ "<div><iframe src=\"http://127.0.0.1:7860/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>" ], "text/plain": [ "<IPython.core.display.HTML object>" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import gradio as gr\n", "from transformers import AutoTokenizer, AutoModelForCausalLM\n", "import torch\n", "\n", "# بارگذاری مدل و توکنایزر\n", "tokenizer = AutoTokenizer.from_pretrained(\"HooshvareLab/gpt2-fa\")\n", "model = AutoModelForCausalLM.from_pretrained(\"HooshvareLab/gpt2-fa\")\n", "\n", "# تابع تولید متن با دستور\n", "def generate_with_instruction(instruction):\n", " prompt = f\"دستور: {instruction}\\nپاسخ:\"\n", " input_ids = tokenizer.encode(prompt, return_tensors=\"pt\")\n", " output = model.generate(\n", " input_ids,\n", " max_new_tokens=900,\n", " do_sample=True,\n", " temperature=0.7,\n", " top_k=50,\n", " top_p=0.92,\n", " repetition_penalty=1.3,\n", " no_repeat_ngram_size=3,\n", " pad_token_id=tokenizer.eos_token_id,\n", " eos_token_id=tokenizer.eos_token_id\n", " )\n", " return tokenizer.decode(output[0], skip_special_tokens=True)\n", "\n", "# رابط گرافیکی\n", "gr.Interface(\n", " fn=generate_with_instruction,\n", " inputs=gr.Textbox(label=\"📝 دستور وارد کنید\", placeholder=\"مثلاً: دربارهی تاثیر ورزش بر ذهن بنویس\", lines=3),\n", " outputs=gr.Textbox(label=\"📄 پاسخ مدل\"),\n", " title=\"💬 دستور به مدل GPT2 فارسی\",\n", " description=\"با وارد کردن دستور در قالب فارسی، مدل شروع به تولید متن میکند. مثل: نوشتن، خلاصهسازی یا ترجمه.\",\n", " theme=\"soft\"\n", ").launch()\n" ] }, { "cell_type": "code", "execution_count": 1, "id": "b693482a-21c0-483f-bb46-deb050ce82ee", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "* Running on local URL: http://127.0.0.1:7860\n", "* To create a public link, set `share=True` in `launch()`.\n" ] }, { "data": { "text/html": [ "<div><iframe src=\"http://127.0.0.1:7860/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>" ], "text/plain": [ "<IPython.core.display.HTML object>" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import gradio as gr\n", "from transformers import GPT2LMHeadModel, GPT2Tokenizer\n", "import torch\n", "\n", "# بارگذاری مدل و توکنایزر\n", "model_name = \"HooshvareLab/gpt2-fa\"\n", "model = GPT2LMHeadModel.from_pretrained(model_name)\n", "tokenizer = GPT2Tokenizer.from_pretrained(model_name)\n", "\n", "# تنظیم مدل برای تولید متن\n", "model.eval()\n", "\n", "# تابعی برای تولید متن\n", "def generate_text(prompt):\n", " input_ids = tokenizer.encode(prompt, return_tensors='pt')\n", " \n", " # تولید متن\n", " with torch.no_grad():\n", " output = model.generate(input_ids, max_length=100, num_return_sequences=1, no_repeat_ngram_size=2, temperature=0.7)\n", "\n", " # تبدیل توکنهای خروجی به متن\n", " generated_text = tokenizer.decode(output[0], skip_special_tokens=True)\n", " \n", " return generated_text\n", "\n", "# تعریف رابط کاربری با Gradio\n", "iface = gr.Interface(fn=generate_text, inputs=\"text\", outputs=\"text\", live=True, title=\"تولید متن فارسی با مدل GPT-2\")\n", "\n", "# اجرا کردن رابط\n", "iface.launch()\n" ] }, { "cell_type": "code", "execution_count": null, "id": "fc890196-c4bf-4b01-ab3c-0796836f9355", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python [conda env:base] *", "language": "python", "name": "conda-base-py" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.7" } }, "nbformat": 4, "nbformat_minor": 5}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "f8a34a5c-7d7b-4c3f-ac3b-72fb8361d148", "metadata": { "scrolled": true }, "outputs": [], "source": [ "import gradio as gr\n", "from transformers import AutoTokenizer, AutoModelForCausalLM\n", "import torch\n", "\n", "# بارگذاری مدل و توکنایزر\n", "tokenizer = AutoTokenizer.from_pretrained(\"HooshvareLab/gpt2-fa\")\n", "model = AutoModelForCausalLM.from_pretrained(\"HooshvareLab/gpt2-fa\")\n", "\n", "# تابع تولید متن با تنظیمات دقیق\n", "def generate_text(prompt):\n", " input_ids = tokenizer.encode(prompt, return_tensors=\"pt\")\n", " output = model.generate(\n", " input_ids,\n", " max_new_tokens=256,\n", " do_sample=True,\n", " temperature=0.7,\n", " top_k=50,\n", " top_p=0.92,\n", " repetition_penalty=1.3,\n", " no_repeat_ngram_size=3,\n", " pad_token_id=tokenizer.eos_token_id,\n", " eos_token_id=tokenizer.eos_token_id\n", " )\n", " return tokenizer.decode(output[0], skip_special_tokens=True)\n", "\n", "# ساخت رابط گرافیکی با Gradio\n", "gr.Interface(\n", " fn=generate_text,\n", " inputs=gr.Textbox(label=\"📝 متن ورودی (پرامپت)\", placeholder=\"مثلاً: در یک روز بهاری،\", lines=3),\n", " outputs=gr.Textbox(label=\"📄 متن تولید شده\"),\n", " title=\"💬 تولید متن فارسی دقیق با GPT2\",\n", " description=\"این ابزار از مدل bolbolzaban/gpt2-persian استفاده میکند و متن روان و طبیعی به زبان فارسی تولید میکند.\",\n", " theme=\"soft\"\n", ").launch()\n" ] }, { "cell_type": "code", "execution_count": null, "id": "33b7f00a-888b-4e51-9453-3c9b7f2e82c0", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python [conda env:base] *", "language": "python", "name": "conda-base-py" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.7" } }, "nbformat": 4, "nbformat_minor": 5}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "ebc05db3-a28f-4f6c-8ebc-649d9b3012ca", "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "1b61a5c74bbf4d45b2b1c469682586e5", "version_major": 2, "version_minor": 0 }, "text/plain": [ "tokenizer_config.json: 0%| | 0.00/50.8k [00:00<?, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "dd9d2a48c24546d59e49ea586ffc47e9", "version_major": 2, "version_minor": 0 }, "text/plain": [ "tokenizer.json: 0%| | 0.00/9.09M [00:00<?, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "70e69a427f724affb5eab8ccf71a9f6c", "version_major": 2, "version_minor": 0 }, "text/plain": [ "special_tokens_map.json: 0%| | 0.00/73.0 [00:00<?, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "c34b9f14434942229268d03748061964", "version_major": 2, "version_minor": 0 }, "text/plain": [ "config.json: 0%| | 0.00/844 [00:00<?, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "ename": "ValueError", "evalue": "The repository for microsoft/bitnet-b1.58-2B-4T contains custom code which must be executed to correctly load the model. You can inspect the repository content at https://hf.co/microsoft/bitnet-b1.58-2B-4T.\nPlease pass the argument `trust_remote_code=True` to allow custom code to be run.", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)", "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\transformers\\dynamic_module_utils.py:666\u001b[0m, in \u001b[0;36mresolve_trust_remote_code\u001b[1;34m(trust_remote_code, model_name, has_local_code, has_remote_code)\u001b[0m\n\u001b[0;32m 665\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[1;32m--> 666\u001b[0m prev_sig_handler \u001b[38;5;241m=\u001b[39m signal\u001b[38;5;241m.\u001b[39msignal(signal\u001b[38;5;241m.\u001b[39mSIGALRM, _raise_timeout_error)\n\u001b[0;32m 667\u001b[0m signal\u001b[38;5;241m.\u001b[39malarm(TIME_OUT_REMOTE_CODE)\n", "\u001b[1;31mAttributeError\u001b[0m: module 'signal' has no attribute 'SIGALRM'", "\nDuring handling of the above exception, another exception occurred:\n", "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", "Cell \u001b[1;32mIn[1], line 8\u001b[0m\n\u001b[0;32m 6\u001b[0m \u001b[38;5;66;03m# Load tokenizer and model\u001b[39;00m\n\u001b[0;32m 7\u001b[0m tokenizer \u001b[38;5;241m=\u001b[39m AutoTokenizer\u001b[38;5;241m.\u001b[39mfrom_pretrained(model_id)\n\u001b[1;32m----> 8\u001b[0m model \u001b[38;5;241m=\u001b[39m AutoModelForCausalLM\u001b[38;5;241m.\u001b[39mfrom_pretrained(\n\u001b[0;32m 9\u001b[0m model_id,\n\u001b[0;32m 10\u001b[0m torch_dtype\u001b[38;5;241m=\u001b[39mtorch\u001b[38;5;241m.\u001b[39mbfloat16\n\u001b[0;32m 11\u001b[0m )\n\u001b[0;32m 13\u001b[0m \u001b[38;5;66;03m# Apply the chat template\u001b[39;00m\n\u001b[0;32m 14\u001b[0m messages \u001b[38;5;241m=\u001b[39m [\n\u001b[0;32m 15\u001b[0m {\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mrole\u001b[39m\u001b[38;5;124m\"\u001b[39m: \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124msystem\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mcontent\u001b[39m\u001b[38;5;124m\"\u001b[39m: \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mYou are a helpful AI assistant.\u001b[39m\u001b[38;5;124m\"\u001b[39m},\n\u001b[0;32m 16\u001b[0m {\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mrole\u001b[39m\u001b[38;5;124m\"\u001b[39m: \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124muser\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mcontent\u001b[39m\u001b[38;5;124m\"\u001b[39m: \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mHow are you?\u001b[39m\u001b[38;5;124m\"\u001b[39m},\n\u001b[0;32m 17\u001b[0m ]\n", "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\transformers\\models\\auto\\auto_factory.py:531\u001b[0m, in \u001b[0;36m_BaseAutoModelClass.from_pretrained\u001b[1;34m(cls, pretrained_model_name_or_path, *model_args, **kwargs)\u001b[0m\n\u001b[0;32m 528\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m kwargs\u001b[38;5;241m.\u001b[39mget(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mquantization_config\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;28;01mNone\u001b[39;00m) \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[0;32m 529\u001b[0m _ \u001b[38;5;241m=\u001b[39m kwargs\u001b[38;5;241m.\u001b[39mpop(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mquantization_config\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m--> 531\u001b[0m config, kwargs \u001b[38;5;241m=\u001b[39m AutoConfig\u001b[38;5;241m.\u001b[39mfrom_pretrained(\n\u001b[0;32m 532\u001b[0m pretrained_model_name_or_path,\n\u001b[0;32m 533\u001b[0m return_unused_kwargs\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m,\n\u001b[0;32m 534\u001b[0m trust_remote_code\u001b[38;5;241m=\u001b[39mtrust_remote_code,\n\u001b[0;32m 535\u001b[0m code_revision\u001b[38;5;241m=\u001b[39mcode_revision,\n\u001b[0;32m 536\u001b[0m _commit_hash\u001b[38;5;241m=\u001b[39mcommit_hash,\n\u001b[0;32m 537\u001b[0m \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mhub_kwargs,\n\u001b[0;32m 538\u001b[0m \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs,\n\u001b[0;32m 539\u001b[0m )\n\u001b[0;32m 541\u001b[0m \u001b[38;5;66;03m# if torch_dtype=auto was passed here, ensure to pass it on\u001b[39;00m\n\u001b[0;32m 542\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m kwargs_orig\u001b[38;5;241m.\u001b[39mget(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mtorch_dtype\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;28;01mNone\u001b[39;00m) \u001b[38;5;241m==\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mauto\u001b[39m\u001b[38;5;124m\"\u001b[39m:\n", "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\transformers\\models\\auto\\configuration_auto.py:1117\u001b[0m, in \u001b[0;36mAutoConfig.from_pretrained\u001b[1;34m(cls, pretrained_model_name_or_path, **kwargs)\u001b[0m\n\u001b[0;32m 1115\u001b[0m has_remote_code \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mauto_map\u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;129;01min\u001b[39;00m config_dict \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mAutoConfig\u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;129;01min\u001b[39;00m config_dict[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mauto_map\u001b[39m\u001b[38;5;124m\"\u001b[39m]\n\u001b[0;32m 1116\u001b[0m has_local_code \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mmodel_type\u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;129;01min\u001b[39;00m config_dict \u001b[38;5;129;01mand\u001b[39;00m config_dict[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mmodel_type\u001b[39m\u001b[38;5;124m\"\u001b[39m] \u001b[38;5;129;01min\u001b[39;00m CONFIG_MAPPING\n\u001b[1;32m-> 1117\u001b[0m trust_remote_code \u001b[38;5;241m=\u001b[39m resolve_trust_remote_code(\n\u001b[0;32m 1118\u001b[0m trust_remote_code, pretrained_model_name_or_path, has_local_code, has_remote_code\n\u001b[0;32m 1119\u001b[0m )\n\u001b[0;32m 1121\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m has_remote_code \u001b[38;5;129;01mand\u001b[39;00m trust_remote_code:\n\u001b[0;32m 1122\u001b[0m class_ref \u001b[38;5;241m=\u001b[39m config_dict[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mauto_map\u001b[39m\u001b[38;5;124m\"\u001b[39m][\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mAutoConfig\u001b[39m\u001b[38;5;124m\"\u001b[39m]\n", "File \u001b[1;32m~\\anaconda3\\Lib\\site-packages\\transformers\\dynamic_module_utils.py:682\u001b[0m, in \u001b[0;36mresolve_trust_remote_code\u001b[1;34m(trust_remote_code, model_name, has_local_code, has_remote_code)\u001b[0m\n\u001b[0;32m 679\u001b[0m signal\u001b[38;5;241m.\u001b[39malarm(\u001b[38;5;241m0\u001b[39m)\n\u001b[0;32m 680\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mException\u001b[39;00m:\n\u001b[0;32m 681\u001b[0m \u001b[38;5;66;03m# OS which does not support signal.SIGALRM\u001b[39;00m\n\u001b[1;32m--> 682\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\n\u001b[0;32m 683\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mThe repository for \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mmodel_name\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m contains custom code which must be executed to correctly \u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m 684\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mload the model. You can inspect the repository content at https://hf.co/\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mmodel_name\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m.\u001b[39m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m 685\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mPlease pass the argument `trust_remote_code=True` to allow custom code to be run.\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m 686\u001b[0m )\n\u001b[0;32m 687\u001b[0m \u001b[38;5;28;01mfinally\u001b[39;00m:\n\u001b[0;32m 688\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m prev_sig_handler \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n", "\u001b[1;31mValueError\u001b[0m: The repository for microsoft/bitnet-b1.58-2B-4T contains custom code which must be executed to correctly load the model. You can inspect the repository content at https://hf.co/microsoft/bitnet-b1.58-2B-4T.\nPlease pass the argument `trust_remote_code=True` to allow custom code to be run." ] } ], "source": [ "import torch\n", "from transformers import AutoModelForCausalLM, AutoTokenizer\n", "\n", "model_id = \"microsoft/bitnet-b1.58-2B-4T\"\n", "\n", "# Load tokenizer and model\n", "tokenizer = AutoTokenizer.from_pretrained(model_id)\n", "model = AutoModelForCausalLM.from_pretrained(\n", " model_id,\n", " torch_dtype=torch.bfloat16\n", ")\n", "\n", "# Apply the chat template\n", "messages = [\n", " {\"role\": \"system\", \"content\": \"You are a helpful AI assistant.\"},\n", " {\"role\": \"user\", \"content\": \"How are you?\"},\n", "]\n", "prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)\n", "chat_input = tokenizer(prompt, return_tensors=\"pt\").to(model.device)\n", "\n", "# Generate response\n", "chat_outputs = model.generate(**chat_input, max_new_tokens=50)\n", "response = tokenizer.decode(chat_outputs[0][chat_input['input_ids'].shape[-1]:], skip_special_tokens=True) # Decode only the response part\n", "print(\"\\nAssistant Response:\", response)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "2b6c0add-3a67-47df-be9d-ed78bbd08a16", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python [conda env:base] *", "language": "python", "name": "conda-base-py" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.7" } }, "nbformat": 4, "nbformat_minor": 5}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194{ "cells": [ { "cell_type": "code", "execution_count": 37, "id": "34a23b48-2ef5-42d3-859c-bf1ce6bf414c", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "تا ۵ ثانیه وقت داری پنجره تلگرام رو فعال کنی...\n", "ارسال متوقف شد.\n" ] } ], "source": [ "import pyautogui\n", "import time\n", "\n", "# چند ثانیه صبر کن تا بتونی پنجره تلگرام رو فعال کنی\n", "print(\"تا ۵ ثانیه وقت داری پنجره تلگرام رو فعال کنی...\")\n", "\n", "time.sleep(10)\n", "\n", "try:\n", " while True:\n", " pyautogui.write(\".\")\n", " pyautogui.press('enter') # هر ۵۰ میلیثانیه یک پیام میفرسته\n", "except KeyboardInterrupt:\n", " print(\"ارسال متوقف شد.\")\n", "\n", "\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": 9, "id": "46f24ef6-81b2-493b-96eb-e3b72aec8df8", "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (46814942.py, line 1)", "output_type": "error", "traceback": [ "\u001b[1;36m Cell \u001b[1;32mIn[9], line 1\u001b[1;36m\u001b[0m\n\u001b[1;33m .\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n" ] } ], "source": [ ".\n", ".\n", ".\n", ".\n", "..8923333\n", "8923333\n", "8923333\n", ".\n", ".\n", ".\n", ".\n", ".\n", "\n", "8923333\n", "8923333\n", "333\n", "8923333\n", "8923333\n", "8923333\n", "\n", "..\n", "\n", "*\n", "*\n", " *\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", " \n", " *\n", "*\n", " *\n", " *\n", "*\n", " *\n", " *\n", "*\n", " *\n", " *\n", "*\n", "\n", "\n", "\n", "\n", "\n", "\n", ".\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", ".\n", ".\n", ".\n", ".*99123\n", "*99123\n", "*99123\n", "*99123\n", "*99123\n", "*99123\n", "\n", ".\n", ".\n", ".\n", ".\n", ".\n", ".\n", ".\n", ".\n", "\n", ".\n", ".\n", ".\n", "..\n", ".\n", ".\n", ".\n", ".\n", "..\n", "..\n", ".\n", ".\n", "..\n", ".\n", ".\n", ".\n", ".\n", "..\n", ".\n", ".\n", ".\n", ".\n", "." ] }, { "cell_type": "code", "execution_count": null, "id": "939146aa-0063-4bba-90ec-ea9d637dda07", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python [conda env:base] *", "language": "python", "name": "conda-base-py" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.7" } }, "nbformat": 4, "nbformat_minor": 5}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "1dabd320-903a-4f6c-9634-e8bd5993f90f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "* Running on local URL: http://127.0.0.1:7860\n", "* To create a public link, set `share=True` in `launch()`.\n" ] }, { "data": { "text/html": [ "<div><iframe src=\"http://127.0.0.1:7860/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>" ], "text/plain": [ "<IPython.core.display.HTML object>" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from transformers import AutoModelForCausalLM, AutoTokenizer\n", "import torch\n", "import gradio as gr\n", "\n", "# مدل و توکنایزر\n", "model_name = \"HuggingFaceTB/SmolLM2-360M-Instruct\"\n", "tokenizer = AutoTokenizer.from_pretrained(model_name)\n", "model = AutoModelForCausalLM.from_pretrained(model_name)\n", "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", "model.to(device)\n", "model.eval()\n", "\n", "# پیامهای اولیه مکالمه\n", "def format_messages(user_prompt):\n", " system_message = \"<|im_start|>system\\n<|im_end|>\\n\"\n", " user_message = f\"<|im_start|>user\\n{user_prompt}<|im_end|>\\n\"\n", " assistant_prefix = \"<|im_start|>assistant\\n\"\n", " full_prompt = system_message + user_message + assistant_prefix\n", " return full_prompt\n", "\n", "# تابع چت\n", "def chat(user_input):\n", " prompt = format_messages(user_input)\n", " inputs = tokenizer(prompt, return_tensors=\"pt\").to(device)\n", "\n", " with torch.no_grad():\n", " outputs = model.generate(\n", " **inputs,\n", " max_new_tokens=256,\n", " do_sample=True,\n", " temperature=0.7,\n", " top_p=0.9,\n", " pad_token_id=tokenizer.eos_token_id\n", " )\n", "\n", " response = tokenizer.decode(outputs[0], skip_special_tokens=True)\n", " \n", " # پاسخ مدل بعد از آخرین <|im_start|>assistant\n", " if \"<|im_start|>assistant\" in response:\n", " response = response.split(\"<|im_start|>assistant\")[-1].strip()\n", " if \"<|im_end|>\" in response:\n", " response = response.split(\"<|im_end|>\")[0].strip()\n", " \n", " return response\n", "\n", "# رابط گرافیکی Gradio\n", "interface = gr.Interface(\n", " fn=chat,\n", " inputs=gr.Textbox(lines=3, placeholder=\"پیام خود را وارد کنید...\"),\n", " outputs=\"text\",\n", " title=\"💬 SmolLM2 Chatbot\",\n", " description=\"مدل سبک و مکالمهمحور SmolLM2 از Hugging Face با فرمت قالب رسمی\"\n", ")\n", "\n", "interface.launch()\n" ] }, { "cell_type": "code", "execution_count": null, "id": "0f00bd7a-f925-4970-aeb6-96f1dcbad3c8", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python [conda env:base] *", "language": "python", "name": "conda-base-py" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.7" } }, "nbformat": 4, "nbformat_minor": 5}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "79c435c0-31ba-4c2f-81b3-90d8e670eb76", "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from matplotlib.animation import FuncAnimation\n", "from mpl_toolkits.mplot3d import Axes3D, art3d\n", "import random\n", "\n", "# Parameters\n", "WORLD_SIZE = 100000\n", "AIRCRAFT_COUNT = 100\n", "RADAR_RANGE = 70000\n", "RADAR_ALTITUDE_LIMIT = 20000 # max altitude radar covers in meters\n", "SCAN_SPEED = 2.0 # degrees per frame\n", "BEAM_WIDTH = 5.0 # degrees width of radar beam\n", "TRACK_LENGTH = 20 # length of tail/track for aircrafts\n", "MAX_ACCELERATION = 5 # m/s^2 max change in velocity per frame\n", "\n", "# Aircraft types with properties\n", "AIRCRAFT_TYPES = {\n", " 'commercial': {'rcs_range': (10, 20), 'color': 'cyan', 'size': 30},\n", " 'military': {'rcs_range': (5, 12), 'color': 'red', 'size': 40},\n", " 'drone': {'rcs_range': (1, 4), 'color': 'yellow', 'size': 20},\n", " 'unknown': {'rcs_range': (0.5, 2), 'color': 'magenta', 'size': 25}\n", "}\n", "\n", "# Event Class with motion\n", "class MovingEvent3D:\n", " def __init__(self, evt_type, center, radius, altitude, velocity):\n", " self.type = evt_type\n", " self.center = np.array(center, dtype=float)\n", " self.radius = radius\n", " self.altitude = altitude\n", " self.velocity = np.array(velocity, dtype=float)\n", " self.active = True\n", " \n", " def update(self):\n", " self.center += self.velocity\n", " # Bounce inside world bounds for x,y\n", " for i in [0, 1]:\n", " if self.center[i] < 0 or self.center[i] > WORLD_SIZE:\n", " self.velocity[i] = -self.velocity[i]\n", " self.center[i] = np.clip(self.center[i], 0, WORLD_SIZE)\n", " # Bounce altitude inside radar altitude limit\n", " if self.altitude < 0 or self.altitude > RADAR_ALTITUDE_LIMIT:\n", " self.velocity[2] = -self.velocity[2]\n", " self.altitude = np.clip(self.altitude, 0, RADAR_ALTITUDE_LIMIT)\n", " # Random on/off toggle for event activity\n", " if random.random() < 0.001:\n", " self.active = not self.active\n", "\n", "def generate_moving_events_3d():\n", " events = []\n", " for _ in range(4):\n", " evt_type = random.choice(['storm', 'no-fly-zone', 'jamming', 'interference'])\n", " center = np.random.uniform(0, WORLD_SIZE, 2)\n", " altitude = np.random.uniform(0, RADAR_ALTITUDE_LIMIT)\n", " radius = {'storm': 15000, 'no-fly-zone': 10000, 'jamming': 8000, 'interference':12000}[evt_type]\n", " velocity = np.random.uniform(-50, 50, 3)\n", " events.append(MovingEvent3D(evt_type, center, radius, altitude, velocity))\n", " return events\n", "\n", "world_events = generate_moving_events_3d()\n", "\n", "# Generate aircrafts with altitude, track history, type and variable velocity\n", "def generate_aircraft_3d():\n", " aircrafts = []\n", " for i in range(AIRCRAFT_COUNT):\n", " ac_type = random.choices(list(AIRCRAFT_TYPES.keys()), weights=[0.5,0.3,0.15,0.05])[0]\n", " rcs_min, rcs_max = AIRCRAFT_TYPES[ac_type]['rcs_range']\n", " ac = {\n", " 'id': i,\n", " 'type': ac_type,\n", " 'position': np.array([*np.random.uniform(0, WORLD_SIZE, 2), np.random.uniform(0, RADAR_ALTITUDE_LIMIT)]),\n", " 'velocity': np.random.uniform(-50, 50, 3),\n", " 'rcs': random.uniform(rcs_min, rcs_max),\n", " 'callsign': f\"{ac_type[:2].upper()}{i:03}\",\n", " 'emergency': random.random() < 0.03,\n", " 'track': [],\n", " 'acceleration': np.zeros(3),\n", " }\n", " aircrafts.append(ac)\n", " return aircrafts\n", "\n", "aircrafts = generate_aircraft_3d()\n", "radar_angle = [0]\n", "radar_pos = np.array([WORLD_SIZE/2, WORLD_SIZE/2, 0])\n", "paused = [False]\n", "\n", "def is_event_active_3d(pos):\n", " for evt in world_events:\n", " if evt.active:\n", " d_xy = np.linalg.norm(pos[:2] - evt.center)\n", " dz = abs(pos[2] - evt.altitude)\n", " if d_xy < evt.radius and dz < evt.radius / 2:\n", " return evt.type\n", " return None\n", "\n", "def detect_3d(ac, radar_pos):\n", " delta = ac['position'] - radar_pos\n", " rng = np.linalg.norm(delta)\n", " if rng > RADAR_RANGE or ac['position'][2] > RADAR_ALTITUDE_LIMIT:\n", " return False\n", " bearing = (np.degrees(np.arctan2(delta[1], delta[0])) + 360) % 360\n", " diff = abs((bearing - radar_angle[0] + 180) % 360 - 180)\n", " if diff > BEAM_WIDTH / 2:\n", " return False\n", " evt = is_event_active_3d(ac['position'])\n", " snr_val = 20 - 20*np.log10(rng + 1) + ac['rcs']\n", " if evt == 'jamming':\n", " snr_val -= 50\n", " elif evt == 'storm':\n", " snr_val -= 15\n", " elif evt == 'interference':\n", " snr_val -= 25\n", " prob = 1 / (1 + np.exp(-(snr_val - 10)))\n", " # Introduce random detection noise\n", " noise = np.random.normal(0, 0.1)\n", " return np.random.rand() < (prob + noise)\n", "\n", "# Setup plot\n", "fig = plt.figure(figsize=(14, 10))\n", "ax = fig.add_subplot(111, projection='3d')\n", "ax.set_xlim(0, WORLD_SIZE)\n", "ax.set_ylim(0, WORLD_SIZE)\n", "ax.set_zlim(0, RADAR_ALTITUDE_LIMIT)\n", "ax.set_facecolor('black')\n", "\n", "# Scatter for different types of aircrafts (dynamic update)\n", "all_scatter = ax.scatter([], [], [], c=[], s=[], label='Aircraft')\n", "detected_scatter = ax.scatter([], [], [], c='lime', s=60, label='Detected')\n", "emergency_scatter = ax.scatter([], [], [], c='orange', s=80, marker='^', label='Emergency')\n", "radar_sweep_line, = ax.plot([], [], [], c='cyan', linewidth=3, label='Radar Sweep')\n", "\n", "# Track lines for aircrafts\n", "track_lines = [ax.plot([], [], [], c='white', alpha=0.3, linewidth=1)[0] for _ in range(AIRCRAFT_COUNT)]\n", "\n", "event_spheres = []\n", "event_colors = {'storm':'blue', 'no-fly-zone':'yellow', 'jamming':'magenta', 'interference':'purple'}\n", "\n", "def plot_sphere(center, radius, color):\n", " u = np.linspace(0, 2*np.pi, 20)\n", " v = np.linspace(0, np.pi, 20)\n", " x = center[0] + radius * np.outer(np.cos(u), np.sin(v))\n", " y = center[1] + radius * np.outer(np.sin(u), np.sin(v))\n", " z = center[2] + radius * np.outer(np.ones(np.size(u)), np.cos(v))\n", " return ax.plot_surface(x, y, z, color=color, alpha=0.15)\n", "\n", "for evt in world_events:\n", " sphere = plot_sphere(np.array([*evt.center, evt.altitude]), evt.radius, event_colors[evt.type])\n", " event_spheres.append(sphere)\n", "\n", "# Radar range circle on ground\n", "radar_circle = plt.Circle((radar_pos[0], radar_pos[1]), RADAR_RANGE, color='cyan', alpha=0.1)\n", "ax.add_patch(radar_circle)\n", "art3d.pathpatch_2d_to_3d(radar_circle, z=0, zdir=\"z\")\n", "\n", "def update(frame):\n", " if paused[0]:\n", " return\n", " \n", " # بهروزرسانی زاویه رادار\n", " radar_angle[0] = (radar_angle[0] + 1) % 360\n", "\n", " all_pos = []\n", " all_colors = []\n", " all_sizes = []\n", "\n", " detected_pos = []\n", " emergency_pos = []\n", "\n", " for ac in aircrafts:\n", " # محدود کردن سرعت\n", " v_mag = np.linalg.norm(ac['velocity'])\n", " max_speed = 250 # m/s\n", " if v_mag > max_speed:\n", " ac['velocity'] = (ac['velocity'] / v_mag) * max_speed\n", " \n", " # بهروزرسانی موقعیت\n", " ac['position'] += ac['velocity']\n", " \n", " # برخورد به دیوارههای جهان\n", " for i in [0, 1]:\n", " if ac['position'][i] < 0 or ac['position'][i] > WORLD_SIZE:\n", " ac['velocity'][i] = -ac['velocity'][i]\n", " ac['position'][i] = np.clip(ac['position'][i], 0, WORLD_SIZE)\n", " if ac['position'][2] < 0 or ac['position'][2] > RADAR_ALTITUDE_LIMIT:\n", " ac['velocity'][2] = -ac['velocity'][2]\n", " ac['position'][2] = np.clip(ac['position'][2], 0, RADAR_ALTITUDE_LIMIT)\n", " \n", " # ثبت رد حرکت\n", " ac['track'].append(ac['position'].copy())\n", " if len(ac['track']) > TRACK_LENGTH:\n", " ac['track'].pop(0)\n", " \n", " all_pos.append(ac['position'])\n", " all_colors.append(AIRCRAFT_TYPES[ac['type']]['color'])\n", " all_sizes.append(AIRCRAFT_TYPES[ac['type']]['size'])\n", " \n", " if detect_3d(ac, radar_pos):\n", " detected_pos.append(ac['position'])\n", " if ac['emergency']:\n", " emergency_pos.append(ac['position'])\n", "\n", " # تبدیل به np.array\n", " all_pos = np.array(all_pos)\n", " detected_pos = np.array(detected_pos)\n", " emergency_pos = np.array(emergency_pos)\n", "\n", " # آپدیت scatter کل هواپیماها\n", " if len(all_pos) > 0:\n", " all_scatter._offsets3d = (all_pos[:,0], all_pos[:,1], all_pos[:,2])\n", " all_scatter.set_color(all_colors)\n", " all_scatter.set_sizes(all_sizes)\n", " else:\n", " all_scatter._offsets3d = ([], [], [])\n", " all_scatter.set_color([])\n", " all_scatter.set_sizes([])\n", "\n", " # آپدیت scatter هواپیماهای تشخیص داده شده\n", " if len(detected_pos) > 0:\n", " detected_scatter._offsets3d = (detected_pos[:,0], detected_pos[:,1], detected_pos[:,2])\n", " detected_scatter.set_sizes([60]*len(detected_pos))\n", " else:\n", " detected_scatter._offsets3d = ([], [], [])\n", " detected_scatter.set_sizes([])\n", "\n", " # آپدیت scatter هواپیماهای اضطراری\n", " if len(emergency_pos) > 0:\n", " emergency_scatter._offsets3d = (emergency_pos[:,0], emergency_pos[:,1], emergency_pos[:,2])\n", " emergency_scatter.set_sizes([80]*len(emergency_pos))\n", " else:\n", " emergency_scatter._offsets3d = ([], [], [])\n", " emergency_scatter.set_sizes([])\n", "\n", " # بهروزرسانی خطوط رد حرکت\n", " for i, ac in enumerate(aircrafts):\n", " if len(ac['track']) >= 2:\n", " track_arr = np.array(ac['track'])\n", " track_lines[i].set_data(track_arr[:,0], track_arr[:,1])\n", " track_lines[i].set_3d_properties(track_arr[:,2])\n", " else:\n", " track_lines[i].set_data([], [])\n", " track_lines[i].set_3d_properties([])\n", "\n", " # بهروزرسانی خط اسکن رادار\n", " angle_rad = np.radians(radar_angle[0])\n", " x = [radar_pos[0], radar_pos[0] + RADAR_RANGE * np.cos(angle_rad)]\n", " y = [radar_pos[1], radar_pos[1] + RADAR_RANGE * np.sin(angle_rad)]\n", " z = [0, 0]\n", " radar_sweep_line.set_data(x, y)\n", " radar_sweep_line.set_3d_properties(z)\n", "\n", " ax.set_title(f\"3D Radar Simulation - Scan Angle: {radar_angle[0]:.1f}°\")\n", "\n", " \n", "def on_key(event):\n", " if event.key == ' ':\n", " paused[0] = not paused[0]\n", "\n", "fig.canvas.mpl_connect('key_press_event', on_key)\n", "\n", "ani = FuncAnimation(fig, update, interval=50)\n", "plt.legend(loc='upper right')\n", "plt.show()\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python [conda env:base] *", "language": "python", "name": "conda-base-py" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.7" } }, "nbformat": 4, "nbformat_minor": 5}123version https://git-lfs.github.com/spec/v1oid sha256:d8d7aa882c8afb95efe250e6849296fb22ca1695eff05da8a168ac658cfb750asize 692123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869import cv2
import numpy as np
# استفاده از الگوریتم پیشرفته KNN برای background subtraction
back_sub = cv2.createBackgroundSubtractorKNN(history=500, dist2Threshold=400, detectShadows=True)
# تابع برای محاسبه مرکز (centroid)
def get_centroid(x, y, w, h):
return (int(x + w / 2), int(y + h / 2))
# گرفتن تصویر از دوربین
cap = cv2.VideoCapture(0)
# Kalman Filter برای ردیابی دقیقتر
kalman = cv2.KalmanFilter(4, 2)
kalman.measurementMatrix = np.array([[1, 0, 0, 0], [0, 1, 0, 0]], np.float32)
kalman.transitionMatrix = np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1]], np.float32)
kalman.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)
while True:
ret, frame = cap.read()
if not ret:
break
# تبدیل تصویر به خاکستری
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# دریافت ماسک اشیاء متحرک
fg_mask = back_sub.apply(frame)
# حذف نویز پیشرفته با استفاده از GaussianBlur و MedianBlur
fg_mask = cv2.GaussianBlur(fg_mask, (5, 5), 0) # حذف نویز با بلور گوسی
fg_mask = cv2.medianBlur(fg_mask, 5) # حذف نویز با استفاده از MedianBlur
# اعمال عملیات مورفولوژیکی پیچیدهتر برای حذف نویز و سایهها
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7)) # هسته بزرگتر
fg_mask = cv2.morphologyEx(fg_mask, cv2.MORPH_CLOSE, kernel, iterations=2) # استفاده از عملیات CLOSE
fg_mask = cv2.dilate(fg_mask, kernel, iterations=3) # افزایش سایز ماسک
# پیدا کردن کانتورها
contours, _ = cv2.findContours(fg_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
area = cv2.contourArea(cnt)
if area > 500: # فقط اشیاء بزرگتر از این اندازه رو بررسی کن
x, y, w, h = cv2.boundingRect(cnt)
centroid = get_centroid(x, y, w, h)
# استفاده از Kalman Filter برای پیشبینی موقعیت شیء
kalman.correct(np.array([np.float32(centroid[0]), np.float32(centroid[1])]))
prediction = kalman.predict()
predicted_x, predicted_y = int(prediction[0]), int(prediction[1])
# رسم باکس و پیشبینی موقعیت
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.circle(frame, centroid, 4, (0, 0, 255), -1)
cv2.putText(frame, "Moving Object", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
cv2.circle(frame, (predicted_x, predicted_y), 4, (255, 0, 0), -1) # پیشبینی موقعیت
# نمایش تصویر
cv2.imshow('Optimized Object Tracking', frame)
# خروج از برنامه با کلید ESC
if cv2.waitKey(1) & 0xFF == 27:
break
cap.release()
cv2.destroyAllWindows()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153import cv2
import numpy as np
import time
from sklearn.neighbors import KNeighborsClassifier
from collections import defaultdict, deque
# Create background subtractor for motion detection
back_sub = cv2.createBackgroundSubtractorKNN(history=500, dist2Threshold=400, detectShadows=True)
cap = cv2.VideoCapture(0)
# Store object traces
object_traces = defaultdict(lambda: deque(maxlen=30)) # Last 30 points of each object
object_last_seen = {}
object_id_counter = 0
# For real-time learning
knn = KNeighborsClassifier(n_neighbors=3)
features_set = []
labels_set = []
frame_count = 0
learning_interval = 30
# Timer for data collection
start_time = time.time()
learning_time_limit = 60 # 1 minute for data collection
# Variable to avoid predicting before training
is_trained = False
def apply_noise_reduction(mask):
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=2)
mask = cv2.dilate(mask, kernel, iterations=1)
return mask
def get_centroid(x, y, w, h):
return (int(x + w / 2), int(y + h / 2))
def calculate_direction(trace):
if len(trace) < 2:
return "-"
dx = trace[-1][0] - trace[0][0]
dy = trace[-1][1] - trace[0][1]
if abs(dx) > abs(dy):
return "Left" if dx < 0 else "Right"
else:
return "Up" if dy < 0 else "Down"
def calculate_speed(trace, duration):
if len(trace) < 2 or duration == 0:
return 0
dist = np.linalg.norm(np.array(trace[-1]) - np.array(trace[0]))
return dist / duration
def count_direction_changes(trace):
changes = 0
for i in range(2, len(trace)):
dx1 = trace[i-1][0] - trace[i-2][0]
dx2 = trace[i][0] - trace[i-1][0]
if dx1 * dx2 < 0: # Horizontal direction change
changes += 1
return changes
while True:
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
fg_mask = back_sub.apply(frame)
fg_mask = apply_noise_reduction(fg_mask)
contours, _ = cv2.findContours(fg_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
current_ids = []
predicted = 1 # Default prediction value (if no prediction is made)
for cnt in contours:
area = cv2.contourArea(cnt)
if area < 150:
continue
x, y, w, h = cv2.boundingRect(cnt)
centroid = get_centroid(x, y, w, h)
# Identify or create a new ID for the object
matched_id = None
for oid, trace in object_traces.items():
if np.linalg.norm(np.array(trace[-1]) - np.array(centroid)) < 50:
matched_id = oid
break
if matched_id is None:
matched_id = object_id_counter
object_id_counter += 1
object_traces[matched_id].append(centroid)
object_last_seen[matched_id] = time.time()
current_ids.append(matched_id)
trace = object_traces[matched_id]
duration = time.time() - object_last_seen[matched_id] + 0.001
speed = calculate_speed(trace, duration)
direction = calculate_direction(trace)
direction_changes = count_direction_changes(trace)
total_move = sum(np.linalg.norm(np.array(trace[i]) - np.array(trace[i-1])) for i in range(1, len(trace)))
# Feature for the model
feature = [w, h, centroid[0], centroid[1], area, speed, direction_changes]
label = 1 # Default label: Normal
# Simple automatic labeling:
if speed > 100 or direction_changes > 4:
label = 2 # Suspicious
features_set.append(feature)
labels_set.append(label)
# Train the model only after enough data is collected
if time.time() - start_time < learning_time_limit:
# Still in data collection phase
continue
elif not is_trained: # If the model hasn't been trained yet
if len(features_set) > 10:
knn.fit(features_set, labels_set) # Train the model
is_trained = True # Model is trained
print("Model updated.")
# Prediction only after training
if is_trained:
predicted = knn.predict([feature])[0]
# Draw information on the frame
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0) if label == 1 else (0, 0, 255), 2)
cv2.circle(frame, centroid, 4, (255, 255, 255), -1)
cv2.putText(frame, f"ID: {matched_id} | Direction: {direction} | Speed: {int(speed)}", (x, y - 25),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 0), 1)
cv2.putText(frame, f"Behavior: {'Normal' if predicted == 1 else 'Suspicious'}", (x, y - 5),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 1)
frame_count += 1
# Remove old object IDs
for oid in list(object_last_seen):
if time.time() - object_last_seen[oid] > 2:
object_traces.pop(oid, None)
object_last_seen.pop(oid, None)
cv2.imshow("Behavioral Intelligence", frame)
if cv2.waitKey(1) & 0xFF == 27:
break
cap.release()
cv2.destroyAllWindows()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147import cv2
import numpy as np
import time
from sklearn.neighbors import KNeighborsClassifier
from collections import defaultdict, deque
# Create background subtractor for motion detection
back_sub = cv2.createBackgroundSubtractorKNN(history=500, dist2Threshold=400, detectShadows=True)
cap = cv2.VideoCapture(0)
# Store object traces
object_traces = defaultdict(lambda: deque(maxlen=30)) # Last 30 points of each object
object_last_seen = {}
object_id_counter = 0
# For real-time learning
knn = KNeighborsClassifier(n_neighbors=3)
features_set = []
labels_set = []
# Timer for real-time learning and training interval
start_time = time.time()
training_interval = 5 # 5 seconds for real-time training
# Variable to avoid predicting before training
is_trained = False
def apply_noise_reduction(mask):
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=2)
mask = cv2.dilate(mask, kernel, iterations=1)
return mask
def get_centroid(x, y, w, h):
return (int(x + w / 2), int(y + h / 2))
def calculate_direction(trace):
if len(trace) < 2:
return "-"
dx = trace[-1][0] - trace[0][0]
dy = trace[-1][1] - trace[0][1]
if abs(dx) > abs(dy):
return "Left" if dx < 0 else "Right"
else:
return "Up" if dy < 0 else "Down"
def calculate_speed(trace, duration):
if len(trace) < 2 or duration == 0:
return 0
dist = np.linalg.norm(np.array(trace[-1]) - np.array(trace[0]))
return dist / duration
def count_direction_changes(trace):
changes = 0
for i in range(2, len(trace)):
dx1 = trace[i-1][0] - trace[i-2][0]
dx2 = trace[i][0] - trace[i-1][0]
if dx1 * dx2 < 0: # Horizontal direction change
changes += 1
return changes
while True:
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
fg_mask = back_sub.apply(frame)
fg_mask = apply_noise_reduction(fg_mask)
contours, _ = cv2.findContours(fg_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
current_ids = []
predicted = 1 # Default prediction value (if no prediction is made)
for cnt in contours:
area = cv2.contourArea(cnt)
if area < 150:
continue
x, y, w, h = cv2.boundingRect(cnt)
centroid = get_centroid(x, y, w, h)
# Identify or create a new ID for the object
matched_id = None
for oid, trace in object_traces.items():
if np.linalg.norm(np.array(trace[-1]) - np.array(centroid)) < 50:
matched_id = oid
break
if matched_id is None:
matched_id = object_id_counter
object_id_counter += 1
object_traces[matched_id].append(centroid)
object_last_seen[matched_id] = time.time()
current_ids.append(matched_id)
trace = object_traces[matched_id]
duration = time.time() - object_last_seen[matched_id] + 0.001
speed = calculate_speed(trace, duration)
direction = calculate_direction(trace)
direction_changes = count_direction_changes(trace)
total_move = sum(np.linalg.norm(np.array(trace[i]) - np.array(trace[i-1])) for i in range(1, len(trace)))
# Feature for the model
feature = [w, h, centroid[0], centroid[1], area, speed, direction_changes]
label = 1 # Default label: Normal
# Simple automatic labeling:
if speed > 100 or direction_changes > 4:
label = 2 # Suspicious
features_set.append(feature)
labels_set.append(label)
# Retrain the model every 5 seconds
if time.time() - start_time > training_interval:
if len(features_set) > 10:
knn.fit(features_set, labels_set) # Train the model
is_trained = True # Model is trained
print("Model updated.")
start_time = time.time() # Reset the timer after retraining
# Prediction only after training
if is_trained:
predicted = knn.predict([feature])[0]
# Draw information on the frame
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0) if label == 1 else (0, 0, 255), 2)
cv2.circle(frame, centroid, 4, (255, 255, 255), -1)
cv2.putText(frame, f"ID: {matched_id} | Direction: {direction} | Speed: {int(speed)}", (x, y - 25),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 0), 1)
cv2.putText(frame, f"Behavior: {'Normal' if predicted == 1 else 'Suspicious'}", (x, y - 5),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 1)
# Remove old object IDs
for oid in list(object_last_seen):
if time.time() - object_last_seen[oid] > 2:
object_traces.pop(oid, None)
object_last_seen.pop(oid, None)
cv2.imshow("Behavioral Intelligence", frame)
if cv2.waitKey(1) & 0xFF == 27:
break
cap.release()
cv2.destroyAllWindows()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157import cv2
import numpy as np
import time
from sklearn.neighbors import KNeighborsClassifier
from collections import defaultdict, deque
# Create background subtractor for motion detection
back_sub = cv2.createBackgroundSubtractorKNN(history=500, dist2Threshold=400, detectShadows=True)
cap = cv2.VideoCapture(0)
# Store object traces
object_traces = defaultdict(lambda: deque(maxlen=30)) # Last 30 points of each object
object_last_seen = {}
object_id_counter = 0
# For real-time learning
knn = KNeighborsClassifier(n_neighbors=3)
features_set = []
labels_set = []
# Timer for real-time learning and training interval
start_time = time.time()
training_interval = 5 # 5 seconds for real-time training
# Variable to avoid predicting before training
is_trained = False
# Memory storage for past predictions and features
memory = defaultdict(list) # Store memory of features and predictions for each object
def apply_noise_reduction(mask):
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=2)
mask = cv2.dilate(mask, kernel, iterations=1)
return mask
def get_centroid(x, y, w, h):
return (int(x + w / 2), int(y + h / 2))
def calculate_direction(trace):
if len(trace) < 2:
return "-"
dx = trace[-1][0] - trace[0][0]
dy = trace[-1][1] - trace[0][1]
if abs(dx) > abs(dy):
return "Left" if dx < 0 else "Right"
else:
return "Up" if dy < 0 else "Down"
def calculate_speed(trace, duration):
if len(trace) < 2 or duration == 0:
return 0
dist = np.linalg.norm(np.array(trace[-1]) - np.array(trace[0]))
return dist / duration
def count_direction_changes(trace):
changes = 0
for i in range(2, len(trace)):
dx1 = trace[i-1][0] - trace[i-2][0]
dx2 = trace[i][0] - trace[i-1][0]
if dx1 * dx2 < 0: # Horizontal direction change
changes += 1
return changes
while True:
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
fg_mask = back_sub.apply(frame)
fg_mask = apply_noise_reduction(fg_mask)
contours, _ = cv2.findContours(fg_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
current_ids = []
predicted = 1 # Default prediction value (if no prediction is made)
for cnt in contours:
area = cv2.contourArea(cnt)
if area < 150:
continue
x, y, w, h = cv2.boundingRect(cnt)
centroid = get_centroid(x, y, w, h)
# Identify or create a new ID for the object
matched_id = None
for oid, trace in object_traces.items():
if np.linalg.norm(np.array(trace[-1]) - np.array(centroid)) < 50:
matched_id = oid
break
if matched_id is None:
matched_id = object_id_counter
object_id_counter += 1
object_traces[matched_id].append(centroid)
object_last_seen[matched_id] = time.time()
current_ids.append(matched_id)
trace = object_traces[matched_id]
duration = time.time() - object_last_seen[matched_id] + 0.001
speed = calculate_speed(trace, duration)
direction = calculate_direction(trace)
direction_changes = count_direction_changes(trace)
total_move = sum(np.linalg.norm(np.array(trace[i]) - np.array(trace[i-1])) for i in range(1, len(trace)))
# Feature for the model
feature = [w, h, centroid[0], centroid[1], area, speed, direction_changes]
label = 1 # Default label: Normal
# Simple automatic labeling:
if speed > 100 or direction_changes > 4:
label = 2 # Suspicious
features_set.append(feature)
labels_set.append(label)
# Store features and predictions in memory
memory[matched_id].append({
'features': feature,
'prediction': label
})
# Retrain the model every 5 seconds
if time.time() - start_time > training_interval:
if len(features_set) > 10:
knn.fit(features_set, labels_set) # Train the model
is_trained = True # Model is trained
print("Model updated.")
start_time = time.time() # Reset the timer after retraining
# Prediction only after training
if is_trained:
predicted = knn.predict([feature])[0]
# Draw information on the frame
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0) if label == 1 else (0, 0, 255), 2)
cv2.circle(frame, centroid, 4, (255, 255, 255), -1)
cv2.putText(frame, f"ID: {matched_id} | Direction: {direction} | Speed: {int(speed)}", (x, y - 25),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 0), 1)
cv2.putText(frame, f"Behavior: {'Normal' if predicted == 1 else 'Suspicious'}", (x, y - 5),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 1)
# Remove old object IDs from memory
for oid in list(object_last_seen):
if time.time() - object_last_seen[oid] > 2:
object_traces.pop(oid, None)
object_last_seen.pop(oid, None)
memory.pop(oid, None) # Remove from memory as well
cv2.imshow("Behavioral Intelligence", frame)
if cv2.waitKey(1) & 0xFF == 27:
break
cap.release()
cv2.destroyAllWindows()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172import cv2
import numpy as np
import time
from sklearn.neighbors import KNeighborsClassifier
from collections import defaultdict, deque
# Create background subtractor for motion detection
back_sub = cv2.createBackgroundSubtractorKNN(history=500, dist2Threshold=400, detectShadows=True)
cap = cv2.VideoCapture(0)
# Store object traces
object_traces = defaultdict(lambda: deque(maxlen=30)) # Last 30 points of each object
object_last_seen = {}
object_id_counter = 0
# For real-time learning
knn = KNeighborsClassifier(n_neighbors=3)
features_set = []
labels_set = []
# Timer for real-time learning and training interval
start_time = time.time()
training_interval = 5 # 5 seconds for real-time training
# Variable to avoid predicting before training
is_trained = False
# Memory storage for past predictions and features (long-term memory)
long_term_memory = defaultdict(list) # Store memory of features and predictions for each object
# Function to apply noise reduction (post-processing)
def apply_noise_reduction(mask):
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=2)
mask = cv2.dilate(mask, kernel, iterations=1)
return mask
def get_centroid(x, y, w, h):
return (int(x + w / 2), int(y + h / 2))
# Function to calculate the direction of movement
def calculate_direction(trace):
if len(trace) < 2:
return "-"
dx = trace[-1][0] - trace[0][0]
dy = trace[-1][1] - trace[0][1]
if abs(dx) > abs(dy):
return "Left" if dx < 0 else "Right"
else:
return "Up" if dy < 0 else "Down"
# Function to calculate speed based on trace distance and duration
def calculate_speed(trace, duration):
if len(trace) < 2 or duration == 0:
return 0
dist = np.linalg.norm(np.array(trace[-1]) - np.array(trace[0]))
return dist / duration
# Function to count the number of direction changes (for complexity detection)
def count_direction_changes(trace):
changes = 0
for i in range(2, len(trace)):
dx1 = trace[i-1][0] - trace[i-2][0]
dx2 = trace[i][0] - trace[i-1][0]
if dx1 * dx2 < 0: # Horizontal direction change
changes += 1
return changes
# Function to check if an object is old (not detected for a while)
def is_old_object(object_id, threshold_time=10):
# Threshold time is how long since last seen for the object to be considered "old"
if time.time() - object_last_seen[object_id] > threshold_time:
return True
return False
while True:
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
fg_mask = back_sub.apply(frame)
fg_mask = apply_noise_reduction(fg_mask)
contours, _ = cv2.findContours(fg_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
current_ids = []
predicted = 1 # Default prediction value (if no prediction is made)
for cnt in contours:
area = cv2.contourArea(cnt)
if area < 150:
continue
x, y, w, h = cv2.boundingRect(cnt)
centroid = get_centroid(x, y, w, h)
# Identify or create a new ID for the object
matched_id = None
for oid, trace in object_traces.items():
if np.linalg.norm(np.array(trace[-1]) - np.array(centroid)) < 50:
matched_id = oid
break
if matched_id is None:
matched_id = object_id_counter
object_id_counter += 1
object_traces[matched_id].append(centroid)
object_last_seen[matched_id] = time.time()
current_ids.append(matched_id)
trace = object_traces[matched_id]
duration = time.time() - object_last_seen[matched_id] + 0.001
speed = calculate_speed(trace, duration)
direction = calculate_direction(trace)
direction_changes = count_direction_changes(trace)
total_move = sum(np.linalg.norm(np.array(trace[i]) - np.array(trace[i-1])) for i in range(1, len(trace)))
# Feature for the model
feature = [w, h, centroid[0], centroid[1], area, speed, direction_changes]
label = 1 # Default label: Normal
# Simple automatic labeling based on speed and direction changes:
if speed > 100 or direction_changes > 4:
label = 2 # Suspicious
features_set.append(feature)
labels_set.append(label)
# Store features and predictions in long-term memory
long_term_memory[matched_id].append({
'features': feature,
'prediction': label
})
# Retrain the model every 5 seconds
if time.time() - start_time > training_interval:
if len(features_set) > 10:
knn.fit(features_set, labels_set) # Train the model
is_trained = True # Model is trained
print("Model updated.")
start_time = time.time() # Reset the timer after retraining
# Prediction only after training
if is_trained:
predicted = knn.predict([feature])[0]
# Draw information on the frame
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0) if label == 1 else (0, 0, 255), 2)
cv2.circle(frame, centroid, 4, (255, 255, 255), -1)
cv2.putText(frame, f"ID: {matched_id} | Direction: {direction} | Speed: {int(speed)}", (x, y - 25),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 0), 1)
cv2.putText(frame, f"Behavior: {'Normal' if predicted == 1 else 'Suspicious'}", (x, y - 5),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 1)
# Check if the object is old and mark it
if is_old_object(matched_id):
cv2.putText(frame, f"Old Object", (x, y - 50), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)
# Remove old object IDs from memory
for oid in list(object_last_seen):
if time.time() - object_last_seen[oid] > 2:
object_traces.pop(oid, None)
object_last_seen.pop(oid, None)
long_term_memory.pop(oid, None) # Remove from long-term memory as well
cv2.imshow("Behavioral Intelligence", frame)
if cv2.waitKey(1) & 0xFF == 27:
break
cap.release()
cv2.destroyAllWindows()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114import cv2
import numpy as np
from collections import deque, defaultdict
import time
# پارامترها
trace_len = 20
min_area = 500
# حافظه
object_traces = defaultdict(lambda: deque(maxlen=trace_len))
long_term_memory = defaultdict(list)
next_object_id = 1
object_centroids = {}
def count_direction_changes(trace):
count = 0
for i in range(2, len(trace)):
v1 = np.array(trace[i - 1]) - np.array(trace[i - 2])
v2 = np.array(trace[i]) - np.array(trace[i - 1])
if np.dot(v1, v2) < 0:
count += 1
return count
def extract_features(trace):
if len(trace) < 2:
return [0, 0, 0, 0]
dx = trace[-1][0] - trace[0][0]
dy = trace[-1][1] - trace[0][1]
total_distance = sum(np.linalg.norm(np.array(trace[i]) - np.array(trace[i-1])) for i in range(1, len(trace)))
avg_speed = total_distance / (len(trace) + 1e-6)
direction_changes = count_direction_changes(trace)
return [dx, dy, avg_speed, direction_changes]
def ai_brain(trace, memory):
if len(trace) < 3:
return "Unknown"
dx, dy, speed, changes = extract_features(trace)
if len(memory) >= 5 and memory.count("Erratic") > 3:
return "Suspicious"
if speed > 150 and changes > 4:
return "Erratic"
if speed < 5 and changes == 0:
return "Idle"
return "Normal"
def get_color(i):
np.random.seed(i)
return tuple(int(x) for x in np.random.randint(100, 255, 3))
# آمادهسازی دوربین
cap = cv2.VideoCapture(0)
ret, prev = cap.read()
prev_gray = cv2.cvtColor(prev, cv2.COLOR_BGR2GRAY)
prev_gray = cv2.GaussianBlur(prev_gray, (21, 21), 0)
while True:
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray_blur = cv2.GaussianBlur(gray, (21, 21), 0)
# محاسبه اختلاف فریمها
delta = cv2.absdiff(prev_gray, gray_blur)
thresh = cv2.threshold(delta, 25, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.dilate(thresh, None, iterations=2)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
current_centroids = []
for cnt in contours:
if cv2.contourArea(cnt) < min_area:
continue
(x, y, w, h) = cv2.boundingRect(cnt)
cx, cy = x + w // 2, y + h // 2
current_centroids.append((cx, cy))
matched_id = None
# تطبیق با شیء قبلی
for object_id, last_centroid in object_centroids.items():
if np.linalg.norm(np.array([cx, cy]) - np.array(last_centroid)) < 50:
matched_id = object_id
break
if matched_id is None:
matched_id = next_object_id
next_object_id += 1
object_centroids[matched_id] = (cx, cy)
object_traces[matched_id].append((cx, cy))
trace = object_traces[matched_id]
behavior = ai_brain(trace, [m['status'] for m in long_term_memory[matched_id]])
long_term_memory[matched_id].append({'status': behavior, 'timestamp': time.time()})
color = get_color(matched_id)
cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
cv2.putText(frame, f"ID {matched_id}", (x, y - 20), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
cv2.putText(frame, f"Behavior: {behavior}", (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 1)
# پاکسازی اشیاء غیرفعال
inactive_ids = [obj_id for obj_id in object_centroids if obj_id not in [id for id, _ in object_centroids.items()]]
for iid in inactive_ids:
object_centroids.pop(iid, None)
prev_gray = gray_blur.copy()
cv2.imshow("Motion AI", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cap.release()
cv2.destroyAllWindows()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147import cv2
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
# ======== AI MODEL (PyTorch) ========
device = torch.device("cpu")
label_map = {"Idle": 0, "Normal": 1, "Erratic": 2}
reverse_label = {v: k for k, v in label_map.items()}
class BehaviorAI(nn.Module):
def __init__(self):
super().__init__()
self.model = nn.Sequential(
nn.Linear(4, 16),
nn.ReLU(),
nn.Linear(16, 8),
nn.ReLU(),
nn.Linear(8, 3)
)
self.loss_fn = nn.CrossEntropyLoss()
self.optimizer = optim.Adam(self.model.parameters(), lr=0.001)
def forward(self, x):
return self.model(x)
def predict_behavior(self, features):
self.model.eval()
with torch.no_grad():
x = torch.tensor([features], dtype=torch.float32).to(device)
logits = self.model(x)
pred = torch.argmax(logits, dim=-1).item()
return reverse_label[pred]
def learn_from(self, features, label):
self.model.train()
x = torch.tensor([features], dtype=torch.float32).to(device)
y = torch.tensor([label_map[label]], dtype=torch.long).to(device)
logits = self.model(x)
loss = self.loss_fn(logits, y)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
# ======== FEATURE EXTRACTION ========
def extract_features(trace):
if len(trace) < 2:
return [0, 0, 0, 0]
dx = trace[-1][0] - trace[0][0]
dy = trace[-1][1] - trace[0][1]
speeds = []
directions = []
for i in range(1, len(trace)):
x1, y1 = trace[i-1]
x2, y2 = trace[i]
dist = np.linalg.norm([x2 - x1, y2 - y1])
speeds.append(dist)
directions.append(np.arctan2(y2 - y1, x2 - x1))
avg_speed = np.mean(speeds)
direction_changes = np.sum(np.abs(np.diff(directions)))
return [dx, dy, avg_speed, direction_changes]
# ======== MAIN REAL-TIME TRACKING ========
cap = cv2.VideoCapture(0) # یا 'video.mp4' برای فایل
bg_subtractor = cv2.createBackgroundSubtractorMOG2()
traces = {}
next_id = 0
ai = BehaviorAI()
while True:
ret, frame = cap.read()
if not ret:
break
fgmask = bg_subtractor.apply(frame)
contours, _ = cv2.findContours(fgmask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
current_positions = []
for cnt in contours:
if cv2.contourArea(cnt) < 500:
continue
x, y, w, h = cv2.boundingRect(cnt)
cx, cy = x + w // 2, y + h // 2
current_positions.append((cx, cy))
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
new_traces = {}
matched_ids = set()
for cx, cy in current_positions:
min_dist = float('inf')
matched_id = None
for id, trace in traces.items():
if len(trace) == 0:
continue
prev_x, prev_y = trace[-1]
dist = np.linalg.norm([cx - prev_x, cy - prev_y])
if dist < 50 and id not in matched_ids:
min_dist = dist
matched_id = id
if matched_id is None:
matched_id = next_id
next_id += 1
new_traces[matched_id] = []
else:
new_traces[matched_id] = traces[matched_id]
new_traces[matched_id].append((cx, cy))
matched_ids.add(matched_id)
traces = new_traces
for id, trace in traces.items():
if len(trace) >= 2:
for i in range(1, len(trace)):
cv2.line(frame, trace[i-1], trace[i], (255, 0, 0), 2)
features = extract_features(trace)
behavior = ai.predict_behavior(features)
if len(trace) >= 10:
if features[2] < 2:
label = "Idle"
elif features[3] > 4:
label = "Erratic"
else:
label = "Normal"
ai.learn_from(features, label)
cv2.putText(frame, f"ID:{id} AI:{behavior}", trace[-1], cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 1)
cv2.imshow("Real-Time Tracker with AI", frame)
if cv2.waitKey(1) == 27: # ESC
break
cap.release()
cv2.destroyAllWindows()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586import cv2
import numpy as np
import torch
# AI-based Visual Memory
class ObjectMemory:
def __init__(self):
self.memory = {} # object_id: feature_vector
self.next_id = 1
def extract_features(self, crop):
try:
crop_resized = cv2.resize(crop, (32, 32)) # Resize to fixed size
crop_tensor = torch.tensor(crop_resized.transpose(2, 0, 1), dtype=torch.float32).unsqueeze(0) / 255.0
return crop_tensor.view(-1) # Flatten
except:
return None
def memorize(self, crop):
vec = self.extract_features(crop)
if vec is None:
return None
obj_id = self.next_id
self.memory[obj_id] = vec
self.next_id += 1
return obj_id
def find_match(self, crop, threshold=0.95):
vec = self.extract_features(crop)
if vec is None:
return None, 0.0
best_id = None
best_sim = 0.0
for obj_id, stored_vec in self.memory.items():
sim = torch.cosine_similarity(vec, stored_vec, dim=0).item()
if sim > best_sim and sim > threshold:
best_sim = sim
best_id = obj_id
return best_id, best_sim
# Video object tracker
def main():
cap = cv2.VideoCapture(0) # Use webcam; change to "video.mp4" for a file
fgbg = cv2.createBackgroundSubtractorMOG2()
memory = ObjectMemory()
while True:
ret, frame = cap.read()
if not ret:
break
fgmask = fgbg.apply(frame)
_, thresh = cv2.threshold(fgmask, 200, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
if cv2.contourArea(cnt) < 800:
continue
x, y, w, h = cv2.boundingRect(cnt)
crop = frame[y:y+h, x:x+w]
match_id, sim = memory.find_match(crop)
if match_id is not None:
label = f"Seen before (ID {match_id})"
color = (0, 255, 0)
else:
new_id = memory.memorize(crop)
label = f"New Object (ID {new_id})"
color = (255, 0, 0)
cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
cv2.putText(frame, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX,
0.6, (255, 255, 255), 2)
cv2.imshow("Object Tracker with Memory", frame)
if cv2.waitKey(1) & 0xFF == 27: # ESC to quit
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100import cv2
import numpy as np
import torch
import torchvision.transforms as transforms
from torchvision.models import resnet18
from torch.nn.functional import cosine_similarity
# Use GPU if available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Feature extractor using pretrained ResNet18
class VisualFeatureExtractor:
def __init__(self):
model = resnet18(pretrained=True)
self.model = torch.nn.Sequential(*list(model.children())[:-1]).to(device).eval()
self.transform = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize((224, 224)),
transforms.ToTensor()
])
def extract(self, image):
try:
tensor = self.transform(image).unsqueeze(0).to(device)
with torch.no_grad():
features = self.model(tensor).squeeze()
return features / features.norm()
except:
return None
# Memory system for object identity
class ObjectMemory:
def __init__(self):
self.memory = {} # id: feature_vector
self.next_id = 1
def compare(self, feat, threshold=0.9):
best_id, best_sim = None, 0.0
for obj_id, stored_feat in self.memory.items():
sim = cosine_similarity(feat, stored_feat, dim=0).item()
if sim > best_sim and sim > threshold:
best_id, best_sim = obj_id, sim
return best_id, best_sim
def memorize(self, feat):
obj_id = self.next_id
self.memory[obj_id] = feat
self.next_id += 1
return obj_id
# Main application
def main():
cap = cv2.VideoCapture(0)
fgbg = cv2.createBackgroundSubtractorMOG2()
extractor = VisualFeatureExtractor()
memory = ObjectMemory()
while True:
ret, frame = cap.read()
if not ret:
break
fgmask = fgbg.apply(frame)
_, thresh = cv2.threshold(fgmask, 200, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
if cv2.contourArea(cnt) < 1000:
continue
x, y, w, h = cv2.boundingRect(cnt)
crop = frame[y:y+h, x:x+w]
feat = extractor.extract(crop)
if feat is None:
continue
matched_id, similarity = memory.compare(feat)
if matched_id is not None:
label = f"Known ID {matched_id} ({similarity*100:.1f}%)"
color = (0, 255, 0)
else:
new_id = memory.memorize(feat)
label = f"New Object (ID {new_id})"
color = (0, 0, 255)
cv2.rectangle(frame, (x, y), (x+w, y+h), color, 2)
cv2.putText(frame, label, (x, y-10), cv2.FONT_HERSHEY_SIMPLEX,
0.6, (255, 255, 255), 2)
cv2.imshow("AI Object Memory", frame)
if cv2.waitKey(1) & 0xFF == 27: # ESC
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899import cv2
import numpy as np
import torch
import torchvision.transforms as transforms
from torchvision.models import mobilenet_v2
from torch.nn.functional import cosine_similarity
# Use GPU if available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Lightweight feature extractor using MobileNetV2
class FastFeatureExtractor:
def __init__(self):
model = mobilenet_v2(pretrained=True).features
self.model = torch.nn.Sequential(*list(model.children())[:-1]).to(device).eval()
self.transform = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize((96, 96)),
transforms.ToTensor()
])
def extract(self, image):
try:
tensor = self.transform(image).unsqueeze(0).to(device)
with torch.no_grad():
feat = self.model(tensor).mean([2, 3]).squeeze()
return feat / feat.norm()
except:
return None
# Simple memory with similarity threshold
class ObjectMemory:
def __init__(self, threshold=0.88):
self.memory = {}
self.next_id = 1
self.threshold = threshold
def match(self, feat):
best_id, best_sim = None, 0.0
for obj_id, ref_feat in self.memory.items():
sim = cosine_similarity(feat, ref_feat, dim=0).item()
if sim > best_sim and sim > self.threshold:
best_id, best_sim = obj_id, sim
return best_id, best_sim
def add(self, feat):
obj_id = self.next_id
self.memory[obj_id] = feat
self.next_id += 1
return obj_id
# Main app
def main():
cap = cv2.VideoCapture(0)
fgbg = cv2.createBackgroundSubtractorMOG2()
extractor = FastFeatureExtractor()
memory = ObjectMemory()
while True:
ret, frame = cap.read()
if not ret:
break
fg = fgbg.apply(frame)
_, thresh = cv2.threshold(fg, 200, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
if cv2.contourArea(cnt) < 1200:
continue
x, y, w, h = cv2.boundingRect(cnt)
roi = frame[y:y+h, x:x+w]
feat = extractor.extract(roi)
if feat is None:
continue
matched_id, similarity = memory.match(feat)
if matched_id:
label = f"Known #{matched_id} ({similarity*100:.1f}%)"
color = (0, 255, 0)
else:
new_id = memory.add(feat)
label = f"New Object #{new_id}"
color = (0, 0, 255)
cv2.rectangle(frame, (x, y), (x+w, y+h), color, 2)
cv2.putText(frame, label, (x, y-8), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
cv2.imshow("Fast Object Understanding", frame)
if cv2.waitKey(1) & 0xFF == 27: # ESC to exit
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475import cv2
import numpy as np
# استفاده از الگوریتم پیشرفته KNN برای background subtraction
back_sub = cv2.createBackgroundSubtractorKNN(history=500, dist2Threshold=400, detectShadows=True)
# تابع برای محاسبه مرکز (centroid)
def get_centroid(x, y, w, h):
return (int(x + w / 2), int(y + h / 2))
# ایجاد یک فیلتر کالمن برای پیگیری حرکت شیء
kalman = cv2.KalmanFilter(4, 2)
kalman.transitionMatrix = np.array([[1, 0, 1, 0],
[0, 1, 0, 1],
[0, 0, 1, 0],
[0, 0, 0, 1]], np.float32)
kalman.measurementMatrix = np.array([[1, 0, 0, 0],
[0, 1, 0, 0]], np.float32)
kalman.processNoiseCov = np.array([[1e-2, 0, 0, 0],
[0, 1e-2, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]], np.float32)
kalman.errorCovPost = np.eye(4, dtype=np.float32)
kalman.statePost = np.zeros((4, 1), np.float32)
# گرفتن تصویر از دوربین
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
# تبدیل تصویر به خاکستری
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# دریافت ماسک اشیاء متحرک
fg_mask = back_sub.apply(frame)
# اعمال عملیات مورفولوژیکی برای حذف سایهها و نویز
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
fg_mask = cv2.morphologyEx(fg_mask, cv2.MORPH_OPEN, kernel, iterations=1)
fg_mask = cv2.dilate(fg_mask, kernel, iterations=1)
# پیدا کردن کانتورها
contours, _ = cv2.findContours(fg_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
area = cv2.contourArea(cnt)
if area > 100: # فقط اشیاء بزرگتر از این اندازه رو بررسی کن
x, y, w, h = cv2.boundingRect(cnt)
centroid = get_centroid(x, y, w, h)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.circle(frame, centroid, 4, (0, 0, 255), -1)
cv2.putText(frame, "Moving Object", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
# اندازهگیری موقعیت شیء و پیشبینی با فیلتر کالمن
kalman.correct(np.array([x + w / 2, y + h / 2], np.float32))
prediction = kalman.predict()
# استخراج مقادیر پیشبینی شده
predicted_x, predicted_y = int(prediction[0, 0]), int(prediction[1, 0])
# رسم موقعیت پیشبینی شده
cv2.circle(frame, (predicted_x, predicted_y), 4, (255, 0, 0), -1)
# نمایش تصویر پردازش شده
cv2.imshow('Real-Time Object Tracking with Kalman Filter', frame)
# خروج از برنامه با کلید ESC
if cv2.waitKey(1) & 0xFF == 27:
break
cap.release()
cv2.destroyAllWindows()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899import cv2
import numpy as np
import torch
import torchvision.transforms as transforms
from torchvision.models import mobilenet_v3_small
from torch.nn.functional import cosine_similarity
# Use GPU if available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Lightweight feature extractor using MobileNetV3
class FastFeatureExtractor:
def __init__(self):
model = mobilenet_v3_small(pretrained=True).features
self.model = torch.nn.Sequential(*list(model.children())[:-1]).to(device).eval()
self.transform = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize((96, 96)),
transforms.ToTensor()
])
def extract(self, image):
try:
tensor = self.transform(image).unsqueeze(0).to(device)
with torch.no_grad():
feat = self.model(tensor).mean([2, 3]).squeeze()
return feat / feat.norm()
except:
return None
# Simple memory with similarity threshold
class ObjectMemory:
def __init__(self, threshold=0.88):
self.memory = {}
self.next_id = 1
self.threshold = threshold
def match(self, feat):
best_id, best_sim = None, 0.0
for obj_id, ref_feat in self.memory.items():
sim = cosine_similarity(feat, ref_feat, dim=0).item()
if sim > best_sim and sim > self.threshold:
best_id, best_sim = obj_id, sim
return best_id, best_sim
def add(self, feat):
obj_id = self.next_id
self.memory[obj_id] = feat
self.next_id += 1
return obj_id
# Main app
def main():
cap = cv2.VideoCapture(0)
fgbg = cv2.createBackgroundSubtractorMOG2()
extractor = FastFeatureExtractor()
memory = ObjectMemory()
while True:
ret, frame = cap.read()
if not ret:
break
fg = fgbg.apply(frame)
_, thresh = cv2.threshold(fg, 200, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
if cv2.contourArea(cnt) < 1200:
continue
x, y, w, h = cv2.boundingRect(cnt)
roi = frame[y:y+h, x:x+w]
feat = extractor.extract(roi)
if feat is None:
continue
matched_id, similarity = memory.match(feat)
if matched_id:
label = f"Known #{matched_id} ({similarity*100:.1f}%)"
color = (0, 255, 0)
else:
new_id = memory.add(feat)
label = f"New Object #{new_id}"
color = (0, 0, 255)
cv2.rectangle(frame, (x, y), (x+w, y+h), color, 2)
cv2.putText(frame, label, (x, y-8), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
cv2.imshow("Fast Object Understanding", frame)
if cv2.waitKey(1) & 0xFF == 27: # ESC to exit
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()12345from ultralytics import YOLO
# بارگذاری مدل YOLOv8 از پیش آموزشدیده
model = YOLO("yolo11x.pt") # مدلهای مختلف: yolov8n.pt, yolov8s.pt, yolov8m.pt
12345678910111213141516171819202122232425262728293031import cv2
from ultralytics import YOLO
# بارگذاری مدل YOLOv8 از پیش آموزشدیده
model = YOLO("yolo11n.pt") # مدلهای مختلف: yolov8n.pt, yolov8s.pt, yolov8m.pt
# استفاده از دوربین برای تشخیص اشیا به صورت real-time
cap = cv2.VideoCapture(0) # 0 برای استفاده از دوربین پیشفرض سیستم
while True:
ret, frame = cap.read()
if not ret:
break
# انجام تشخیص روی هر فریم از ویدیو
results = model(frame)
# نتایج مدل در قالب لیستی از اشیا است
result = results[0] # گرفتن اولین نتیجه
# نمایش فریم با نتایج پیشبینی شده
result.show() # نمایش تصاویر با مربعات شناسایی شده
# بررسی اگر کلید "q" فشار داده شد برای بستن ویدیو
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# آزادسازی منابع
cap.release()
cv2.destroyAllWindows()1234567891011121314151617181920212223242526272829303132import cv2
from ultralytics import YOLO
# بارگذاری مدل YOLOv8 از پیش آموزشدیده
model = YOLO("yolo12l.pt") # مدلهای مختلف: yolov8n.pt, yolov8s.pt, yolov8m.pt
# استفاده از دوربین برای تشخیص اشیا به صورت real-time
cap = cv2.VideoCapture(0) # 0 برای استفاده از دوربین پیشفرض سیستم
while True:
ret, frame = cap.read()
if not ret:
break
# انجام تشخیص روی هر فریم از ویدیو
results = model(frame)
# نتایج مدل در قالب لیستی از اشیا است
result = results[0] # گرفتن اولین نتیجه
# نمایش فریم با نتایج پیشبینی شده
frame_with_boxes = result.plot() # تصویر با جعبههای شناسایی شده
cv2.imshow('Real-Time Object Detection', frame_with_boxes) # نمایش فریم با جعبهها
# بررسی اگر کلید "q" فشار داده شد برای بستن ویدیو
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# آزادسازی منابع
cap.release()
cv2.destroyAllWindows()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980import cv2
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
# استفاده از الگوریتم پیشرفته KNN برای background subtraction
back_sub = cv2.createBackgroundSubtractorKNN(history=500, dist2Threshold=400, detectShadows=True)
# تابع برای محاسبه مرکز (centroid)
def get_centroid(x, y, w, h):
return (int(x + w / 2), int(y + h / 2))
# گرفتن تصویر از دوربین
cap = cv2.VideoCapture(0)
# مدل KNN
knn = KNeighborsClassifier(n_neighbors=3)
# دادههای آموزشی و برچسبها
object_features = []
object_labels = []
# تنظیمات برای آموزش دورهای
learning_interval = 30 # هر 30 فریم یک بار آموزش انجام شود
frame_count = 0
while True:
ret, frame = cap.read()
if not ret:
break
# تبدیل تصویر به خاکستری
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# دریافت ماسک اشیاء متحرک
fg_mask = back_sub.apply(frame)
# اعمال عملیات مورفولوژیکی برای حذف سایهها و نویز
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
fg_mask = cv2.morphologyEx(fg_mask, cv2.MORPH_OPEN, kernel, iterations=1)
fg_mask = cv2.dilate(fg_mask, kernel, iterations=1)
# پیدا کردن کانتورها
contours, _ = cv2.findContours(fg_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
area = cv2.contourArea(cnt)
if area > 100: # فقط اشیاء بزرگتر از این اندازه رو بررسی کن
x, y, w, h = cv2.boundingRect(cnt)
centroid = get_centroid(x, y, w, h)
# استخراج ویژگیها
features = [w, h, centroid[0], centroid[1]]
object_features.append(features)
object_labels.append(1) # فرض میکنیم همه اشیاء متحرک به کلاس 1 تعلق دارند
# رسم باکس و مرکز
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.circle(frame, centroid, 4, (0, 0, 255), -1)
# آموزش مدل به صورت دورهای
frame_count += 1
if frame_count % learning_interval == 0 and len(object_features) > 5:
# آموزش مدل فقط زمانی که دادهها کافی باشند
knn.fit(object_features, object_labels)
print("Model updated!")
# پیشبینی با مدل KNN برای اشیاء جدید
if len(object_features) > 5 and frame_count % learning_interval == 0:
# اطمینان حاصل میکنیم که مدل آموزش داده شده است قبل از پیشبینی
predicted_label = knn.predict([features])[0]
cv2.putText(frame, f"Predicted: {predicted_label}", (x, y - 30), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
cv2.imshow('Optimized Object Tracking', frame)
# خروج از برنامه با کلید ESC
if cv2.waitKey(1) & 0xFF == 27:
break
cap.release()
cv2.destroyAllWindows()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586import cv2
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
# استفاده از الگوریتم پیشرفته KNN برای background subtraction
back_sub = cv2.createBackgroundSubtractorKNN(history=500, dist2Threshold=400, detectShadows=True)
# تابع برای محاسبه مرکز (centroid)
def get_centroid(x, y, w, h):
return (int(x + w / 2), int(y + h / 2))
# گرفتن تصویر از دوربین
cap = cv2.VideoCapture(0)
# مدل KNN
knn = KNeighborsClassifier(n_neighbors=3)
# دادههای آموزشی و برچسبها
object_features = []
object_labels = []
# تنظیمات برای آموزش دورهای
learning_interval = 30 # هر 30 فریم یک بار آموزش انجام شود
frame_count = 0
# استفاده از فیلتر برای کاهش نویز
def apply_noise_reduction(fg_mask):
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
fg_mask = cv2.morphologyEx(fg_mask, cv2.MORPH_OPEN, kernel, iterations=2) # حذف نویز بهوسیله باز کردن
fg_mask = cv2.dilate(fg_mask, kernel, iterations=1) # گسترش اشیاء برای تقویت
return fg_mask
while True:
ret, frame = cap.read()
if not ret:
break
# تبدیل تصویر به خاکستری
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# دریافت ماسک اشیاء متحرک
fg_mask = back_sub.apply(frame)
# اعمال فیلتر برای کاهش نویز
fg_mask = apply_noise_reduction(fg_mask)
# پیدا کردن کانتورها
contours, _ = cv2.findContours(fg_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
area = cv2.contourArea(cnt)
if area > 100: # فقط اشیاء بزرگتر از این اندازه رو بررسی کن
x, y, w, h = cv2.boundingRect(cnt)
centroid = get_centroid(x, y, w, h)
# استخراج ویژگیها
features = [w, h, centroid[0], centroid[1], area] # اضافه کردن مساحت به ویژگیها
object_features.append(features)
object_labels.append(1) # فرض میکنیم همه اشیاء متحرک به کلاس 1 تعلق دارند
# رسم باکس و مرکز
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.circle(frame, centroid, 4, (0, 0, 255), -1)
# آموزش مدل به صورت دورهای
frame_count += 1
if frame_count % learning_interval == 0 and len(object_features) > 5:
# آموزش مدل فقط زمانی که دادهها کافی باشند
knn.fit(object_features, object_labels)
print("Model updated!")
# پیشبینی با مدل KNN برای اشیاء جدید
if len(object_features) > 5 and frame_count % learning_interval == 0:
# اطمینان حاصل میکنیم که مدل آموزش داده شده است قبل از پیشبینی
predicted_label = knn.predict([features])[0]
cv2.putText(frame, f"Predicted: {predicted_label}", (x, y - 30), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
# نمایش تصویر
cv2.imshow('Optimized Object Tracking', frame)
# خروج از برنامه با کلید ESC
if cv2.waitKey(1) & 0xFF == 27:
break
cap.release()
cv2.destroyAllWindows()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100import cv2
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
# استفاده از الگوریتم پیشرفته KNN برای background subtraction
back_sub = cv2.createBackgroundSubtractorKNN(history=500, dist2Threshold=400, detectShadows=True)
# تابع برای محاسبه مرکز (centroid)
def get_centroid(x, y, w, h):
return (int(x + w / 2), int(y + h / 2))
# تابع برای کاهش نویز
def apply_noise_reduction(fg_mask):
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
fg_mask = cv2.morphologyEx(fg_mask, cv2.MORPH_OPEN, kernel, iterations=2)
fg_mask = cv2.dilate(fg_mask, kernel, iterations=1)
return fg_mask
# تابع برای تشخیص جهت حرکت
def detect_direction(prev, curr):
dx = curr[0] - prev[0]
dy = curr[1] - prev[1]
if abs(dx) > abs(dy):
return "Right" if dx > 0 else "Left"
else:
return "Down" if dy > 0 else "Up"
# گرفتن تصویر از دوربین
cap = cv2.VideoCapture(0)
# مدل KNN
knn = KNeighborsClassifier(n_neighbors=3)
# دادههای آموزشی و برچسبها
object_features = []
object_labels = []
# تنظیمات آموزش دورهای
learning_interval = 30
frame_count = 0
# نگهداری آخرین موقعیت centroid برای دنبال کردن مسیر
prev_centroids = []
while True:
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
fg_mask = back_sub.apply(frame)
fg_mask = apply_noise_reduction(fg_mask)
contours, _ = cv2.findContours(fg_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
current_centroids = []
for cnt in contours:
area = cv2.contourArea(cnt)
if area > 100:
x, y, w, h = cv2.boundingRect(cnt)
centroid = get_centroid(x, y, w, h)
current_centroids.append(centroid)
# استخراج ویژگیها
features = [w, h, centroid[0], centroid[1], area]
object_features.append(features)
object_labels.append(1)
# رسم باکس و مرکز
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.circle(frame, centroid, 4, (0, 0, 255), -1)
# اگر centroid قبلی موجود است، جهت را تشخیص بده
if len(prev_centroids) > 0:
closest_prev = min(prev_centroids, key=lambda p: np.linalg.norm(np.array(p) - np.array(centroid)))
direction = detect_direction(closest_prev, centroid)
cv2.putText(frame, f"Dir: {direction}", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 0), 2)
# بهروزرسانی centroid های قبلی
prev_centroids = current_centroids.copy()
# آموزش دورهای مدل
frame_count += 1
if frame_count % learning_interval == 0 and len(object_features) > 5:
knn.fit(object_features, object_labels)
print("Model updated!")
if len(object_features) > 5 and frame_count % learning_interval == 0:
predicted_label = knn.predict([features])[0]
cv2.putText(frame, f"Predicted: {predicted_label}", (x, y - 30), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
# نمایش تصویر
cv2.imshow('Object Tracking with Direction', frame)
# خروج با کلید ESC
if cv2.waitKey(1) & 0xFF == 27:
break
cap.release()
cv2.destroyAllWindows()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138import cv2
import numpy as np
import time
from sklearn.neighbors import KNeighborsClassifier
from collections import defaultdict, deque
back_sub = cv2.createBackgroundSubtractorKNN(history=500, dist2Threshold=400, detectShadows=True)
cap = cv2.VideoCapture(0)
# ذخیره مسیر اشیاء
object_traces = defaultdict(lambda: deque(maxlen=30)) # آخرین ۳۰ نقطه هر شیء
object_last_seen = {}
object_id_counter = 0
# برای یادگیری real-time
knn = KNeighborsClassifier(n_neighbors=3)
features_set = []
labels_set = []
frame_count = 0
learning_interval = 30
def apply_noise_reduction(mask):
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=2)
mask = cv2.dilate(mask, kernel, iterations=1)
return mask
def get_centroid(x, y, w, h):
return (int(x + w / 2), int(y + h / 2))
def calculate_direction(trace):
if len(trace) < 2:
return "-"
dx = trace[-1][0] - trace[0][0]
dy = trace[-1][1] - trace[0][1]
if abs(dx) > abs(dy):
return "چپ" if dx < 0 else "راست"
else:
return "بالا" if dy < 0 else "پایین"
def calculate_speed(trace, duration):
if len(trace) < 2 or duration == 0:
return 0
dist = np.linalg.norm(np.array(trace[-1]) - np.array(trace[0]))
return dist / duration
def count_direction_changes(trace):
changes = 0
for i in range(2, len(trace)):
dx1 = trace[i-1][0] - trace[i-2][0]
dx2 = trace[i][0] - trace[i-1][0]
if dx1 * dx2 < 0: # تغییر جهت افقی
changes += 1
return changes
while True:
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
fg_mask = back_sub.apply(frame)
fg_mask = apply_noise_reduction(fg_mask)
contours, _ = cv2.findContours(fg_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
current_ids = []
for cnt in contours:
area = cv2.contourArea(cnt)
if area < 150:
continue
x, y, w, h = cv2.boundingRect(cnt)
centroid = get_centroid(x, y, w, h)
# شناسایی یا ایجاد شناسه جدید
matched_id = None
for oid, trace in object_traces.items():
if np.linalg.norm(np.array(trace[-1]) - np.array(centroid)) < 50:
matched_id = oid
break
if matched_id is None:
matched_id = object_id_counter
object_id_counter += 1
object_traces[matched_id].append(centroid)
object_last_seen[matched_id] = time.time()
current_ids.append(matched_id)
trace = object_traces[matched_id]
duration = time.time() - object_last_seen[matched_id] + 0.001
speed = calculate_speed(trace, duration)
direction = calculate_direction(trace)
direction_changes = count_direction_changes(trace)
total_move = sum(np.linalg.norm(np.array(trace[i]) - np.array(trace[i-1])) for i in range(1, len(trace)))
# ویژگی برای مدل
feature = [w, h, centroid[0], centroid[1], area, speed, direction_changes]
label = 1 # کلاس پیشفرض: عادی
# برچسبگذاری خودکار ساده:
if speed > 100 or direction_changes > 4:
label = 2 # مشکوک
features_set.append(feature)
labels_set.append(label)
if len(features_set) > 10 and frame_count % learning_interval == 0:
knn.fit(features_set, labels_set)
print("مدل بهروزرسانی شد.")
predicted = "-"
if len(features_set) > 10:
predicted = knn.predict([feature])[0]
# رسم اطلاعات روی فریم
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0) if label == 1 else (0, 0, 255), 2)
cv2.circle(frame, centroid, 4, (255, 255, 255), -1)
cv2.putText(frame, f"ID: {matched_id} | جهت: {direction} | سرعت: {int(speed)}", (x, y - 25),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 0), 1)
cv2.putText(frame, f"رفتار: {'عادی' if predicted == 1 else 'مشکوک'}", (x, y - 5),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 1)
frame_count += 1
# حذف آیدیهای قدیمی
for oid in list(object_last_seen):
if time.time() - object_last_seen[oid] > 2:
object_traces.pop(oid, None)
object_last_seen.pop(oid, None)
cv2.imshow("هوش رفتاری", frame)
if cv2.waitKey(1) & 0xFF == 27:
break
cap.release()
cv2.destroyAllWindows()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140import cv2
import numpy as np
import time
from sklearn.neighbors import KNeighborsClassifier
from collections import defaultdict, deque
back_sub = cv2.createBackgroundSubtractorKNN(history=500, dist2Threshold=400, detectShadows=True)
cap = cv2.VideoCapture(0)
# ذخیره مسیر اشیاء
object_traces = defaultdict(lambda: deque(maxlen=30)) # آخرین ۳۰ نقطه هر شیء
object_last_seen = {}
object_id_counter = 0
# برای یادگیری real-time
knn = KNeighborsClassifier(n_neighbors=3)
features_set = []
labels_set = []
frame_count = 0
learning_interval = 30
def apply_noise_reduction(mask):
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=2)
mask = cv2.dilate(mask, kernel, iterations=1)
return mask
def get_centroid(x, y, w, h):
return (int(x + w / 2), int(y + h / 2))
def calculate_direction(trace):
if len(trace) < 2:
return "-"
dx = trace[-1][0] - trace[0][0]
dy = trace[-1][1] - trace[0][1]
if abs(dx) > abs(dy):
return "چپ" if dx < 0 else "راست"
else:
return "بالا" if dy < 0 else "پایین"
def calculate_speed(trace, duration):
if len(trace) < 2 or duration == 0:
return 0
dist = np.linalg.norm(np.array(trace[-1]) - np.array(trace[0]))
return dist / duration
def count_direction_changes(trace):
changes = 0
for i in range(2, len(trace)):
dx1 = trace[i-1][0] - trace[i-2][0]
dx2 = trace[i][0] - trace[i-1][0]
if dx1 * dx2 < 0: # تغییر جهت افقی
changes += 1
return changes
while True:
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
fg_mask = back_sub.apply(frame)
fg_mask = apply_noise_reduction(fg_mask)
contours, _ = cv2.findContours(fg_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
current_ids = []
predicted = 1 # مقدار پیشفرض برای پیشبینی (در صورتی که پیشبینی انجام نشود)
for cnt in contours:
area = cv2.contourArea(cnt)
if area < 150:
continue
x, y, w, h = cv2.boundingRect(cnt)
centroid = get_centroid(x, y, w, h)
# شناسایی یا ایجاد شناسه جدید
matched_id = None
for oid, trace in object_traces.items():
if np.linalg.norm(np.array(trace[-1]) - np.array(centroid)) < 50:
matched_id = oid
break
if matched_id is None:
matched_id = object_id_counter
object_id_counter += 1
object_traces[matched_id].append(centroid)
object_last_seen[matched_id] = time.time()
current_ids.append(matched_id)
trace = object_traces[matched_id]
duration = time.time() - object_last_seen[matched_id] + 0.001
speed = calculate_speed(trace, duration)
direction = calculate_direction(trace)
direction_changes = count_direction_changes(trace)
total_move = sum(np.linalg.norm(np.array(trace[i]) - np.array(trace[i-1])) for i in range(1, len(trace)))
# ویژگی برای مدل
feature = [w, h, centroid[0], centroid[1], area, speed, direction_changes]
label = 1 # کلاس پیشفرض: عادی
# برچسبگذاری خودکار ساده:
if speed > 100 or direction_changes > 4:
label = 2 # مشکوک
features_set.append(feature)
labels_set.append(label)
# آموزش مدل فقط زمانی که دادههای کافی وجود داشته باشد
if len(features_set) > 10 and frame_count % learning_interval == 0:
knn.fit(features_set, labels_set)
print("مدل بهروزرسانی شد.")
# فقط پیشبینی بعد از آموزش
if len(features_set) > 10:
predicted = knn.predict([feature])[0]
# رسم اطلاعات روی فریم
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0) if label == 1 else (0, 0, 255), 2)
cv2.circle(frame, centroid, 4, (255, 255, 255), -1)
cv2.putText(frame, f"ID: {matched_id} | جهت: {direction} | سرعت: {int(speed)}", (x, y - 25),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 0), 1)
cv2.putText(frame, f"رفتار: {'عادی' if predicted == 1 else 'مشکوک'}", (x, y - 5),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 1)
frame_count += 1
# حذف آیدیهای قدیمی
for oid in list(object_last_seen):
if time.time() - object_last_seen[oid] > 2:
object_traces.pop(oid, None)
object_last_seen.pop(oid, None)
cv2.imshow("هوش رفتاری", frame)
if cv2.waitKey(1) & 0xFF == 27:
break
cap.release()
cv2.destroyAllWindows()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153import cv2
import numpy as np
import time
from sklearn.neighbors import KNeighborsClassifier
from collections import defaultdict, deque
# ایجاد پسزمینه برای شناسایی حرکت
back_sub = cv2.createBackgroundSubtractorKNN(history=500, dist2Threshold=400, detectShadows=True)
cap = cv2.VideoCapture(0)
# ذخیره مسیر اشیاء
object_traces = defaultdict(lambda: deque(maxlen=30)) # آخرین ۳۰ نقطه هر شیء
object_last_seen = {}
object_id_counter = 0
# برای یادگیری real-time
knn = KNeighborsClassifier(n_neighbors=3)
features_set = []
labels_set = []
frame_count = 0
learning_interval = 30
# زمان شروع برای جمعآوری دادهها
start_time = time.time()
learning_time_limit = 60 # 1 دقیقه برای جمعآوری دادهها
# متغیر برای جلوگیری از پیشبینی قبل از آموزش
is_trained = False
def apply_noise_reduction(mask):
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=2)
mask = cv2.dilate(mask, kernel, iterations=1)
return mask
def get_centroid(x, y, w, h):
return (int(x + w / 2), int(y + h / 2))
def calculate_direction(trace):
if len(trace) < 2:
return "-"
dx = trace[-1][0] - trace[0][0]
dy = trace[-1][1] - trace[0][1]
if abs(dx) > abs(dy):
return "چپ" if dx < 0 else "راست"
else:
return "بالا" if dy < 0 else "پایین"
def calculate_speed(trace, duration):
if len(trace) < 2 or duration == 0:
return 0
dist = np.linalg.norm(np.array(trace[-1]) - np.array(trace[0]))
return dist / duration
def count_direction_changes(trace):
changes = 0
for i in range(2, len(trace)):
dx1 = trace[i-1][0] - trace[i-2][0]
dx2 = trace[i][0] - trace[i-1][0]
if dx1 * dx2 < 0: # تغییر جهت افقی
changes += 1
return changes
while True:
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
fg_mask = back_sub.apply(frame)
fg_mask = apply_noise_reduction(fg_mask)
contours, _ = cv2.findContours(fg_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
current_ids = []
predicted = 1 # مقدار پیشفرض برای پیشبینی (در صورتی که پیشبینی انجام نشود)
for cnt in contours:
area = cv2.contourArea(cnt)
if area < 150:
continue
x, y, w, h = cv2.boundingRect(cnt)
centroid = get_centroid(x, y, w, h)
# شناسایی یا ایجاد شناسه جدید
matched_id = None
for oid, trace in object_traces.items():
if np.linalg.norm(np.array(trace[-1]) - np.array(centroid)) < 50:
matched_id = oid
break
if matched_id is None:
matched_id = object_id_counter
object_id_counter += 1
object_traces[matched_id].append(centroid)
object_last_seen[matched_id] = time.time()
current_ids.append(matched_id)
trace = object_traces[matched_id]
duration = time.time() - object_last_seen[matched_id] + 0.001
speed = calculate_speed(trace, duration)
direction = calculate_direction(trace)
direction_changes = count_direction_changes(trace)
total_move = sum(np.linalg.norm(np.array(trace[i]) - np.array(trace[i-1])) for i in range(1, len(trace)))
# ویژگی برای مدل
feature = [w, h, centroid[0], centroid[1], area, speed, direction_changes]
label = 1 # کلاس پیشفرض: عادی
# برچسبگذاری خودکار ساده:
if speed > 100 or direction_changes > 4:
label = 2 # مشکوک
features_set.append(feature)
labels_set.append(label)
# آموزش مدل فقط زمانی که دادههای کافی جمعآوری شده باشد
if time.time() - start_time < learning_time_limit:
# هنوز در مرحله جمعآوری دادهها هستیم
continue
elif not is_trained: # اگر هنوز مدل آموزش داده نشده است
if len(features_set) > 10:
knn.fit(features_set, labels_set) # آموزش مدل
is_trained = True # مدل آموزش داده شد
print("مدل بهروزرسانی شد.")
# پیشبینی فقط پس از آموزش
if is_trained:
predicted = knn.predict([feature])[0]
# رسم اطلاعات روی فریم
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0) if label == 1 else (0, 0, 255), 2)
cv2.circle(frame, centroid, 4, (255, 255, 255), -1)
cv2.putText(frame, f"ID: {matched_id} | جهت: {direction} | سرعت: {int(speed)}", (x, y - 25),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 0), 1)
cv2.putText(frame, f"رفتار: {'عادی' if predicted == 1 else 'مشکوک'}", (x, y - 5),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 1)
frame_count += 1
# حذف آیدیهای قدیمی
for oid in list(object_last_seen):
if time.time() - object_last_seen[oid] > 2:
object_traces.pop(oid, None)
object_last_seen.pop(oid, None)
cv2.imshow("هوش رفتاری", frame)
if cv2.waitKey(1) & 0xFF == 27:
break
cap.release()
cv2.destroyAllWindows()opencv_test/Untitled.ipynbAdded+261
opencv_test/Untitled1.ipynbAdded+174
opencv_test/Untitled2.ipynbAdded+78
opencv_test/Untitled3.ipynbAdded+141
opencv_test/Untitled4.ipynbAdded+194
opencv_test/Untitled5.ipynbAdded+126
opencv_test/Untitled6.ipynbAdded+297
opencv_test/Untitled7.ipynbAdded
opencv_test/object_memory.ptAdded+3
opencv_test/untitled.pyAdded
opencv_test/untitled1.pyAdded+69
opencv_test/untitled10.pyAdded+153
opencv_test/untitled11.pyAdded+147
opencv_test/untitled12.pyAdded+157
opencv_test/untitled13.pyAdded+172
opencv_test/untitled14.pyAdded+114
opencv_test/untitled15.pyAdded+147
opencv_test/untitled16.pyAdded+86
opencv_test/untitled17.pyAdded+100
opencv_test/untitled18.pyAdded+99
opencv_test/untitled2.pyAdded+75
opencv_test/untitled21.pyAdded+99
opencv_test/untitled22.pyAdded+5
opencv_test/untitled23.pyAdded+31
opencv_test/untitled24.pyAdded+32
opencv_test/untitled3.pyAdded+80
opencv_test/untitled5.pyAdded+86
opencv_test/untitled6.pyAdded+100
opencv_test/untitled7.pyAdded+138
opencv_test/untitled8.pyAdded+140
opencv_test/untitled9.pyAdded+153