<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mert on Medium]]></title>
        <description><![CDATA[Stories by Mert on Medium]]></description>
        <link>https://medium.com/@Mert.A?source=rss-323545448d05------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FbFFny8Ni8gsIqH49y08uA.jpeg</url>
            <title>Stories by Mert on Medium</title>
            <link>https://medium.com/@Mert.A?source=rss-323545448d05------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 17:38:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Mert.A/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to use YOLOv26 for Object Detection]]></title>
            <link>https://medium.com/@Mert.A/how-to-use-yolov26-for-object-detection-2712ea268838?source=rss-323545448d05------2</link>
            <guid isPermaLink="false">https://medium.com/p/2712ea268838</guid>
            <category><![CDATA[ultralytics]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[yolo26]]></category>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Mert]]></dc:creator>
            <pubDate>Mon, 26 Jan 2026 13:11:37 GMT</pubDate>
            <atom:updated>2026-01-26T13:11:37.529Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yteNDbKSxugwt8zL2SKuQA.png" /></figure><h3>Introduction</h3><p>The YOLO (You Only Look Once) family has consistently set the standard for real-time object detection, balancing speed, accuracy, and practical deployment. With each generation, YOLO has evolved not just in raw performance, but in how efficiently it can be trained, exported, and run across diverse hardware — from GPUs to edge and mobile devices.</p><p><strong>YOLO26</strong> represents the latest and most deployment-focused step in this evolution. Rather than adding complexity for marginal gains, YOLO26 revisits the detection pipeline itself, simplifying key components while still improving accuracy, stability, and inference speed. The result is a model that feels less like a research prototype and more like a production-ready vision system.</p><p>Some of the most notable advances in YOLO26 include:</p><ul><li><strong>End-to-end, NMS-free inference</strong>, eliminating post-processing bottlenecks and reducing latency variability.</li><li><strong>Removal of Distribution Focal Loss (DFL)</strong>, leading to a lighter, more hardware-friendly regression pipeline.</li><li><strong>Improved training stability and small-object performance</strong> through Progressive Loss Balancing (ProgLoss) and Small-Target-Aware Label Assignment (STAL).</li><li><strong>A new MuSGD optimizer</strong>, designed to converge faster and more reliably across model scales.</li><li><strong>Unified multi-task support</strong>, covering object detection, instance segmentation, pose/keypoint estimation, oriented bounding boxes, and classification within a single framework.</li></ul><p>If you’ve been following the YOLO journey, this direction may feel familiar. In previous posts, I’ve explored earlier milestones in the series — covering <a href="https://medium.com/@Mert.A/how-to-use-yolov8-and-yolo-nas-for-object-detection-8c5893939480"><strong>YOLOv8</strong></a>, <a href="https://medium.com/@Mert.A/how-to-use-yolov9-for-object-detection-93598ad88d7d"><strong>YOLOv9</strong></a>, <a href="https://medium.com/@Mert.A/how-to-use-yolov11-for-object-detection-924aa18ac86f"><strong>YOLO11</strong></a>, and <a href="https://medium.com/@Mert.A/how-to-use-yolov12-for-object-detection-a93b3c2592a3"><strong>YOLO12</strong> </a>— each of which pushed the architecture forward in its own way. YOLO26 builds on those ideas, but with a stronger emphasis on simplicity, exportability, and real-world deployment, especially for edge and low-power environments.</p><h3>From theory to practice</h3><p>Architecture and benchmarks are important — but what really matters is how easily you can use the model in your own projects. In the next section, we’ll move from concepts to code and walk through <strong>how to use YOLO26 in practice</strong>, from loading a pretrained model to running inference and integrating it into a real application.</p><h3>How to use YOLO26</h3><h4>Step 1: Installing the necessary libraries</h4><pre>pip install opencv-python ultralytics</pre><h4>Step 2: Importing libraries</h4><pre>import cv2<br>from ultralytics import YOLO</pre><h4>Step 3: Choose your model</h4><pre>model = YOLO(&quot;yolo26n.pt&quot;)</pre><p>On this <a href="https://docs.ultralytics.com/de/models/yolo26/#supported-tasks-and-modes">website</a>, you can compare different models and weigh up their respective advantages and disadvantages. In this case we have chosen yolo26n.pt.</p><h4>Step 4: Write a function to predict and detect objects in images</h4><pre>def predict(chosen_model, img, classes=[], conf=0.5):<br>    if classes:<br>        results = chosen_model.predict(img, classes=classes, conf=conf)<br>    else:<br>        results = chosen_model.predict(img, conf=conf)<br>return results<br>def predict_and_detect(chosen_model, img, classes=[], conf=0.5, rectangle_thickness=2, text_thickness=1):<br>    results = predict(chosen_model, img, classes, conf=conf)<br>    for result in results:<br>        for box in result.boxes:<br>            cv2.rectangle(img, (int(box.xyxy[0][0]), int(box.xyxy[0][1])),<br>                          (int(box.xyxy[0][2]), int(box.xyxy[0][3])), (255, 0, 0), rectangle_thickness)<br>            cv2.putText(img, f&quot;{result.names[int(box.cls[0])]}&quot;,<br>                        (int(box.xyxy[0][0]), int(box.xyxy[0][1]) - 10),<br>                        cv2.FONT_HERSHEY_PLAIN, 1, (255, 0, 0), text_thickness)<br>    return img, results</pre><p>An explanation of the two functions can be found <a href="https://medium.com/@Mert.A/how-to-use-yolov10-for-object-detection-de9f47898db2">here</a>.</p><h4>Step 5: Detecting Objects in Images with YOLO26</h4><pre># read the image<br>image = cv2.imread(&quot;YourImagePath&quot;)<br>result_img, _ = predict_and_detect(model, image, classes=[], conf=0.5)</pre><p>If you want to detect specific classes, which you can find <a href="https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/datasets/coco.yaml">here</a>, simply write the ID number of the object in the list of classes.</p><h4>Step 6: Save and Plot the result Image</h4><pre>cv2.imshow(&quot;Image&quot;, result_img)<br>cv2.imwrite(&quot;YourSavePath&quot;, result_img)<br>cv2.waitKey(0)</pre><h4>The whole code:</h4><pre>from ultralytics import YOLO<br>import cv2<br><br>def predict(chosen_model, img, classes=[], conf=0.5):<br>    if classes:<br>        results = chosen_model.predict(img, classes=classes, conf=conf)<br>    else:<br>        results = chosen_model.predict(img, conf=conf)<br>    return results<br><br>def predict_and_detect(chosen_model, img, classes=[], conf=0.5, rectangle_thickness=2, text_thickness=1):<br>    results = predict(chosen_model, img, classes, conf=conf)<br>    for result in results:<br>        for box in result.boxes:<br>            cv2.rectangle(img, (int(box.xyxy[0][0]), int(box.xyxy[0][1])),<br>                          (int(box.xyxy[0][2]), int(box.xyxy[0][3])), (255, 0, 0), rectangle_thickness)<br>            cv2.putText(img, f&quot;{result.names[int(box.cls[0])]}&quot;,<br>                        (int(box.xyxy[0][0]), int(box.xyxy[0][1]) - 10),<br>                        cv2.FONT_HERSHEY_PLAIN, 1, (255, 0, 0), text_thickness)<br>    return img, results<br>model = YOLO(&quot;yolo26n.pt&quot;)<br># read the image<br>image = cv2.imread(&quot;YourImagePath.png&quot;)<br>result_img, _ = predict_and_detect(model, image, classes=[], conf=0.5)<br>cv2.imshow(&quot;Image&quot;, result_img)<br>cv2.imwrite(&quot;YourSavePath.png&quot;, result_img)<br>cv2.waitKey(0)</pre><h3>Conclusion</h3><p>In this tutorial we have learned how to detect objects with YOLO26 in images and videos. If you found this code helpful, please clap your hands and comment on this post! I would also love for you to follow me to learn more about Data Science and other related topics. Thanks for reading!</p><h3>References</h3><p><strong>Paper:</strong> <a href="https://arxiv.org/pdf/2509.25164">YOLO26: Key Architectural Enhancements and Performance Benchmarking for Real-Time Object Detection</a></p><p><strong>Repo:</strong> <a href="https://docs.ultralytics.com/de/models/yolo26/#overview">Ultralytics YOLO26 — Ultralytics YOLO-Dokumentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2712ea268838" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bildklassen-Finder mit YOLO und Streamlit]]></title>
            <link>https://medium.com/@Mert.A/bildklassen-finder-mit-yolo-und-streamlit-7cd0b18c3e8a?source=rss-323545448d05------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cd0b18c3e8a</guid>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[ultralytics]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[portfolio]]></category>
            <dc:creator><![CDATA[Mert]]></dc:creator>
            <pubDate>Sat, 28 Jun 2025 15:01:55 GMT</pubDate>
            <atom:updated>2025-06-28T15:01:55.784Z</atom:updated>
            <content:encoded><![CDATA[<p>Für dieses Projekt habe ich eine interaktive Webanwendung entwickelt, mit der Benutzer Bilder hochladen, Objektkategorien auswählen und Bilder basierend auf den ausgewählten Objekten automatisch erkennen und filtern können. Die App wurde mit YOLO für die Objekterkennung und Streamlit für die Weboberfläche erstellt und demonstriert Echtzeit-Filterung auf Basis künstlicher Intelligenz in einer übersichtlichen und einfachen Benutzeroberfläche.</p><p>Hier können Sie es selbst ausprobieren: <a href="https://searchimagesyolo.streamlit.app/">Streamlit</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ADjKVeMasgoIv8LsZvFpHg.png" /></figure><h3>Einleitung</h3><p>In diesem Projekt habe ich eine intelligente Bildfilteranwendung entwickelt, die die <strong>YOLO-Objekterkennung</strong> mit einer <strong>Streamlit-basierten</strong> Benutzeroberfläche kombiniert. Die App ermöglicht es Benutzern:</p><ul><li>Laden Sie ein oder mehrere Bilder hoch.</li><li>Wählen Sie Objektkategorien (z. B. „Hund“, „Auto“, „Pizza“) aus dem COCO-Datensatz aus.</li><li>Erkennen Sie diese Objekte in Echtzeit.</li><li>Nur die Bilder anzeigen und isolieren, die die ausgewählten Objekte enthalten.</li></ul><p>Dieser Beitrag gibt einen Überblick über die Struktur des Projekts, seine wichtigsten Komponenten und die zugrunde liegende Logik dieses Echtzeit-Filtertools. Er dient auch als technisches Vorzeigeprojekt, das meine Fähigkeit demonstriert, Deep Learning mit produktionsreifen Frontend-Erfahrungen zu kombinieren.</p><h3>Kernlogik und Funktionen</h3><h3>🔁 Modell-Caching</h3><p>Um zu vermeiden, dass das große YOLO-Modell bei jeder Erkennung neu geladen werden muss, habe ich Streamlit’s @st.cache_resource decorator benutzt:</p><pre>@st.cache_resource<br>def load_yolo_model():<br>    return YOLO(&quot;yolo11m.pt&quot;)  # Replace with your model path</pre><p>Dies verbessert die Leistung erheblich, insbesondere bei mehreren Interaktionen in derselben Sitzung.</p><h3>🎯 Erkennungsfunktion</h3><p>Die detect_with_yolo Funktion führt eine Inferenz unter Verwendung des YOLO-Modells durch, ordnet vom Benutzer ausgewählte Klassennamen internen Klassen-IDs zu und filtert die Vorhersagen entsprechend:</p><pre>def detect_with_yolo(image, selected_classes, conf: float = 0.25):<br>    model = load_yolo_model()<br>    all_class_names = model.names<br>    name_to_index = {v: k for k, v in all_class_names.items()}<br>    target_labels = [name_to_index[name] for name in selected_classes if name in name_to_index]<br>    results = model.predict(image, classes=target_labels, conf=conf)<br>    return results[0] if results else None</pre><p>Diese Funktion stellt sicher, dass wir nur nach den Objekten suchen, die für den Benutzer tatsächlich von Interesse sind.</p><h3>🖼️ Benutzeroberfläche mit Streamlit</h3><p>Die Benutzeroberfläche umfasst:</p><ul><li>Eine <strong>Seitenleiste </strong>mit Klassenauswahl und Schieberegler für die Konfidenzschwelle</li><li>Ein <strong>Datei-Uploader</strong> für Bilddateien</li><li>Eine <strong>Schaltfläche zur Erkennung von Bewegungen</strong>, um die Objekterkennung auszulösen</li><li>Ein <strong>Ergebnisfenster</strong>, das nur Bilder mit übereinstimmenden Objekten anzeigt.</li></ul><pre>if result and result.boxes and len(result.boxes.cls) &gt; 0:<br>    matched_images.append((file.name, image))</pre><p>Der Fortschritt wird in Echtzeit verfolgt, sodass Benutzer während der Verarbeitung ihrer Bilder Feedback erhalten.</p><h3>▶️ Ausführen der Anwendung</h3><p>Um die Anwendung lokal auszuführen:</p><p>Das Repository klonen</p><pre>git clone https://github.com/MertAkguel/SearchImages.git</pre><p>Abhängigkeiten installieren</p><pre>pip install -r requirements.txt</pre><p>Die App ausführen</p><pre>streamlit run app.py</pre><p>Die App wird in Ihrem Browser gestartet und ist sofort einsatzbereit.</p><h3>📌 Funktionen auf einen Blick</h3><p>✅ Mehrere Bilder hochladen<br> ✅Wählen Sie aus über 80 COCO-Objektklassen<br> ✅ Schwellenwert für die Erkennungssicherheit festlegen<br> ✅ Filtern und anzeigen Sie nur Bilder mit den gewünschten Objekten.<br> ✅ Reaktionsschnelles Feedback zu Fortschritten und ErfolgenFazit</p><h3>Fazit</h3><p>Dieses Projekt zeigt, wie leistungsstarke Computer-Vision-Tools wie YOLO mithilfe von Streamlit in benutzerfreundliche Anwendungen integriert werden können. Es ist ein übersichtliches, praxisnahes Beispiel für:</p><ul><li>Modellbereitstellung mit effizientem Caching</li><li>Benutzerorientierte Filterung auf Basis von KI-Prognosen</li><li>Ein modernes, interaktives Frontend ohne traditionellen Webcode zu schreiben</li></ul><p>Ob Sie KI-gestützte Content-Tools entwickeln, Pipelines filtern oder einfach nur maschinelles Lernen präsentieren — dieses Projekt zeigt, wie Sie fortschrittliche KI mit echter Benutzerfreundlichkeit verbinden können.</p><p><strong>Full Source Code</strong>: <a href="https://github.com/MertAkguel/SearchImages">https://github.com/MertAkguel/SearchImages</a><br><strong>Probieren Sie es selbst aus: </strong><a href="https://searchimagesyolo.streamlit.app/">Streamlit</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cd0b18c3e8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Class Finder Using YOLO and Streamlit]]></title>
            <link>https://medium.com/@Mert.A/image-class-finder-using-yolo-and-streamlit-69aa405ef913?source=rss-323545448d05------2</link>
            <guid isPermaLink="false">https://medium.com/p/69aa405ef913</guid>
            <category><![CDATA[portfolio]]></category>
            <category><![CDATA[ultralytics]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[streamlit]]></category>
            <dc:creator><![CDATA[Mert]]></dc:creator>
            <pubDate>Sun, 22 Jun 2025 14:01:43 GMT</pubDate>
            <atom:updated>2025-06-28T14:25:20.527Z</atom:updated>
            <content:encoded><![CDATA[<p>For this project, I developed an interactive web application that enables users to upload images, select object categories and automatically detect and filter images based on the chosen objects. Built using YOLO for object detection and Streamlit for the web interface, the app demonstrates real-time, AI-powered filtering within a clean and simple UI.</p><p>Here you can try it yourself: <a href="https://searchimagesyolo.streamlit.app/">Streamlit</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ADjKVeMasgoIv8LsZvFpHg.png" /></figure><h3>Introduction</h3><p>In this project, I developed an intelligent image filtering application that combines <strong>YOLO object detection</strong> with a <strong>Streamlit-powered interface</strong>. The app allows users to:</p><ul><li>Upload one or more images</li><li>Select object categories (e.g., “dog”, “car”, “pizza”) from the COCO dataset</li><li>Detect those objects in real-time</li><li>View and isolate only the images that contain the selected objects</li></ul><p>This post walks through the project’s structure, key components, and the underlying logic powering this real-time filtering tool. It also serves as a technical showcase demonstrating my ability to combine deep learning with production-ready front-end experiences.</p><h3>Core Logic and Features</h3><h3>🔁 Model Caching</h3><p>To avoid reloading the large YOLO model every time a detection is run, I used Streamlit’s @st.cache_resource decorator:</p><pre>@st.cache_resource<br>def load_yolo_model():<br>    return YOLO(&quot;yolo11m.pt&quot;)  # Replace with your model path</pre><p>This improves performance significantly, especially during multiple interactions in the same session.</p><h3>🎯 Detection Function</h3><p>The detect_with_yolo function performs inference using the YOLO model, mapping user-selected class names to internal class IDs and filtering predictions accordingly:</p><pre>def detect_with_yolo(image, selected_classes, conf: float = 0.25):<br>    model = load_yolo_model()<br>    all_class_names = model.names<br>    name_to_index = {v: k for k, v in all_class_names.items()}<br>    target_labels = [name_to_index[name] for name in selected_classes if name in name_to_index]<br><br>    results = model.predict(image, classes=target_labels, conf=conf)<br>    return results[0] if results else None</pre><p>This function ensures we only look for the objects the user actually cares about.</p><h3>🖼️ User Interface with Streamlit</h3><p>The UI includes:</p><ul><li>A <strong>sidebar</strong> with class selection and confidence threshold slider</li><li>A <strong>file uploader</strong> for image inputs</li><li>A <strong>Run Detection</strong> button to trigger object detection</li><li>A <strong>results panel</strong> that only shows images with matched objects</li></ul><pre>if result and result.boxes and len(result.boxes.cls) &gt; 0:<br>    matched_images.append((file.name, image))</pre><p>Progress is tracked in real-time, giving users feedback as their images are processed.</p><h3>▶️ Running the Application</h3><p>To run the application locally:</p><p><strong>Clone the repository</strong></p><pre>git clone https://github.com/MertAkguel/SearchImages.git</pre><p><strong>Install dependencies</strong></p><pre>pip install -r requirements.txt</pre><p><strong>Run the app</strong></p><pre>streamlit run app.py</pre><p>The app will launch in your browser, ready for use.</p><h3>📌 Features at a Glance</h3><p>✅ Upload multiple images<br> ✅ Select from 80+ COCO object classes<br> ✅ Set detection confidence threshold<br> ✅ Filter and view only images with desired objects<br> ✅ Responsive progress and success feedbackConclusion</p><h3>Conclusion</h3><p>This project demonstrates how powerful computer vision tools like <strong>YOLO</strong> can be packaged into user-friendly applications using <strong>Streamlit</strong>. It’s a clean, real-world example of:</p><ul><li>Model deployment with efficient caching</li><li>User-centric filtering based on AI predictions</li><li>A modern, interactive frontend without writing traditional web code</li></ul><p>Whether you’re building AI-powered content tools, filtering pipelines, or just showcasing machine learning, this project shows how to bridge advanced AI with real usability.</p><p><strong>Full Source Code</strong>: <a href="https://github.com/MertAkguel/SearchImages">https://github.com/MertAkguel/SearchImages</a><br><strong>Try it yourself: </strong><a href="https://searchimagesyolo.streamlit.app/">Streamlit</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69aa405ef913" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Echtzeit Fahrzeugerkennung und -zählung mit YOLOv8 und SORT]]></title>
            <link>https://medium.com/@Mert.A/echtzeit-fahrzeugerkennung-und-z%C3%A4hlung-mit-yolov8-und-sort-f26b72d8cf30?source=rss-323545448d05------2</link>
            <guid isPermaLink="false">https://medium.com/p/f26b72d8cf30</guid>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[sort]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Mert]]></dc:creator>
            <pubDate>Wed, 16 Apr 2025 16:02:24 GMT</pubDate>
            <atom:updated>2025-04-16T16:02:24.070Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yX-SZm9QQP_JfJW985byIA.gif" /></figure><p><em>“Wie viele Fahrzeuge haben die linke und rechte Straßenseite passiert?”</em> — In diesem Projekt beantworte ich diese Frage mithilfe von Echtzeit-Objekterkennung und -verfolgung mit <strong>YOLOv8</strong>, <strong>SORT</strong> und <strong>OpenCV</strong>.</p><p>Ich habe ein System entwickelt, das Fahrzeuge in einem Video erkennt und verfolgt, zählt, wie viele eine definierte Linie überqueren, und alles in Echtzeit visualisiert — ein hervorragendes Beispiel für Computer Vision im Bereich Verkehrsüberwachung.</p><h4>Schritt 1: Benötigte Bibliotheken installieren</h4><pre>pip install ultralytics opencv-python numpy filterpy scikit-image</pre><h4>Schritt 2: Bibliotheken importieren</h4><pre>import cv2<br>from ultralytics import YOLO<br>from sort import *<br>from help_func import create_video_writer</pre><p>Die Datei sort.py findest du auf <a href="https://github.com/MertAkguel/TrafficAnalysis#">GitHub</a>. Sie enthält den Multi-Object-Tracking-Algorithmus SORT, der Objekten über mehrere Frames hinweg konsistente IDs zuweist, basierend auf den Bounding Boxes eines Detektors wie YOLO oder Faster R-CNN.</p><p><strong>Die Kernideen von SORT:</strong></p><ul><li><strong>Vorhersage:</strong> Wo wird sich ein Objekt im nächsten Frame befinden?</li><li><strong>Zuordnung:</strong> Neue Detektionen den Vorhersagen zuordnen</li><li><strong>Update:</strong> Tracker mit neuen Positionen aktualisieren</li><li><strong>Verwaltung:</strong> Neue Tracker erstellen und veraltete löschen</li></ul><h4>Schritt 3: Videoquelle und Modell vorbereiten</h4><pre>BLUE = (255, 0, 0)<br>RED = (0, 0, 255)<br>GREEN = (0, 255, 0)<br><br># Link zum Video: https://youtu.be/KBsqQez-O4w?si=iUbXmv8Q1dlnzm69<br>path = r&quot;PfadZumVideo&quot;<br>output_filename = &quot;video/hightraffic_result.mp4&quot;<br><br>CLASS_ID = [2, 3, 5, 7]  # Auto, Motorrad, Bus, LKW<br>model = YOLO(&quot;yolov8l.pt&quot;)<br>tracker = Sort(max_age=20, min_hits=2, iou_threshold=0.3)</pre><ul><li>Nur Fahrzeugklassen detektieren</li><li>YOLOv8 Modell und SORT Tracker initialisieren</li></ul><h4>Schritt 4: Video öffnen und Variablen initialisieren</h4><pre>cap = cv2.VideoCapture(path)<br>writer = create_video_writer(cap, output_filename)<br><br>left_road_count = []<br>right_road_count = []<br>limits = [0, 600, 1280, 600]  # Horizontale Linie</pre><h4>Schritt 5: Videoframes verarbeiten</h4><pre>while True:<br>    success, img = cap.read()<br>    if not success:<br>        break<br><br>    results = model.predict(img, classes=CLASS_ID)<br>    detections = np.empty((0, 5))<br><br>    for r in results:<br>        for box in r.boxes:<br>            conf = np.ceil((box.conf[0] * 100)) / 100<br>            if conf &lt; 0.3:<br>                continue<br>            x1, y1, x2, y2 = map(int, box.xyxy[0])<br>            detections = np.vstack((detections, np.array([x1, y1, x2, y2, conf])))</pre><p>Bounding Boxes werden aus YOLO-Vorhersagen extrahiert und zur Weiterverarbeitung vorbereitet.</p><h4>Schritt 6: Objekte verfolgen</h4><pre>    resultsTracker = tracker.update(detections)<br><br>    for result in resultsTracker:<br>        x1, y1, x2, y2, id = map(int, result)<br>        cx, cy = x1 + (x2 - x1) // 2, y1 + (y2 - y1) // 2</pre><p>SORT liefert aktuelle Objektpositionen mit einzigartigen IDs.</p><h4>Schritt 7: Linienüberquerung erkennen und zählen</h4><pre>        if cx &gt; img.shape[1] // 2 and limits[1] - 15 &lt; cy &lt; limits[1] + 15:<br>            if id not in right_road_count:<br>                right_road_count.append(id)<br><br>        elif cx &lt; img.shape[1] // 2 and limits[1] - 15 &lt; cy &lt; limits[1] + 15:<br>            if id not in left_road_count:<br>                left_road_count.append(id)</pre><p>Die Linie befindet sich bei y = 600. Je nach cx-Position wird links oder rechts gezählt.</p><h4>Schritt 8: Visualisierung und Ausgabe speichern</h4><pre>    cv2.line(img, (limits[0], limits[1]), (limits[2], limits[3]), (255, 0, 255), 5)<br>    cv2.putText(img, str(len(left_road_count)), (255, 100), cv2.FONT_HERSHEY_PLAIN, 5, (0, 0, 255), 8)<br>    cv2.putText(img, str(len(right_road_count)), (800, 100), cv2.FONT_HERSHEY_PLAIN, 5, (255, 0, 0), 8)<br><br>    writer.write(img)<br>    cv2.imshow(&quot;Video&quot;, img)<br>    if cv2.waitKey(1) == ord(&#39;q&#39;):<br>        break</pre><p>Zähler werden dargestellt, Linien gezeichnet, und das Video gespeichert.</p><h4>Schritt 9: Alles freigeben</h4><pre>writer.release()<br>cv2.destroyAllWindows()</pre><h4>Schritt 10: Hilfsfunktion (help_func.py)</h4><pre>import cv2<br><br>def create_video_writer(video_cap, output_filename):<br>    frame_width = int(video_cap.get(cv2.CAP_PROP_FRAME_WIDTH))<br>    frame_height = int(video_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))<br>    fps = int(video_cap.get(cv2.CAP_PROP_FPS))<br><br>    fourcc = cv2.VideoWriter_fourcc(*&#39;XVID&#39;)<br>    writer = cv2.VideoWriter(output_filename, fourcc, fps,<br>                             (frame_width, frame_height))<br>    return writer</pre><p>Diese Funktion initialisiert den VideoWriter korrekt.</p><h3>Der komplette Code:</h3><p><strong>main.py</strong></p><pre>import cv2<br>from ultralytics import YOLO<br>from sort import *<br>from help_func import create_video_writer<br><br>BLUE = (255, 0, 0)<br>RED = (0, 0, 255)<br>GREEN = (0, 255, 0)<br><br># https://youtu.be/KBsqQez-O4w?si=iUbXmv8Q1dlnzm69<br>path = r&quot;D:\ML_datasets\CarsVideoObjectTracking\4KVideoOfHighwayTraffic!.mp4&quot;<br>output_filename = &quot;video/hightraffic_result.mp4&quot;<br><br># class_ids of interest - car, motorcycle, bus and truck<br>CLASS_ID = [2, 3, 5, 7]<br><br>model = YOLO(&quot;yolov8l.pt&quot;)<br>tracker = Sort(max_age=20, min_hits=2, iou_threshold=0.3)<br><br>cap = cv2.VideoCapture(path)<br>writer = create_video_writer(cap, output_filename)<br><br>pTime = 0<br><br>left_road_count = []<br>right_road_count = []<br>color = (0, 0, 0)<br><br>crossed_line_already = set()<br><br>limits = [0, 600, 1280, 600]<br><br>print(&quot;So it begins&quot;)<br>while True:<br>    success, img = cap.read()<br><br>    if not success:<br>        break<br><br>    height, width, _ = img.shape  # 720, 1280<br><br>    results = model.predict(img, classes=CLASS_ID)<br><br>    detections = np.empty((0, 5))<br><br>    for r in results:<br>        boxes = r.boxes<br>        for i, box in enumerate(r.boxes):<br><br>            conf = np.ceil((box.conf[0] * 100)) / 100<br><br>            x1 = int(box.xyxy[0][0])<br>            y1 = int(box.xyxy[0][1])<br>            x2 = int(box.xyxy[0][2])<br>            y2 = int(box.xyxy[0][3])<br><br>            cx = int((x1 + x1 + (x2 - x1)) / 2)<br>            cy = int((y1 + y1 + (y2 - y1)) // 2)<br><br>            if x2 &lt; width // 2:<br>                color = BLUE<br>            else:<br>                color = RED<br><br>            currentArray = np.array([x1, y1, x2, y2, conf])<br>            detections = np.vstack((detections, currentArray))<br><br>            # cv2.rectangle(img, (x1, y1), (x2, y2), color, 2)<br><br>    resultsTracker = tracker.update(detections)<br><br>    color_line = (255, 0, 255)<br><br>    for result in resultsTracker:<br>        x1, y1, x2, y2, id = result<br>        x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)<br>        # print(result)<br>        w, h = x2 - x1, y2 - y1<br><br>        cx, cy = x1 + w // 2, y1 + h // 2<br>        color_circle = (255, 0, 255)<br><br>        if cx &gt; width // 2 and limits[1] - 15 &lt; cy &lt; limits[1] + 15:<br>            if right_road_count.count(id) == 0:<br>                right_road_count.append(id)<br><br>                color_line = BLUE<br>                color_circle = BLUE<br><br>        elif cx &lt; width // 2 and limits[1] - 15 &lt; cy &lt; limits[1] + 15:<br>            if left_road_count.count(id) == 0:<br>                left_road_count.append(id)<br>                color_line = RED<br>                color_circle = RED<br><br>        # cv2.circle(img, (cx, cy), 5, (255, 0, 255), cv2.FILLED)<br><br>    cv2.line(img, (limits[0], limits[1]), (limits[2], limits[3]), color_line, 5)<br><br>    # cvzone.putTextRect(img, f&#39; Count: {len(totalCount)}&#39;, (50, 50))<br>    cv2.putText(img, str(len(left_road_count)), (255, 100), cv2.FONT_HERSHEY_PLAIN, 5, RED, 8)<br>    cv2.putText(img, str(len(right_road_count)), (800, 100), cv2.FONT_HERSHEY_PLAIN, 5, BLUE, 8)<br>    cTime = time.time()<br>    fps = 1 / (cTime - pTime)<br>    pTime = cTime<br><br>    cv2.putText(img, f&#39;FPS: {int(fps)}&#39;, (20, 70), cv2.FONT_HERSHEY_PLAIN, 3, GREEN, 2)<br>    cv2.imshow(&quot;Video&quot;, img)<br>    writer.write(img)<br><br>    k = cv2.waitKey(1)<br>    if k == ord(&#39;q&#39;):<br>        break<br>    &quot;&quot;&quot;elif k == ord(&#39;s&#39;):<br>        continue&quot;&quot;&quot;<br><br>writer.release()<br>cv2.destroyAllWindows()</pre><p><strong>help_func.py</strong></p><pre>import cv2<br><br>def create_video_writer(video_cap, output_filename):<br>    # grab the width, height, and fps of the frames in the video stream.<br>    frame_width = int(video_cap.get(cv2.CAP_PROP_FRAME_WIDTH))<br>    frame_height = int(video_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))<br>    fps = int(video_cap.get(cv2.CAP_PROP_FPS))<br><br>    # initialize the FourCC and a video writer object<br>    fourcc = cv2.VideoWriter_fourcc(*&#39;XVID&#39;)<br>    writer = cv2.VideoWriter(output_filename, fourcc, fps,<br>                             (frame_width, frame_height))<br><br>    return writer</pre><h3>Fazit</h3><p>In diesem Projekt habe ich Echtzeit-Objekterkennung und -verfolgung kombiniert, um den Verkehr in einem Video zu überwachen. Ich habe gelernt:</p><ul><li>Objekterkennung mit YOLO zu integrieren</li><li>SORT zur Verfolgung mit Kalman-Filter und ungarischem Algorithmus zu nutzen</li><li>Objekte beim Überqueren einer definierten Linie zu zählen</li><li>Ergebnisse mit OpenCV visuell darzustellen</li></ul><p>Dieses Projekt ist Teil meines Portfolios und zeigt angewandte Computer Vision. Ich hoffe, es gibt dir Inspiration oder Hilfe für deine eigenen Projekte. Du kannst den Code gerne forken, mit eigenen Videos testen oder ein Dashboard darauf aufbauen!</p><p>💬 Schreib mir gerne, wenn du Fragen hast — ich helfe gerne weiter!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f26b72d8cf30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-Time Vehicle Tracking and Counting Using YOLOv8 and SORT with OpenCV]]></title>
            <link>https://medium.com/@Mert.A/real-time-vehicle-tracking-and-counting-using-yolov8-and-sort-with-opencv-cfce239c0567?source=rss-323545448d05------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfce239c0567</guid>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[sort]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Mert]]></dc:creator>
            <pubDate>Wed, 16 Apr 2025 16:02:22 GMT</pubDate>
            <atom:updated>2025-04-16T16:02:22.619Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yX-SZm9QQP_JfJW985byIA.gif" /></figure><p>“How many vehicles passed on the left and right side of the road?” — In this project, I answer this question using real-time object detection and tracking with <strong>YOLOv8</strong>, <strong>SORT</strong>, and <strong>OpenCV.</strong></p><p>I built a system that detects and tracks vehicles in a video, counts how many cross a certain line, and visualizes everything on the screen — a great example of computer vision in traffic monitoring.</p><h3>Getting Started</h3><h4>Step 1: Install the Required Libraries</h4><pre>pip install ultralytics opencv-python numpy filterpy</pre><h4>Step 2: Import the Libraries</h4><pre>import cv2<br>from ultralytics import YOLO<br>from sort import *<br>from help_func import create_video_writer</pre><p>The sort file can you find at <a href="https://github.com/MertAkguel/TrafficAnalysis#">Github</a>. The sort file uses<strong> </strong>a <strong>multi-object tracking algorithm</strong>. It <strong>assigns consistent IDs to objects</strong> across video frames, using <strong>bounding boxes</strong> from an object detector like YOLO or Faster R-CNN.</p><h4>The Core Ideas of SORT:</h4><ol><li><strong>Prediction</strong>: Predict where each object will be in the next frame.</li><li><strong>Association</strong>: Match new detections to those predictions.</li><li><strong>Update</strong>: Update trackers with new positions if matched.</li><li><strong>Management</strong>: Create trackers for new objects and remove old ones that are no longer seen.</li></ol><h4>Step 3: Prepare the Video Source and Model</h4><pre>BLUE = (255, 0, 0)<br>RED = (0, 0, 255)<br>GREEN = (0, 255, 0)<br><br># Link to video: # https://youtu.be/KBsqQez-O4w?si=iUbXmv8Q1dlnzm69<br>path = r&quot;PathToVideo&quot;<br>output_filename = &quot;video/hightraffic_result.mp4&quot;<br><br>CLASS_ID = [2, 3, 5, 7]  # car, motorcycle, bus, truck<br>model = YOLO(&quot;yolov8l.pt&quot;)<br>tracker = Sort(max_age=20, min_hits=2, iou_threshold=0.3)</pre><ul><li>Only detect vehicle classes</li><li>Initialize the YOLOv8 model and SORT tracker</li></ul><h4>Step 4: Open the Video and Initialize Variables</h4><p>This sets up the video reader/writer and the counter lists.</p><pre>cap = cv2.VideoCapture(path)<br>writer = create_video_writer(cap, output_filename)<br><br>left_road_count = []<br>right_road_count = []<br>limits = [0, 600, 1280, 600]  # Horizontal line</pre><h4>Step 5: Process Video Frame-by-Frame</h4><p>Loop over the video frames, detect vehicles, and track them</p><pre>while True:<br>    success, img = cap.read()<br>    if not success:<br>        break<br><br>    results = model.predict(img, classes=CLASS_ID)<br>    detections = np.empty((0, 5))<br><br>    for r in results:<br>        for box in r.boxes:<br>            conf = np.ceil((box.conf[0] * 100)) / 100<br>            if conf &lt; 0.3:<br>                continue<br>            x1, y1, x2, y2 = map(int, box.xyxy[0])<br>            detections = np.vstack((detections, np.array([x1, y1, x2, y2, conf])))</pre><p>This extracts bounding boxes from YOLO predictions and prepares them for tracking.</p><h4>Step 6: Track the Objects</h4><pre>    resultsTracker = tracker.update(detections)<br><br>    for result in resultsTracker:<br>        x1, y1, x2, y2, id = map(int, result)<br>        cx, cy = x1 + (x2 - x1) // 2, y1 + (y2 - y1) // 2</pre><p>This part runs SORT and gets updated object positions with unique IDs.</p><h4>Step 7: Detect Line Crossings and Count</h4><pre>        if cx &gt; img.shape[1] // 2 and limits[1] - 15 &lt; cy &lt; limits[1] + 15:<br>            if id not in right_road_count:<br>                right_road_count.append(id)<br><br>        elif cx &lt; img.shape[1] // 2 and limits[1] - 15 &lt; cy &lt; limits[1] + 15:<br>            if id not in left_road_count:<br>                left_road_count.append(id)</pre><ul><li>The line is at y = 600</li><li>Depending on the cx position, we count left or right</li></ul><h4>Step 8: Draw Visuals and Save the Output</h4><pre>    cv2.line(img, (limits[0], limits[1]), (limits[2], limits[3]), (255, 0, 255), 5)<br>    cv2.putText(img, str(len(left_road_count)), (255, 100), cv2.FONT_HERSHEY_PLAIN, 5, (0, 0, 255), 8)<br>    cv2.putText(img, str(len(right_road_count)), (800, 100), cv2.FONT_HERSHEY_PLAIN, 5, (255, 0, 0), 8)<br><br>    writer.write(img)<br>    cv2.imshow(&quot;Video&quot;, img)<br>    if cv2.waitKey(1) == ord(&#39;q&#39;):<br>        break</pre><p>We draw the counting line, display counts, and save the output video.</p><h4>Step 9: Release Everything</h4><pre>writer.release()<br>cv2.destroyAllWindows()</pre><h4>Step 10: Helper Function (help_func.py)</h4><p><strong>help_func.py</strong></p><pre>import cv2<br><br>def create_video_writer(video_cap, output_filename):<br>    # grab the width, height, and fps of the frames in the video stream.<br>    frame_width = int(video_cap.get(cv2.CAP_PROP_FRAME_WIDTH))<br>    frame_height = int(video_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))<br>    fps = int(video_cap.get(cv2.CAP_PROP_FPS))<br><br>    # initialize the FourCC and a video writer object<br>    fourcc = cv2.VideoWriter_fourcc(*&#39;XVID&#39;)<br>    writer = cv2.VideoWriter(output_filename, fourcc, fps,<br>                             (frame_width, frame_height))<br><br>    return writer</pre><p>This helper initializes the video writer with correct properties.</p><h4>The whole code:</h4><p><strong>main.py</strong></p><pre>import cv2<br>from ultralytics import YOLO<br>from sort import *<br>from help_func import create_video_writer<br><br>BLUE = (255, 0, 0)<br>RED = (0, 0, 255)<br>GREEN = (0, 255, 0)<br><br># https://youtu.be/KBsqQez-O4w?si=iUbXmv8Q1dlnzm69<br>path = r&quot;D:\ML_datasets\CarsVideoObjectTracking\4KVideoOfHighwayTraffic!.mp4&quot;<br>output_filename = &quot;video/hightraffic_result.mp4&quot;<br><br># class_ids of interest - car, motorcycle, bus and truck<br>CLASS_ID = [2, 3, 5, 7]<br><br>model = YOLO(&quot;yolov8l.pt&quot;)<br>tracker = Sort(max_age=20, min_hits=2, iou_threshold=0.3)<br><br>cap = cv2.VideoCapture(path)<br>writer = create_video_writer(cap, output_filename)<br><br>pTime = 0<br><br>left_road_count = []<br>right_road_count = []<br>color = (0, 0, 0)<br><br>crossed_line_already = set()<br><br>limits = [0, 600, 1280, 600]<br><br>print(&quot;So it begins&quot;)<br>while True:<br>    success, img = cap.read()<br><br>    if not success:<br>        break<br><br>    height, width, _ = img.shape  # 720, 1280<br><br>    results = model.predict(img, classes=CLASS_ID)<br><br>    detections = np.empty((0, 5))<br><br>    for r in results:<br>        boxes = r.boxes<br>        for i, box in enumerate(r.boxes):<br><br>            conf = np.ceil((box.conf[0] * 100)) / 100<br><br>            x1 = int(box.xyxy[0][0])<br>            y1 = int(box.xyxy[0][1])<br>            x2 = int(box.xyxy[0][2])<br>            y2 = int(box.xyxy[0][3])<br><br>            cx = int((x1 + x1 + (x2 - x1)) / 2)<br>            cy = int((y1 + y1 + (y2 - y1)) // 2)<br><br>            if x2 &lt; width // 2:<br>                color = BLUE<br>            else:<br>                color = RED<br><br>            currentArray = np.array([x1, y1, x2, y2, conf])<br>            detections = np.vstack((detections, currentArray))<br><br>            # cv2.rectangle(img, (x1, y1), (x2, y2), color, 2)<br><br>    resultsTracker = tracker.update(detections)<br><br>    color_line = (255, 0, 255)<br><br>    for result in resultsTracker:<br>        x1, y1, x2, y2, id = result<br>        x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)<br>        # print(result)<br>        w, h = x2 - x1, y2 - y1<br><br>        cx, cy = x1 + w // 2, y1 + h // 2<br>        color_circle = (255, 0, 255)<br><br>        if cx &gt; width // 2 and limits[1] - 15 &lt; cy &lt; limits[1] + 15:<br>            if right_road_count.count(id) == 0:<br>                right_road_count.append(id)<br><br>                color_line = BLUE<br>                color_circle = BLUE<br><br>        elif cx &lt; width // 2 and limits[1] - 15 &lt; cy &lt; limits[1] + 15:<br>            if left_road_count.count(id) == 0:<br>                left_road_count.append(id)<br>                color_line = RED<br>                color_circle = RED<br><br>        # cv2.circle(img, (cx, cy), 5, (255, 0, 255), cv2.FILLED)<br><br>    cv2.line(img, (limits[0], limits[1]), (limits[2], limits[3]), color_line, 5)<br><br>    # cvzone.putTextRect(img, f&#39; Count: {len(totalCount)}&#39;, (50, 50))<br>    cv2.putText(img, str(len(left_road_count)), (255, 100), cv2.FONT_HERSHEY_PLAIN, 5, RED, 8)<br>    cv2.putText(img, str(len(right_road_count)), (800, 100), cv2.FONT_HERSHEY_PLAIN, 5, BLUE, 8)<br>    cTime = time.time()<br>    fps = 1 / (cTime - pTime)<br>    pTime = cTime<br><br>    cv2.putText(img, f&#39;FPS: {int(fps)}&#39;, (20, 70), cv2.FONT_HERSHEY_PLAIN, 3, GREEN, 2)<br>    cv2.imshow(&quot;Video&quot;, img)<br>    writer.write(img)<br><br>    k = cv2.waitKey(1)<br>    if k == ord(&#39;q&#39;):<br>        break<br>    &quot;&quot;&quot;elif k == ord(&#39;s&#39;):<br>        continue&quot;&quot;&quot;<br><br>writer.release()<br>cv2.destroyAllWindows()</pre><p><strong>help_func.py</strong></p><pre>import cv2<br><br><br>def create_video_writer(video_cap, output_filename):<br>    # grab the width, height, and fps of the frames in the video stream.<br>    frame_width = int(video_cap.get(cv2.CAP_PROP_FRAME_WIDTH))<br>    frame_height = int(video_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))<br>    fps = int(video_cap.get(cv2.CAP_PROP_FPS))<br><br>    # initialize the FourCC and a video writer object<br>    fourcc = cv2.VideoWriter_fourcc(*&#39;XVID&#39;)<br>    writer = cv2.VideoWriter(output_filename, fourcc, fps,<br>                             (frame_width, frame_height))<br><br>    return writer</pre><h3>Conclusion</h3><p>In this project, I combined real-time object detection and tracking using YOLOv8 and SORT to monitor traffic in a video. I learned how to:</p><ul><li>Integrate detection and tracking</li><li>Use Kalman Filters and the Hungarian Algorithm (via SORT)</li><li>Count objects crossing a defined region</li><li>Visualize real-time results with OpenCV</li></ul><p>This project is part of my portfolio to demonstrate applied computer vision, and I hope it gives you insight or inspiration for your own projects. Feel free to fork the code, test it on your own footage, or build a dashboard on top of it!</p><p>Let me know what you think or if you have any questions — I am happy to help!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfce239c0567" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mit welchem Auge blinzeln Sie mehr? Ich habe ein Python-Tool gebaut, um das herauszufinden]]></title>
            <link>https://medium.com/@Mert.A/mit-welchem-auge-blinzeln-sie-mehr-ich-habe-ein-python-tool-gebaut-um-das-herauszufinden-ffa5e2cc8f44?source=rss-323545448d05------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffa5e2cc8f44</guid>
            <category><![CDATA[mediapipe]]></category>
            <category><![CDATA[pygame]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[numpy]]></category>
            <dc:creator><![CDATA[Mert]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 22:01:39 GMT</pubDate>
            <atom:updated>2025-04-12T22:01:39.394Z</atom:updated>
            <content:encoded><![CDATA[<p>Haben Sie sich jemals gefragt, ob Sie mehr mit dem linken oder dem rechten Auge blinzeln? Als Computer-Vision-Enthusiast habe ich beschlossen, diese Frage mit einem lustigen Projekt zu beantworten, das OpenCV und MediaPipe verwendet, um zu verfolgen und zu zählen, wie oft jedes Auge geschlossen ist. Dieser Blog wird Sie Schritt für Schritt durch den gesamten Prozess führen, den Code erklären und Ihnen zeigen, wie Sie das Projekt selbst bauen können.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*3xshIkBYM2JCCuc3MUFBoQ.gif" /><figcaption>Demo of Counting the Eye Blinker</figcaption></figure><h3>Motivation</h3><p>Die Idee kam mir, als ich über Methoden zur Erkennung von Blinzeln in Müdigkeitsstudien las. Ich stieß auf eine Methode, die das Augen-Aspekt-Verhältnis (EAR) zur Erkennung des Augenschlusses verwendet, und dachte, es wäre interessant, die Blinzler pro Auge zu zählen. Die Blinzelerkennung wird in der Regel bei Fahrerwarnsystemen oder bei der medizinischen Überwachung eingesetzt, aber ich wollte einfach experimentieren und mehr über die Echtzeitverfolgung von Gesichtsmerkmalen lernen.</p><h4>Schritt 1: Installation der erforderlichen Bibliotheken</h4><pre>pip install opencv-python mediapipe pygame numpy</pre><h4>Schritt 2: Importieren der Bibliotheken</h4><p>In zwei Dateien werden wir diese Bibliotheken verwenden:</p><ul><li>cv2 (OpenCV) für Kamera und Bildverarbeitung</li><li>mediapipe für die Erkennung von Gesichtsmerkmalen</li><li>pygame um einen Ton abzuspielen, wenn ein Blinken erkannt wird</li><li>numpy für die Entfernungsberechnung</li></ul><h4>Schritt 3: Erstellen des FaceMeshModuls (Erkennung von Gesichtsmerkmalen)</h4><p>Um Gesichtsmerkmale zu erkennen und die Punkte um die Augen zu extrahieren, verwenden wir das FaceMesh-Modell von MediaPipe.</p><pre># File: FaceMeshModule.py<br>import cv2<br>import mediapipe as mp<br><br>GREEN = (0, 255, 0)  # color used for drawing points<br><br>class FaceMeshDetector:<br>    def __init__(self, static_image_mode=False, max_num_faces=1, refine_landmarks=False, min_detection_con=0.5,<br>                 min_tracking_con=0.5):<br>        # Initialize FaceMesh with selected options<br>        self.mpFaceMesh = mp.solutions.face_mesh<br>        self.faceMesh = self.mpFaceMesh.FaceMesh(static_image_mode, max_num_faces, refine_landmarks,<br>                                                 min_detection_con, min_tracking_con)<br>        # Coordinates for the 6 key points around each eye<br>        self.LEFT_IRIS = [362, 385, 387, 263, 373, 380]<br>        self.RIGHT_IRIS = [33, 160, 158, 133, 153, 144]<br>        self.BOTH_IRISES = self.LEFT_IRIS + self.RIGHT_IRIS<br>    def findMeshIrises(self, img, draw=True, color=GREEN):<br>        # Convert the BGR image to RGB<br>        img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)<br>        # Process the image to detect facial landmarks<br>        results = self.faceMesh.process(img_rgb)<br>        eye_landmarks = []<br>        faces = []<br>        if results.multi_face_landmarks:<br>            for faceLms in results.multi_face_landmarks:<br>                eye_landmarks = []<br>                face = []<br>                for i, lm in enumerate(faceLms.landmark):<br>                    if i in self.BOTH_IRISES:<br>                        h, w, _ = img.shape<br>                        x, y = int(lm.x * w), int(lm.y * h)<br>                        eye_landmarks.append((x, y))<br>                        if draw:<br>                            cv2.circle(img, (x, y), 1, color, -1)<br>                        face.append([x, y])<br>                faces.append(face)<br>        return img, faces, eye_landmarks</pre><h4>Schritt 4: Berechnung des Augen-Aspekt-Verhältnisses (EAR)</h4><p>Um festzustellen, ob das Auge geschlossen ist, berechnen wir das Augen-Aspekt-Verhältnis anhand des euklidischen Abstands zwischen bestimmten Augenmerkpunkten.</p><pre># Calculate distance between two 2D points<br>def get_distance(point1, point2):<br>    distance = []<br>    for p1, p2 in zip(point1, point2):<br>        distance.append((p2 - p1) ** 2)<br>    return np.sqrt(np.sum(distance))<br><br># Calculate Eye Aspect Ratio using 6 key eye points<br>def get_eye_aspect_ratio(p1, p2, p3, p4, p5, p6):<br>    # EAR formula: (||p2 - p6|| + ||p3 - p5||) / (2 * ||p1 - p4||)<br>    distance_p2_6 = get_distance(p2, p6)<br>    distance_p3_5 = get_distance(p3, p5)<br>    distance_p1_4 = get_distance(p1, p4)<br>    ear = (distance_p2_6 + distance_p3_5) / (2 * distance_p1_4)<br>    return ear</pre><h4>Schritt 5: Blinzelerkennung und Zähler</h4><p>Die Hauptschleife liest von der Webcam, erkennt Orientierungspunkte, berechnet die EAR und zählt, wenn sich ein Auge unterhalb eines Schwellenwerts (0,15) schließt.</p><pre># File: Eyeblinker.py<br>import cv2<br>import numpy as np<br>import time<br>from FaceMeshModule import FaceMeshDetector<br>import pygame<br><br>pygame.init()<br># # you can download it here: https://pixabay.com/sound-effects/click-124467/<br>click_sound = pygame.mixer.Sound(r&quot;ThePathToTheSound&quot;)<br>colour = (0, 255, 0)<br>if __name__ == &quot;__main__&quot;:<br>    cap = cv2.VideoCapture(0)  # Start webcam<br>    p_time = 0  # For FPS calculation<br>    detector = FaceMeshDetector(refine_landmarks=True)<br>    left_eye_counter = 0<br>    right_eye_counter = 0<br>    left_eye_opened = True<br>    right_eye_opened = True<br>    while True:<br>        success, img = cap.read()<br>        h, w, _ = img.shape<br>        c_time = time.time()<br>        fps = 1 / (c_time - p_time)<br>        p_time = c_time<br>        try:<br>            # Detect eye landmarks<br>            img, faces, eye_landmarks = detector.findMeshIrises(img, draw=True, color=colour)<br>            left_p = eye_landmarks[6:]   # Left eye landmarks<br>            right_p = eye_landmarks[:6]  # Right eye landmarks<br>            # Calculate EAR for both eyes<br>            left_eye_ear = get_eye_aspect_ratio(left_p[1], left_p[4], left_p[5], left_p[0], left_p[2], left_p[3])<br>            right_eye_ear = get_eye_aspect_ratio(right_p[0], right_p[5], right_p[4], right_p[1], right_p[3], right_p[2])<br>            # If EAR is below threshold, register blink only once while eye is closed<br>            if left_eye_ear &lt; 0.15 and left_eye_opened:<br>                left_eye_counter += 1<br>                left_eye_opened = False<br>                pygame.mixer.Sound.play(click_sound)<br>            if left_eye_ear &gt; 0.15:<br>                left_eye_opened = True<br>            if right_eye_ear &lt; 0.15 and right_eye_opened:<br>                right_eye_counter += 1<br>                right_eye_opened = False<br>            if right_eye_ear &gt; 0.15:<br>                right_eye_opened = True<br>        except Exception:<br>            pass<br>        # Show results on screen<br>        cv2.putText(img, f&#39;FPS: {int(fps)}&#39;, (20, 70), cv2.FONT_HERSHEY_PLAIN, 3, colour, 1)<br>        cv2.putText(img, f&#39;Left EyeCounter: {left_eye_counter}&#39;, (20, h // 2), cv2.FONT_HERSHEY_PLAIN, 1, colour, 1)<br>        cv2.putText(img, f&#39;Right EyeCounter: {right_eye_counter}&#39;, (20, h // 2 + 50), cv2.FONT_HERSHEY_PLAIN, 1, colour, 1)<br>        cv2.imshow(&quot;Image&quot;, img)<br>        # Press &#39;q&#39; to quit<br>        key = cv2.waitKey(1)<br>        if key == ord(&#39;q&#39;):<br>            break<br>    cap.release()<br>    cv2.destroyAllWindows()</pre><h3>Vollständiger Quellcode</h3><p>Zu Ihrer Erleichterung finden Sie hier den vollständigen Code für beide Dateien:</p><h4>FaceMeshModule.py</h4><pre>import cv2<br>import mediapipe as mp<br><br>GREEN = (0, 255, 0)<br><br>class FaceMeshDetector:<br>    def __init__(self, static_image_mode=False, max_num_faces=1, refine_landmarks=False, min_detection_con=0.5,<br>                 min_tracking_con=0.5):<br>        self.static_image_mode = static_image_mode<br>        self.max_num_faces = max_num_faces<br>        self.refine_landmarks = refine_landmarks<br>        self.min_detection_con = min_detection_con<br>        self.min_tracking_con = min_tracking_con<br>        self.mpDraw = mp.solutions.drawing_utils<br>        self.mpFaceMesh = mp.solutions.face_mesh<br>        self.faceMesh = self.mpFaceMesh.FaceMesh(self.static_image_mode, self.max_num_faces, self.refine_landmarks,<br>                                                 self.min_detection_con, self.min_tracking_con)<br>        # coordiantes we need for EAR, for more info see this paper:<br>        # https://vision.fe.uni-lj.si/cvww2016/proceedings/papers/05.pdf<br>        self.LEFT_IRIS = [362, 385, 387, 263, 373, 380]<br>        self.RIGHT_IRIS = [33, 160, 158, 133, 153, 144]<br>        self.BOTH_IRISES = self.LEFT_IRIS + self.RIGHT_IRIS<br>    def findMeshIrises(self, img, draw=True, color=GREEN):<br>        img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)<br>        results = self.faceMesh.process(img_rgb)<br>        eye_landmarks = []<br>        faces = []<br>        if results.multi_face_landmarks:<br>            for faceLms in results.multi_face_landmarks:<br>                eye_landmarks = []<br>                face = []<br>                for i, lm in enumerate(faceLms.landmark):<br>                    if i in self.BOTH_IRISES:<br>                        h, w, ic = img.shape<br>                        x, y = int(lm.x * w), int(lm.y * h)<br>                        eye_landmarks.append((x, y))<br>                        # cv2.putText(img, str(id), (x, y), cv2.FONT_HERSHEY_PLAIN, 1, GREEN, 1)<br>                        if draw:<br>                            cv2.circle(img, (x, y), 1, color, -1)<br>                        face.append([x, y])<br>                faces.append(face)<br>        return img, faces, eye_landmarks</pre><h4>Eyeblinker.py</h4><pre>import cv2<br>import numpy as np<br>import time<br>from FaceMeshModule import FaceMeshDetector<br>import pygame<br><br>pygame.init()<br># you can download it here: https://pixabay.com/sound-effects/click-124467/<br>click_sound = pygame.mixer.Sound(<br>    r&quot;C:\Users\Kleve\Downloads\click-124467.mp3&quot;)<br>GREEN = (0, 255, 0)<br>BLUE = (255, 0, 0)<br>RED = (0, 0, 255)<br>colour = GREEN<br><br>def get_distance(point1, point2):<br>    &quot;&quot;&quot;<br>    calculate Euclidean distance between point1 and point2<br>    :param point1: (x, y, z) landmark of point1<br>    :param point2: (x, y, z) landmark of point2<br>    :return: Euclidean distance between point1 and point2<br>    &quot;&quot;&quot;<br>    distance = []<br>    for p1, p2 in zip(point1, point2):<br>        distance.append((p2 - p1) ** 2)<br>    return np.sqrt(np.sum(distance))<br><br>def get_eye_aspect_ratio(p1, p2, p3, p4, p5, p6):<br>    distance_p2_6 = get_distance(p2, p6)<br>    distance_p3_5 = get_distance(p3, p5)<br>    distance_p1_4 = get_distance(p1, p4)<br>    ear = (distance_p2_6 + distance_p3_5) / (2 * distance_p1_4)<br>    return ear<br><br>if __name__ == &quot;__main__&quot;:<br>    cap = cv2.VideoCapture(0)<br>    pTime = 0<br>    detector = FaceMeshDetector(refine_landmarks=True)<br>    left_eye_counter = 0<br>    right_eye_counter = 0<br>    left_eye_opened = True<br>    right_eye_opened = True<br>    while True:<br>        success, img = cap.read()<br>        h, w, _ = img.shape<br>        cTime = time.time()<br>        fps = 1 / (cTime - pTime)<br>        pTime = cTime<br>        try:<br>            img, faces, eye_landmarks = detector.findMeshIrises(img, draw=True, color=colour)<br>            left_p = eye_landmarks[6:]<br>            right_p = eye_landmarks[:6]<br>            left_eye_ear = get_eye_aspect_ratio(left_p[1], left_p[4], left_p[5],<br>                                                left_p[0], left_p[2], left_p[3])<br>            right_eye_ear = get_eye_aspect_ratio(right_p[0], right_p[5], right_p[4],<br>                                                 right_p[1], right_p[3], right_p[2])<br>            avg_ear = (left_eye_ear + right_eye_ear) / 2.0<br>            if left_eye_ear &lt; 0.15 and left_eye_opened:<br>                left_eye_counter += 1<br>                left_eye_opened = False<br>                pygame.mixer.Sound.play(click_sound)<br>            if left_eye_ear &gt; 0.15:<br>                left_eye_opened = True<br>            if right_eye_ear &lt; 0.15 and right_eye_opened:<br>                right_eye_counter += 1<br>                right_eye_opened = False<br>            if right_eye_ear &gt; 0.15:<br>                right_eye_opened = True<br>        except Exception:<br>            pass<br>        cv2.putText(img, f&#39;FPS: {int(fps)}&#39;, (20, 70), cv2.FONT_HERSHEY_PLAIN, 3, colour, 1)<br>        cv2.putText(img, f&#39;Left EyeCounter: {left_eye_counter}&#39;, (20, h // 2), cv2.FONT_HERSHEY_PLAIN, 1, colour, 1)<br>        cv2.putText(img, f&#39;Right EyeCounter: {right_eye_counter}&#39;, (20, h // 2 + 50), cv2.FONT_HERSHEY_PLAIN, 1, colour,<br>                    1)<br>        cv2.imshow(&quot;Image&quot;, img)<br>        key = cv2.waitKey(1)<br>        if key == ord(&#39;q&#39;):<br>            break<br>    cap.release()<br>    cv2.destroyAllWindows()</pre><h3>Abschließende Gedanken</h3><p>Dieses Projekt half mir, Gesichtsmerkmale und die Mathematik hinter der Augenerkennung mit EAR zu verstehen. Es hat Spaß gemacht, eine einfache Idee in ein funktionierendes Echtzeit-Tool zu verwandeln, und es hat meine Kenntnisse in OpenCV und MediaPipe vertieft.</p><p>Wenn du neugierig bist, was du sonst noch damit machen kannst, kannst du das:</p><ul><li>Blinkdauer verfolgen</li><li>Schätzung des Ermüdungsgrads hinzufügen</li><li>Visualisierung von Blinzelmustern im Zeitverlauf</li><li>Erweitern Sie es für die Arbeit auf dem Handy oder im Web</li></ul><p>Fühlen Sie sich frei, das Projekt auf <a href="https://github.com/MertAkguel/EyeCounter">GitHub</a> zu forken und es selbst auszuprobieren!</p><blockquote>Vielen Dank fürs Lesen! Wenn dir dieser Beitrag gefallen hat oder du Fragen hast, lass es mich in den Kommentaren wissen 😊.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffa5e2cc8f44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Which Eye Do You Blink More? I Built a Python Tool to Find Out]]></title>
            <link>https://medium.com/@Mert.A/which-eye-do-you-blink-more-i-built-a-python-tool-to-find-out-fedd630d2363?source=rss-323545448d05------2</link>
            <guid isPermaLink="false">https://medium.com/p/fedd630d2363</guid>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[pygame]]></category>
            <category><![CDATA[mediapipe]]></category>
            <dc:creator><![CDATA[Mert]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 22:01:39 GMT</pubDate>
            <atom:updated>2025-04-12T22:01:39.376Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered if you blink more with your left or right eye? As a computer vision enthusiast, I decided to answer this question with a fun project that uses OpenCV and MediaPipe to track and count how often each eye is closed. This blog will walk you through the whole process step by step, explain the code, and show you how to build this yourself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*3xshIkBYM2JCCuc3MUFBoQ.gif" /><figcaption>Demo of Counting the Eye Blinker</figcaption></figure><h3>Motivation</h3><p>The idea came from reading about blink detection methods in fatigue studies. I came across a method that uses the Eye Aspect Ratio (EAR) to detect eye closure and thought it would be interesting to count blinks per eye. While blink detection is typically used in driver alert systems or medical monitoring, I just wanted to experiment and learn more about real-time facial landmark tracking.</p><h4>Step 1: Install the required libraries</h4><pre>pip install opencv-python mediapipe pygame numpy</pre><h4>Step 2: Import the libraries</h4><p>In two files, we’ll use these libraries:</p><ul><li>cv2 (OpenCV) for camera and image processing</li><li>mediapipe for facial landmark detection</li><li>pygame to play a sound when a blink is detected</li><li>numpy for distance calculation</li></ul><h4>Step 3: Create the FaceMeshModule (Facial Landmarks Detection)</h4><p>To detect facial landmarks and extract the points around the eyes, we’ll use MediaPipe’s FaceMesh model.</p><pre># File: FaceMeshModule.py<br>import cv2<br>import mediapipe as mp<br><br>GREEN = (0, 255, 0)  # color used for drawing points<br><br>class FaceMeshDetector:<br>    def __init__(self, static_image_mode=False, max_num_faces=1, refine_landmarks=False, min_detection_con=0.5,<br>                 min_tracking_con=0.5):<br>        # Initialize FaceMesh with selected options<br>        self.mpFaceMesh = mp.solutions.face_mesh<br>        self.faceMesh = self.mpFaceMesh.FaceMesh(static_image_mode, max_num_faces, refine_landmarks,<br>                                                 min_detection_con, min_tracking_con)<br><br>        # Coordinates for the 6 key points around each eye<br>        self.LEFT_IRIS = [362, 385, 387, 263, 373, 380]<br>        self.RIGHT_IRIS = [33, 160, 158, 133, 153, 144]<br>        self.BOTH_IRISES = self.LEFT_IRIS + self.RIGHT_IRIS<br><br>    def findMeshIrises(self, img, draw=True, color=GREEN):<br>        # Convert the BGR image to RGB<br>        img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)<br>        # Process the image to detect facial landmarks<br>        results = self.faceMesh.process(img_rgb)<br>        eye_landmarks = []<br>        faces = []<br>        if results.multi_face_landmarks:<br>            for faceLms in results.multi_face_landmarks:<br>                eye_landmarks = []<br>                face = []<br>                for i, lm in enumerate(faceLms.landmark):<br>                    if i in self.BOTH_IRISES:<br>                        h, w, _ = img.shape<br>                        x, y = int(lm.x * w), int(lm.y * h)<br>                        eye_landmarks.append((x, y))<br>                        if draw:<br>                            cv2.circle(img, (x, y), 1, color, -1)<br>                        face.append([x, y])<br>                faces.append(face)<br><br>        return img, faces, eye_landmarks</pre><h4>Step 4: Calculate Eye Aspect Ratio (EAR)</h4><p>To determine if the eye is closed, we calculate the Eye Aspect Ratio using the Euclidean distance between specific eye landmarks.</p><pre># Calculate distance between two 2D points<br>def get_distance(point1, point2):<br>    distance = []<br>    for p1, p2 in zip(point1, point2):<br>        distance.append((p2 - p1) ** 2)<br>    return np.sqrt(np.sum(distance))<br><br># Calculate Eye Aspect Ratio using 6 key eye points<br>def get_eye_aspect_ratio(p1, p2, p3, p4, p5, p6):<br>    # EAR formula: (||p2 - p6|| + ||p3 - p5||) / (2 * ||p1 - p4||)<br>    distance_p2_6 = get_distance(p2, p6)<br>    distance_p3_5 = get_distance(p3, p5)<br>    distance_p1_4 = get_distance(p1, p4)<br>    ear = (distance_p2_6 + distance_p3_5) / (2 * distance_p1_4)<br>    return ear</pre><h4>Step 5: Blink Detection and Counter</h4><p>The main loop reads from the webcam, detects landmarks, calculates the EAR, and counts when an eye closes below a threshold (0.15).</p><pre># File: Eyeblinker.py<br>import cv2<br>import numpy as np<br>import time<br>from FaceMeshModule import FaceMeshDetector<br>import pygame<br><br>pygame.init()<br># # you can download it here: https://pixabay.com/sound-effects/click-124467/<br>click_sound = pygame.mixer.Sound(r&quot;ThePathToTheSound&quot;)<br><br>colour = (0, 255, 0)<br><br>if __name__ == &quot;__main__&quot;:<br>    cap = cv2.VideoCapture(0)  # Start webcam<br>    p_time = 0  # For FPS calculation<br>    detector = FaceMeshDetector(refine_landmarks=True)<br><br>    left_eye_counter = 0<br>    right_eye_counter = 0<br>    left_eye_opened = True<br>    right_eye_opened = True<br><br>    while True:<br>        success, img = cap.read()<br>        h, w, _ = img.shape<br><br>        c_time = time.time()<br>        fps = 1 / (c_time - p_time)<br>        p_time = c_time<br><br>        try:<br>            # Detect eye landmarks<br>            img, faces, eye_landmarks = detector.findMeshIrises(img, draw=True, color=colour)<br>            left_p = eye_landmarks[6:]   # Left eye landmarks<br>            right_p = eye_landmarks[:6]  # Right eye landmarks<br><br>            # Calculate EAR for both eyes<br>            left_eye_ear = get_eye_aspect_ratio(left_p[1], left_p[4], left_p[5], left_p[0], left_p[2], left_p[3])<br>            right_eye_ear = get_eye_aspect_ratio(right_p[0], right_p[5], right_p[4], right_p[1], right_p[3], right_p[2])<br><br>            # If EAR is below threshold, register blink only once while eye is closed<br>            if left_eye_ear &lt; 0.15 and left_eye_opened:<br>                left_eye_counter += 1<br>                left_eye_opened = False<br>                pygame.mixer.Sound.play(click_sound)<br><br>            if left_eye_ear &gt; 0.15:<br>                left_eye_opened = True<br><br>            if right_eye_ear &lt; 0.15 and right_eye_opened:<br>                right_eye_counter += 1<br>                right_eye_opened = False<br><br>            if right_eye_ear &gt; 0.15:<br>                right_eye_opened = True<br><br>        except Exception:<br>            pass<br><br>        # Show results on screen<br>        cv2.putText(img, f&#39;FPS: {int(fps)}&#39;, (20, 70), cv2.FONT_HERSHEY_PLAIN, 3, colour, 1)<br>        cv2.putText(img, f&#39;Left EyeCounter: {left_eye_counter}&#39;, (20, h // 2), cv2.FONT_HERSHEY_PLAIN, 1, colour, 1)<br>        cv2.putText(img, f&#39;Right EyeCounter: {right_eye_counter}&#39;, (20, h // 2 + 50), cv2.FONT_HERSHEY_PLAIN, 1, colour, 1)<br><br>        cv2.imshow(&quot;Image&quot;, img)<br><br>        # Press &#39;q&#39; to quit<br>        key = cv2.waitKey(1)<br>        if key == ord(&#39;q&#39;):<br>            break<br>    cap.release()<br>    cv2.destroyAllWindows()</pre><h3>Full Source Code</h3><p>For your convenience, here’s the full code for both files:</p><h4>FaceMeshModule.py</h4><pre>import cv2<br>import mediapipe as mp<br><br>GREEN = (0, 255, 0)<br><br><br>class FaceMeshDetector:<br><br>    def __init__(self, static_image_mode=False, max_num_faces=1, refine_landmarks=False, min_detection_con=0.5,<br>                 min_tracking_con=0.5):<br>        self.static_image_mode = static_image_mode<br>        self.max_num_faces = max_num_faces<br>        self.refine_landmarks = refine_landmarks<br>        self.min_detection_con = min_detection_con<br>        self.min_tracking_con = min_tracking_con<br><br>        self.mpDraw = mp.solutions.drawing_utils<br>        self.mpFaceMesh = mp.solutions.face_mesh<br>        self.faceMesh = self.mpFaceMesh.FaceMesh(self.static_image_mode, self.max_num_faces, self.refine_landmarks,<br>                                                 self.min_detection_con, self.min_tracking_con)<br><br>        # coordiantes we need for EAR, for more info see this paper:<br>        # https://vision.fe.uni-lj.si/cvww2016/proceedings/papers/05.pdf<br>        self.LEFT_IRIS = [362, 385, 387, 263, 373, 380]<br>        self.RIGHT_IRIS = [33, 160, 158, 133, 153, 144]<br><br>        self.BOTH_IRISES = self.LEFT_IRIS + self.RIGHT_IRIS<br><br>    def findMeshIrises(self, img, draw=True, color=GREEN):<br>        img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)<br>        results = self.faceMesh.process(img_rgb)<br>        eye_landmarks = []<br>        faces = []<br>        if results.multi_face_landmarks:<br>            for faceLms in results.multi_face_landmarks:<br>                eye_landmarks = []<br>                face = []<br>                for i, lm in enumerate(faceLms.landmark):<br>                    if i in self.BOTH_IRISES:<br>                        h, w, ic = img.shape<br>                        x, y = int(lm.x * w), int(lm.y * h)<br>                        eye_landmarks.append((x, y))<br>                        # cv2.putText(img, str(id), (x, y), cv2.FONT_HERSHEY_PLAIN, 1, GREEN, 1)<br>                        if draw:<br>                            cv2.circle(img, (x, y), 1, color, -1)<br>                        face.append([x, y])<br><br>                faces.append(face)<br><br>        return img, faces, eye_landmarks</pre><h4>Eyeblinker.py</h4><pre>import cv2<br>import numpy as np<br>import time<br>from FaceMeshModule import FaceMeshDetector<br>import pygame<br><br>pygame.init()<br><br># you can download it here: https://pixabay.com/sound-effects/click-124467/<br>click_sound = pygame.mixer.Sound(<br>    r&quot;C:\Users\Kleve\Downloads\click-124467.mp3&quot;)<br><br>GREEN = (0, 255, 0)<br>BLUE = (255, 0, 0)<br>RED = (0, 0, 255)<br>colour = GREEN<br><br><br>def get_distance(point1, point2):<br>    &quot;&quot;&quot;<br>    calculate Euclidean distance between point1 and point2<br><br>    :param point1: (x, y, z) landmark of point1<br>    :param point2: (x, y, z) landmark of point2<br>    :return: Euclidean distance between point1 and point2<br>    &quot;&quot;&quot;<br><br>    distance = []<br>    for p1, p2 in zip(point1, point2):<br>        distance.append((p2 - p1) ** 2)<br>    return np.sqrt(np.sum(distance))<br><br><br>def get_eye_aspect_ratio(p1, p2, p3, p4, p5, p6):<br>    distance_p2_6 = get_distance(p2, p6)<br>    distance_p3_5 = get_distance(p3, p5)<br>    distance_p1_4 = get_distance(p1, p4)<br><br>    ear = (distance_p2_6 + distance_p3_5) / (2 * distance_p1_4)<br><br>    return ear<br><br><br>if __name__ == &quot;__main__&quot;:<br>    cap = cv2.VideoCapture(0)<br>    pTime = 0<br>    detector = FaceMeshDetector(refine_landmarks=True)<br><br>    left_eye_counter = 0<br>    right_eye_counter = 0<br><br>    left_eye_opened = True<br>    right_eye_opened = True<br><br>    while True:<br>        success, img = cap.read()<br>        h, w, _ = img.shape<br><br>        cTime = time.time()<br>        fps = 1 / (cTime - pTime)<br>        pTime = cTime<br><br>        try:<br>            img, faces, eye_landmarks = detector.findMeshIrises(img, draw=True, color=colour)<br>            left_p = eye_landmarks[6:]<br>            right_p = eye_landmarks[:6]<br><br>            left_eye_ear = get_eye_aspect_ratio(left_p[1], left_p[4], left_p[5],<br>                                                left_p[0], left_p[2], left_p[3])<br>            right_eye_ear = get_eye_aspect_ratio(right_p[0], right_p[5], right_p[4],<br>                                                 right_p[1], right_p[3], right_p[2])<br>            avg_ear = (left_eye_ear + right_eye_ear) / 2.0<br><br>            if left_eye_ear &lt; 0.15 and left_eye_opened:<br>                left_eye_counter += 1<br>                left_eye_opened = False<br>                pygame.mixer.Sound.play(click_sound)<br><br>            if left_eye_ear &gt; 0.15:<br>                left_eye_opened = True<br><br>            if right_eye_ear &lt; 0.15 and right_eye_opened:<br>                right_eye_counter += 1<br>                right_eye_opened = False<br>            if right_eye_ear &gt; 0.15:<br>                right_eye_opened = True<br><br>        except Exception:<br>            pass<br><br>        cv2.putText(img, f&#39;FPS: {int(fps)}&#39;, (20, 70), cv2.FONT_HERSHEY_PLAIN, 3, colour, 1)<br>        cv2.putText(img, f&#39;Left EyeCounter: {left_eye_counter}&#39;, (20, h // 2), cv2.FONT_HERSHEY_PLAIN, 1, colour, 1)<br>        cv2.putText(img, f&#39;Right EyeCounter: {right_eye_counter}&#39;, (20, h // 2 + 50), cv2.FONT_HERSHEY_PLAIN, 1, colour,<br>                    1)<br><br>        cv2.imshow(&quot;Image&quot;, img)<br><br>        key = cv2.waitKey(1)<br>        if key == ord(&#39;q&#39;):<br>            break<br><br>    cap.release()<br>    cv2.destroyAllWindows()</pre><h3>Final Thoughts</h3><p>This project helped me understand facial landmarks and the math behind eye detection using EAR. It was fun to turn a simple idea into a working real-time tool, and it deepened my skills in OpenCV and MediaPipe.</p><p>If you’re curious about what else you can do with this, you could:</p><ul><li>Track blink duration</li><li>Add fatigue level estimation</li><li>Visualize blink patterns over time</li><li>Extend it to work on mobile or web</li></ul><p>Feel free to fork the project on <a href="https://github.com/MertAkguel/EyeCounter">GitHub</a> and try it out for yourself!</p><blockquote><em>Thanks for reading! If you liked this post or have questions, let me know in the comments. 😊</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fedd630d2363" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Streamlit Web App for Object Detection and Face Blurring with YOLOv8 and Deepface]]></title>
            <link>https://medium.com/@Mert.A/building-a-streamlit-web-app-for-object-detection-and-face-blurring-with-yolov8-and-deepface-43c1e649fecf?source=rss-323545448d05------2</link>
            <guid isPermaLink="false">https://medium.com/p/43c1e649fecf</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[segmentation]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[portfolio]]></category>
            <dc:creator><![CDATA[Mert]]></dc:creator>
            <pubDate>Wed, 09 Apr 2025 11:01:39 GMT</pubDate>
            <atom:updated>2025-04-09T11:01:39.861Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VhhnnX1u2iuKXEjAmCCGGw.gif" /><figcaption>Application Demo</figcaption></figure><h3>Introduction</h3><p>In this project, I developed an interactive web application that integrates real-time object detection and face blurring functionalities using <a href="https://docs.ultralytics.com/guides/streamlit-live-inference/">YOLOv8</a> and <a href="https://streamlit.io/">Streamlit</a>. The application allows users to upload images or videos, perform object detection, segmentation, and apply face blurring techniques. You can experience the live application here: <a href="https://yolowebsite.streamlit.app/">YOLO Streamlit App</a>.</p><p>This blog post serves as both a showcase of the project and a partial tutorial, providing insights into the development process, code structure, and key implementations.</p><h3>Project Structure</h3><p>The project is organized into the following directories and files:</p><pre>CV_website/<br>├── modules/                 # Core logic<br>│   ├── detection_utils.py<br>│   ├── face_blur_utils.py<br>│   └── media_handlers.py<br>│<br>├── streamlit_pages/         # Streamlit UI logic<br>│   ├── main_page.py<br>│   ├── blur_faces_page.py<br>│   ├── object_detection_page.py<br>│   └── segmentation_page.py<br>│<br>├── uploaded_data/           <br>│<br>├── main.py                  # Entry point<br>├── requirements.txt<br>├── README.md<br>├── BlurFace.py              # Custom face blurring logic<br>├── help_functions.py        # Additional utility functions<br>└── ...</pre><h4>Core Modules (modules/)</h4><ul><li><strong>detection_utils.py</strong>: Contains functions for object detection and segmentation.</li><li><strong>face_blur_utils.py</strong>: Implements face detection and blurring techniques using Intersection over Union.</li><li><strong>media_handlers.py</strong>: Handles media processing tasks such as reading and writing images/videos.</li></ul><h4>Streamlit Pages (streamlit_pages/)</h4><ul><li><strong>main_page.py</strong>: The main landing page of the application.</li><li><strong>blur_faces_page.py</strong>: Interface for the face blurring functionality.</li><li><strong>object_detection_page.py</strong>: Interface for object detection.</li><li><strong>segmentation_page.py</strong>: Interface for image segmentation.</li></ul><h3>Running the Application</h3><p>To run the application locally, follow these steps:</p><p><strong>Clone the repository</strong>:</p><pre>git clone https://github.com/MertAkguel/CV_website.git</pre><p><strong>Install the required dependencies</strong>:</p><pre>pip install -r requirements.txt</pre><p><strong>Launch the Streamlit application</strong>:</p><pre>streamlit run main.py</pre><p>After running the above commands, the application will open in your default web browser, allowing you to interact with the various features.</p><h3>Conclusion</h3><p>This project demonstrates the integration of YOLOv8 with Streamlit to create a web application capable of real-time object detection, image segmentation, and face blurring. The modular structure ensures maintainability and scalability, while the user-friendly interface makes these advanced computer vision techniques accessible to users without a technical background.</p><p>The complete source code is available on my <a href="https://github.com/MertAkguel/CV_website/tree/main"><strong>[GitHub repository]</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43c1e649fecf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Erstellung einer Streamlit Web App für Objekterkennung und Gesichtsunschärfe mit YOLOv8 und Deep]]></title>
            <link>https://medium.com/@Mert.A/erstellung-einer-streamlit-web-app-f%C3%BCr-objekterkennung-und-gesichtsunsch%C3%A4rfe-mit-yolov8-und-deep-02d639466f0e?source=rss-323545448d05------2</link>
            <guid isPermaLink="false">https://medium.com/p/02d639466f0e</guid>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[portfolio]]></category>
            <category><![CDATA[segmentation]]></category>
            <dc:creator><![CDATA[Mert]]></dc:creator>
            <pubDate>Wed, 09 Apr 2025 11:01:39 GMT</pubDate>
            <atom:updated>2025-04-09T11:01:39.667Z</atom:updated>
            <content:encoded><![CDATA[<h3>Erstellung einer Streamlit Web App für Objekterkennung und Gesichtsunschärfe mit YOLOv8 und DeepFace</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VhhnnX1u2iuKXEjAmCCGGw.gif" /><figcaption>Application Demo</figcaption></figure><h3>Einleitung</h3><p>In diesem Projekt habe ich eine interaktive Webanwendung entwickelt, die mit Hilfe von YOLOv8 und Streamlit Funktionen zur Objekterkennung und Gesichtsunschärfe in Echtzeit integriert. Die Anwendung ermöglicht es den Nutzern, Bilder oder Videos hochzuladen, die Objekterkennung und -segmentierung durchzuführen und Techniken zur Gesichtsverwischung anzuwenden. Sie können die Anwendung hier live erleben: YOLO Streamlit Anwendung.</p><p>Dieser Blog-Beitrag dient sowohl als Showcase des Projekts als auch als teilweises Tutorial, das Einblicke in den Entwicklungsprozess, die Codestruktur und die wichtigsten Implementierungen bietet.</p><h3>Projekt Struktur</h3><p>Das Projekt ist in die folgenden Verzeichnisse und Dateien unterteilt:</p><pre>CV_website/<br>├── modules/                 # Core logic<br>│   ├── detection_utils.py<br>│   ├── face_blur_utils.py<br>│   └── media_handlers.py<br>│<br>├── streamlit_pages/         # Streamlit UI logic<br>│   ├── main_page.py<br>│   ├── blur_faces_page.py<br>│   ├── object_detection_page.py<br>│   └── segmentation_page.py<br>│<br>├── uploaded_data/           <br>│<br>├── main.py                  # Entry point<br>├── requirements.txt<br>├── README.md<br>├── BlurFace.py              # Custom face blurring logic<br>├── help_functions.py        # Additional utility functions<br>└── ...</pre><h4>Kernmodule (modules/)</h4><ul><li><strong>detection_utils.py</strong>: Enthält Funktionen zur Objekterkennung und Segmentierung.</li><li><strong>face_blur_utils.py</strong>: Implementiert Gesichtserkennung und Unschärfetechniken mit Intersection over Union.</li><li><strong>media_handlers.py</strong>: Erledigt Medienverarbeitungsaufgaben wie das Lesen und Schreiben von Bildern/Videos.</li></ul><h4>Streamlit Seiten (streamlit_pages/)</h4><ul><li><strong>main_page.py</strong>: Die Hauptzielseite der Anwendung.</li><li><strong>blur_faces_page.py</strong>: Schnittstelle für die Gesichtsverwischungsfunktion.</li><li><strong>object_detection_page.py</strong>: Schnittstelle für die Objekterkennung.</li><li><strong>segmentation_page.py</strong>: Schnittstelle für die Bildsegmentierung.</li></ul><h3>Ausführen der Anwendung</h3><p>Um die Anwendung lokal auszuführen, gehen Sie wie folgt vor:</p><p><strong>Klone das Repository:</strong></p><pre>git clone https://github.com/MertAkguel/CV_website.git</pre><p><strong>Installiere die erforderliche Abhängigkeiten:</strong></p><pre>pip install -r requirements.txt</pre><p>Starte die Streamlit-Anwendung:</p><pre>streamlit run main.py</pre><p>Nachdem die oben genannten Befehle ausgeführt wurden, wird die Anwendung in Ihrem Standard-Webbrowser geöffnet, so dass Sie mit den verschiedenen Funktionen interagieren können.</p><h3>Fazit</h3><p>Dieses Projekt demonstriert die Integration von YOLOv8 mit Streamlit, um eine Webanwendung zu erstellen, die Objekterkennung, Bildsegmentierung und Gesichtsunschärfe in Echtzeit ermöglicht. Die modulare Struktur gewährleistet Wartbarkeit und Skalierbarkeit, während die benutzerfreundliche Schnittstelle diese fortschrittlichen Computer-Vision-Techniken für Benutzer ohne technischen Hintergrund zugänglich macht.</p><p>Der vollständige Quellcode ist auf meiner Website verfügbar <a href="https://github.com/MertAkguel/CV_website/tree/main"><strong>[GitHub repository]</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02d639466f0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use YOLOE for Segmentation]]></title>
            <link>https://medium.com/@Mert.A/how-to-use-yoloe-for-segmentation-5790fb609aff?source=rss-323545448d05------2</link>
            <guid isPermaLink="false">https://medium.com/p/5790fb609aff</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[segmentation]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Mert]]></dc:creator>
            <pubDate>Mon, 31 Mar 2025 05:02:10 GMT</pubDate>
            <atom:updated>2025-03-31T05:02:10.215Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*xCG6SyjtcjCeVQHFqY7gww.png" /></figure><h3>Introduction</h3><p>​In the rapidly evolving field of computer vision, object detection and segmentation have traditionally been constrained by models limited to predefined categories, hindering adaptability in open scenarios. Enter <strong>YOLOE</strong> — <em>You Only Look Once for Everything</em> — a groundbreaking model that redefines real-time object detection and segmentation by embracing an open-world paradigm.​</p><p>Unlike its predecessors, YOLOE is designed to detect and segment objects beyond a fixed set of classes, accommodating diverse prompts such as text descriptions, visual cues, or even operating without explicit prompts. This versatility is achieved through innovative components:​</p><ul><li><strong>Re-parameterizable Region-Text Alignment (RepRTA):</strong> Enhances text-prompted detection by refining pretrained textual embeddings via a lightweight auxiliary network, improving visual-textual alignment without adding inference overhead.​<a href="https://huggingface.co/jameslahm/yoloe?utm_source=chatgpt.com">Hugging Face+1arXiv+1</a></li><li><strong>Semantic-Activated Visual Prompt Encoder (SAVPE):</strong> Facilitates visual-prompted detection by encoding reference images into embeddings, allowing the model to detect visually similar objects effectively.​</li><li><strong>Lazy Region-Prompt Contrast (LRPC):</strong> Enables prompt-free detection by utilizing a built-in large vocabulary and specialized embeddings to identify all objects, eliminating the need for external language models.​</li></ul><p>When comparing YOLOE to <a href="https://medium.com/@Mert.A/how-to-use-yolo-world-for-object-detection-27bf82291733"><strong>YOLO-World</strong></a>, another open-set object detection model, YOLOE demonstrates notable advantages. For instance, on the LVIS dataset, YOLOE-v8-S surpasses YOLO-Worldv2-S by 3.5 AP while achieving 1.4× faster inference speeds and requiring three times less training resources. This efficiency makes YOLOE particularly suitable for real-time applications where computational resources are limited.</p><h3>How to use YOLOE</h3><h4>Step 1: Installing the libraries</h4><pre>pip install ultralytics</pre><h4>Step 2: Importing libraries</h4><pre>from ultralytics import YOLOE</pre><h4>Step 3: Choose your model</h4><pre>model = YOLOE(&quot;yoloe-11l-seg.pt&quot;)</pre><p>On this <a href="https://docs.ultralytics.com/de/models/yoloe/">website</a>, you can compare different models and weigh up their respective advantages and disadvantages. In this case we have chosen yoloe-11l-seg.pt</p><h4>Step 4: Detecting Objects in Images with YOLOE</h4><pre>names = [&quot;person&quot;, &quot;bus&quot;, &quot;car&quot;, &quot;truck&quot;, &quot;lights&quot;, &quot;window&quot;, &quot;house&quot;]<br>model.set_classes(names, model.get_text_pe(names))</pre><pre>results = model.predict(&#39;YourImagePath&#39;)</pre><p>If you want to detect specific classes, you can just write any class in the list of model.set_classes function.</p><h4>Step 5: Save and Plot the result Image</h4><pre># Show results<br>results[0].show()</pre><h4>The whole code</h4><pre>from ultralytics import YOLOE<br><br>model = YOLOE(&quot;yoloe-11l-seg.pt&quot;)<br><br>path = &quot;YourImagePath&quot;<br>names = [&quot;person&quot;, &quot;bus&quot;, &quot;car&quot;, &quot;truck&quot;, &quot;lights&quot;, &quot;window&quot;, &quot;house&quot;]<br>model.set_classes(names, model.get_text_pe(names))<br><br>results = model.predict(path)<br><br>print(results)<br><br># Show results<br>results[0].show()</pre><h3>Conclusion</h3><p>In this tutorial we have learned how to detect objects with YOLOE in images. If you found this code helpful, please clap your hands and comment on this post! I would also love for you to follow me to learn more about Data Science and other related topics. Thanks for reading!</p><h3>References</h3><p><strong>Paper of YOLOE:</strong> <a href="https://arxiv.org/abs/2503.07465">https://arxiv.org/pdf/2401.17270v2.pdf</a><br><strong>Github-Page of YOLOE:</strong> <a href="https://github.com/Gaurav14cs17/YOLOE">https://github.com/AILab-CVC/YOLO-World</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5790fb609aff" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>