<?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 Tamás Rózsahegyi on Medium]]></title>
        <description><![CDATA[Stories by Tamás Rózsahegyi on Medium]]></description>
        <link>https://medium.com/@rozsit?source=rss-7f595eb81d3b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*juKrf0z1aamaECvu</url>
            <title>Stories by Tamás Rózsahegyi on Medium</title>
            <link>https://medium.com/@rozsit?source=rss-7f595eb81d3b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:54:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rozsit/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[Automating PCB defect detection: a deep dive into Computer Vision with YOLO26m]]></title>
            <link>https://medium.com/@rozsit/automating-pcb-defect-detection-a-deep-dive-into-computer-vision-with-yolo26m-4ea3a00a2ce8?source=rss-7f595eb81d3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ea3a00a2ce8</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[manufacturing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Tamás Rózsahegyi]]></dc:creator>
            <pubDate>Sat, 07 Mar 2026 08:42:24 GMT</pubDate>
            <atom:updated>2026-03-07T08:42:24.944Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wnyA-HDb-P3o6V5SS4s93Q.png" /></figure><p><strong>How a robust data strategy and modern Deep Learning can revolutionize industrial quality control.</strong></p><p>In modern manufacturing, quality control is no longer just an option; it is the key to competitiveness. Recently, I had the opportunity to dive into an industrial Computer Vision project aimed at automating the Automated Optical Inspection (AOI) of Printed Circuit Boards (PCBs).</p><h3>The Challenge</h3><p>During PCB manufacturing, microscopic defects can occur, such as “mouse bites” (thinning of the conductive trace), “spurs” (copper residue), or critical short circuits. Manual inspection of these issues is slow and highly subjective. Furthermore, traditional rule-based image processing algorithms often fail due to the reflection of copper surfaces or complex geometric patterns.</p><h3>Why Does This Matter?</h3><p>At the end of the day, what is the point of spending hours cleaning data and training a neural network? The answer is highly practical. Today, PCBs are the heart of almost every device we use: our smartwatches, washing machines, car braking systems, and life-saving medical equipment. A single microscopic short circuit on the assembly line can lead to severe malfunctions, expensive warranty recalls, or even dangerous accidents later on.</p><p>During traditional visual inspection, factory operators must hunch over magnifiers or screens for hours, performing monotonous checks. We are only human: by the eighth hour, our eyes get tired, and our attention inevitably drops.</p><p>A machine learning system based on the YOLO26m architecture does not take away anyone’s job. Rather, it functions as a tireless “second pair of eyes” that scans the board in a fraction of a second without blinking, highlighting only the suspicious areas. This frees up human expertise, allowing operators to focus on making critical decisions instead of looking for a needle in a haystack. Furthermore, we can save a massive amount of electronic waste (e-waste) by catching defects early on the assembly line before expensive components are soldered onto a faulty raw board.</p><p>For me, this project was not just about lines of code and impressive metrics. It was about the realization that Artificial Intelligence is no longer distant laboratory magic or an intangible hype, but a very tangible tool that can make everyday industry safer, more sustainable, and more human-centric.</p><h3>The Technical Roadmap: Step-by-Step</h3><p>Applying object detection in an industrial setting presents major challenges, primarily dealing with tiny objects and variable environments. Here is the workflow I used to build a robust PCB defect detector.</p><h4>Phase 1: Data Preparation and XML-YOLO Conversion</h4><p>Industrial datasets often arrive in Pascal VOC format. However, the YOLO model requires normalized coordinates. My approach was to strictly filter out automatically generated, poorly rotated augmented images that would ruin the model’s convergence, relying solely on a clean, manually validated corpus. (all cells in Google Colab)</p><pre>!pip install -q --upgrade kagglehub<br><br>import kagglehub<br>kagglehub.login()<br><br># Download the PCB dataset using the modern method<br>dataset_path = kagglehub.dataset_download(&quot;nakul8820/pcb-dataset-with-augmentations&quot;)<br><br><br># Print the exact local directory where the files are stored<br>print(f&quot;Dataset downloaded successfully to: {dataset_path}&quot;)</pre><pre>import os<br>import shutil<br><br><br># Define the hidden source path where kagglehub saved the files<br>source_path = &#39;/root/.cache/kagglehub/datasets/nakul8820/pcb-dataset-with-augmentations/versions/2&#39;<br><br><br># Define the target path in the visible Colab working directory<br>target_path = &#39;/content/pcb_dataset&#39;<br><br><br># Check if the target directory already exists to prevent errors<br>if not os.path.exists(target_path):<br><br>    # Move the entire directory tree to the visible location<br>    shutil.move(source_path, target_path)<br><br>    # Print a success message confirming the move<br>    print(f&quot;Dataset successfully moved to: {target_path}&quot;)<br><br>else:<br><br>    # Print a message if it has already been moved<br>    print(f&quot;The dataset is already located at: {target_path}&quot;)<br><br><br># Verify the move by listing the contents of the new directory<br>print(&quot;Contents of the dataset directory:&quot;)<br><br>for item in os.listdir(target_path):<br>    print(f&quot;- {item}&quot;)</pre><pre>import os<br>import shutil<br><br># Define the base path according to the screenshots<br>base_path = &#39;/content/pcb_dataset/PCB_DATASET/PCB_DATASET&#39;<br><br># List of directories to remove<br>dirs_to_remove = [&#39;PCB_Mixed_Samples&#39;, &#39;PCB_USED&#39;, &#39;rotation&#39;]<br><br>for dir_name in dirs_to_remove:<br>    target_dir = os.path.join(base_path, dir_name)<br><br>    # Check if the directory exists before attempting to delete<br>    if os.path.exists(target_dir):<br>        shutil.rmtree(target_dir)<br>        print(f&quot;Successfully deleted: {target_dir}&quot;)<br>    else:<br>        print(f&quot;Directory not found, already deleted or incorrect path: {target_dir}&quot;)<br><br>print(&quot;Cleanup process finished.&quot;)</pre><pre>import os<br>import glob<br>import shutil<br>import random<br>import xml.etree.ElementTree as ET<br>import yaml</pre><pre>def create_yolo_dataset_clean():<br>    # Define source and target directories<br>    source_base = &#39;/content/pcb_dataset/PCB_DATASET/PCB_DATASET&#39;<br>    source_images = os.path.join(source_base, &#39;images&#39;)<br>    source_xmls = os.path.join(source_base, &#39;Annotations&#39;)<br><br>    yolo_base = &#39;/content/yolo_pcb&#39;<br><br>    # Define the exact classes based on the XML files<br>    classes = [&#39;missing_hole&#39;, &#39;mouse_bite&#39;, &#39;open_circuit&#39;, &#39;short&#39;, &#39;spur&#39;, &#39;spurious_copper&#39;]<br><br>    # Create target YOLO directory structure<br>    dirs = {<br>        &#39;img_train&#39;: os.path.join(yolo_base, &#39;images/train&#39;),<br>        &#39;img_val&#39;: os.path.join(yolo_base, &#39;images/val&#39;),<br>        &#39;lbl_train&#39;: os.path.join(yolo_base, &#39;labels/train&#39;),<br>        &#39;lbl_val&#39;: os.path.join(yolo_base, &#39;labels/val&#39;)<br>    }<br><br>    for path in dirs.values():<br>        os.makedirs(path, exist_ok=True)<br><br>    print(&quot;YOLO directory structure created.&quot;)<br><br>    # Find XML files but explicitly IGNORE any paths containing &#39;mixed&#39;<br>    all_xml_files = glob.glob(os.path.join(source_xmls, &#39;**/*.xml&#39;), recursive=True)<br>    xml_files = [f for f in all_xml_files if &#39;mixed&#39; not in f.lower()]<br><br>    print(f&quot;Found {len(xml_files)} clean XML annotation files (ignored mixed folders).&quot;)<br><br>    dataset_pairs = []<br><br>    # Process each valid XML file<br>    for xml_file in xml_files:<br>        try:<br>            tree = ET.parse(xml_file)<br>            root = tree.getroot()<br><br>            size = root.find(&#39;size&#39;)<br>            if size is None:<br>                continue<br><br>            w = int(size.find(&#39;width&#39;).text)<br>            h = int(size.find(&#39;height&#39;).text)<br><br>            # Find the corresponding image file recursively<br>            base_name = os.path.basename(xml_file)<br>            img_name = base_name.replace(&#39;.xml&#39;, &#39;.jpg&#39;)<br><br>            # Search for the image in the source_images directory<br>            img_search_pattern = os.path.join(source_images, f&quot;**/{img_name}&quot;)<br>            img_matches = glob.glob(img_search_pattern, recursive=True)<br><br>            if not img_matches:<br>                continue<br><br>            img_path = img_matches[0]<br><br>            # Extract YOLO formatted labels<br>            yolo_labels = []<br>            for obj in root.iter(&#39;object&#39;):<br>                difficult = obj.find(&#39;difficult&#39;).text if obj.find(&#39;difficult&#39;) is not None else &#39;0&#39;<br>                cls_elem = obj.find(&#39;name&#39;)<br><br>                if cls_elem is None or cls_elem.text not in classes or int(difficult) == 1:<br>                    continue<br><br>                cls_id = classes.index(cls_elem.text)<br>                xmlbox = obj.find(&#39;bndbox&#39;)<br>                if xmlbox is None:<br>                    continue<br><br>                b = (float(xmlbox.find(&#39;xmin&#39;).text), float(xmlbox.find(&#39;xmax&#39;).text),<br>                     float(xmlbox.find(&#39;ymin&#39;).text), float(xmlbox.find(&#39;ymax&#39;).text))<br><br>                x_center = ((b[0] + b[1]) / 2.0) / w<br>                y_center = ((b[2] + b[3]) / 2.0) / h<br>                width = (b[1] - b[0]) / w<br>                height = (b[3] - b[2]) / h<br><br>                yolo_labels.append(f&quot;{cls_id} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}&quot;)<br><br>            if yolo_labels:<br>                dataset_pairs.append({<br>                    &#39;img_source&#39;: img_path,<br>                    &#39;base_name&#39;: base_name.replace(&#39;.xml&#39;, &#39;&#39;),<br>                    &#39;labels&#39;: yolo_labels<br>                })<br><br>        except Exception:<br>            # Silently pass any parsing errors to keep the output console clean<br>            pass<br><br>    print(f&quot;Successfully paired {len(dataset_pairs)} images with valid annotations.&quot;)<br><br>    # Shuffle and split the dataset (80% train, 20% validation)<br>    random.seed(42)<br>    random.shuffle(dataset_pairs)<br>    split_idx = int(len(dataset_pairs) * 0.8)<br><br>    train_data = dataset_pairs[:split_idx]<br>    val_data = dataset_pairs[split_idx:]<br><br>    print(f&quot;Splitting data: {len(train_data)} for training, {len(val_data)} for validation.&quot;)<br><br>    # Helper function to write files to the YOLO structure<br>    def save_split(data_subset, split_type):<br>        for item in data_subset:<br>            # Copy image<br>            img_dest = os.path.join(dirs[f&#39;img_{split_type}&#39;], f&quot;{item[&#39;base_name&#39;]}.jpg&quot;)<br>            shutil.copy(item[&#39;img_source&#39;], img_dest)<br><br>            # Write label text file<br>            txt_dest = os.path.join(dirs[f&#39;lbl_{split_type}&#39;], f&quot;{item[&#39;base_name&#39;]}.txt&quot;)<br>            with open(txt_dest, &#39;w&#39;) as f:<br>                f.write(&#39;\n&#39;.join(item[&#39;labels&#39;]) + &#39;\n&#39;)<br><br>    save_split(train_data, &#39;train&#39;)<br>    save_split(val_data, &#39;val&#39;)<br>    print(&quot;File copying and conversion completed.&quot;)<br><br>    # Generate the data.yaml file required for YOLO training<br>    yaml_content = {<br>        &#39;path&#39;: yolo_base,<br>        &#39;train&#39;: &#39;images/train&#39;,<br>        &#39;val&#39;: &#39;images/val&#39;,<br>        &#39;names&#39;: {i: name for i, name in enumerate(classes)}<br>    }<br><br>    yaml_path = os.path.join(yolo_base, &#39;data.yaml&#39;)<br>    with open(yaml_path, &#39;w&#39;) as f:<br>        yaml.dump(yaml_content, f, sort_keys=False)<br><br>    print(f&quot;Configuration file generated successfully at: {yaml_path}&quot;)<br>    print(&quot;Dataset is fully prepared for YOLO training!&quot;)<br><br># Execute the preparation<br>create_yolo_dataset_clean()</pre><h4>Phase 2: Advanced Training Strategy</h4><p>For the architecture, I chose YOLO26m (Medium). While Nano versions are faster, detecting microscopic copper residues requires the deeper feature-extracting capacity of the Medium model (approx. 21.7 million parameters).</p><p>Training was executed on an NVIDIA A100 GPU in the cloud.</p><pre>!pip install -q ultralytics<br><br>from ultralytics import YOLO<br>import os</pre><pre># Verify that the configuration file exists before starting<br>yaml_path = &#39;/content/yolo_pcb/data.yaml&#39;<br><br>if not os.path.exists(yaml_path):<br>    print(f&quot;Error: Configuration file not found at {yaml_path}&quot;)<br>else:<br>    print(&quot;Initializing the YOLO26 Medium model...&quot;)<br>    # Load the pre-trained Medium model<br>    model = YOLO(&#39;yolo26m.pt&#39;)<br><br>    print(&quot;Starting YOLO26m training on the local Colab storage...&quot;)<br>    print(&quot;Configuration: 300 epochs, patience=50, imgsz=1024, auto-batch (-1)&quot;)<br><br>    # Execute the training process<br>    results = model.train(<br>        data=yaml_path,<br>        epochs=300,<br>        patience=50,<br>        imgsz=1024,<br>        batch=-1,<br>        device=0,<br>        project=&#39;/content/pcb_training_runs&#39;,<br>        name=&#39;yolo26m_run1&#39;<br>    )<br><br>    print(&quot;Training completed successfully!&quot;)<br>    print(&quot;The best model weights are located at: /content/pcb_training_runs/yolo26m_run1/weights/best.pt&quot;)</pre><ul><li><strong>imgsz=1024</strong>: Maintaining a high resolution is critical. High-resolution images from industrial cameras should not be downscaled to 640, as critical information (like hairline cracks) will be lost during sampling.</li><li><strong>batch=-1</strong>: The <em>AutoBatch</em> feature dynamically tests GPU memory and sets the largest possible batch size (up to 60% VRAM saturation) for maximum throughput, preventing Out-Of-Memory errors.</li><li><strong>patience=50</strong>: <em>Early Stopping</em> ensures the process halts once validation loss stagnates. The model stopped at epoch 136, saving the optimal weights from epoch 86.</li></ul><p><strong>Validation Results:</strong></p><ul><li><strong>mAP50:</strong> 98.2% (Near-perfect detection of defect presence).</li><li><strong>mAP50–95:</strong> 0.580 (Strict, geometrically accurate bounding box alignment).</li></ul><pre>import shutil<br>import os<br>from google.colab import files<br><br># Define the exact directory where YOLO saved all training results<br>run_dir = &#39;/content/pcb_training_runs/yolo26m_run1&#39;<br>output_zip = &#39;/content/yolo26m_trained_model&#39;<br><br>if os.path.exists(run_dir):<br>    print(f&quot;Archiving the training results from {run_dir}...&quot;)<br>    # Create a zip file containing all weights, metrics, and plots<br>    shutil.make_archive(output_zip, &#39;zip&#39;, run_dir)<br>    print(f&quot;Archive created successfully: {output_zip}.zip&quot;)<br><br>    print(&quot;Starting download. Please wait for the browser prompt to appear...&quot;)<br>    # Trigger the download to your local machine<br>    files.download(output_zip + &#39;.zip&#39;)<br>else:<br>    print(f&quot;Error: The directory {run_dir} does not exist. Ensure training has finished.&quot;)</pre><h4>Phase 3: Local Inference and Fine-tuning</h4><p>After moving the trained best.pt model to a local Jupyter Lab environment, we set up a script for static image testing. To avoid OS-level extension duplication issues (e.g., .jpg vs .JPG), a Python set() is the cleanest approach.</p><pre>import glob<br>import random<br>from ultralytics import YOLO<br>import matplotlib.pyplot as plt<br>import cv2<br><br># Path to the best weights generated by your training<br>model_path = &#39;/content/pcb_training_runs/yolo26m_run1/weights/best.pt&#39;<br># Path to the validation images<br>val_images_dir = &#39;/content/yolo_pcb/images/val&#39;<br><br>try:<br>    # Load the custom trained YOLO26 Medium model<br>    model = YOLO(model_path)<br>    print(&quot;Model loaded successfully. Preparing for inference...&quot;)<br><br>    # Get a list of all validation images<br>    val_images = glob.glob(f&quot;{val_images_dir}/*.jpg&quot;)<br><br>    if not val_images:<br>        print(&quot;Error: No validation images found in the specified directory.&quot;)<br>    else:<br>        # Select 3 random images for testing<br>        # Remove the random.seed(42) line if you want different images every time you run this cell<br>        random.seed(42)<br>        sample_images = random.sample(val_images, min(3, len(val_images)))<br><br>        print(f&quot;Running inference on {len(sample_images)} random validation images...&quot;)<br><br>        # Create a matplotlib figure to display the results inline<br>        fig, axes = plt.subplots(1, len(sample_images), figsize=(20, 10))<br>        if len(sample_images) == 1:<br>            axes = [axes]<br><br>        for i, img_path in enumerate(sample_images):<br>            # Run the model on the image with a confidence threshold of 25%<br>            results = model(img_path, conf=0.25)<br><br>            # The results object contains the image with the predicted bounding boxes drawn on it<br>            annotated_img = results[0].plot()<br><br>            # Convert BGR (OpenCV format) to RGB (Matplotlib format) for correct color display<br>            annotated_img_rgb = cv2.cvtColor(annotated_img, cv2.COLOR_BGR2RGB)<br><br>            # Display the processed image<br>            axes[i].imshow(annotated_img_rgb)<br>            axes[i].axis(&#39;off&#39;)<br>            axes[i].set_title(f&quot;Validation Test {i+1}&quot;)<br><br>        plt.tight_layout()<br>        plt.show()<br><br>except Exception as e:<br>    print(f&quot;An error occurred during model loading or visualization: {e}&quot;)</pre><p>In an industrial setting, line_width=1 and font_size=10 are recommended, as thick lines can obscure the details of tiny defects.</p><p>This project reaffirmed my belief that the foundation of robust industrial AI solutions lies not in mindlessly hoarding data, but in meticulous data cleaning and hardware-optimized parameterization.</p><h3>References &amp; Resources</h3><ul><li><strong>Dataset:</strong> Nakul Bajaj — <a href="https://www.kaggle.com/datasets/nakul8820/pcb-dataset-with-augmentations">PCB Dataset with Augmentations (Kaggle)</a></li><li><strong>Framework:</strong> <a href="https://github.com/ultralytics/ultralytics">Ultralytics YOLO</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ea3a00a2ce8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fém felületi hibák felismerése YOLO26s model segítségével]]></title>
            <link>https://medium.com/@rozsit/f%C3%A9m-fel%C3%BCleti-hib%C3%A1k-felismer%C3%A9se-yolo26s-model-seg%C3%ADts%C3%A9g%C3%A9vel-bdfdde08c1a1?source=rss-7f595eb81d3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdfdde08c1a1</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Tamás Rózsahegyi]]></dc:creator>
            <pubDate>Wed, 25 Feb 2026 10:46:02 GMT</pubDate>
            <atom:updated>2026-02-25T10:46:02.312Z</atom:updated>
            <content:encoded><![CDATA[<p>Ebben a cikkben ismertetek egy gépi látás (computer vision) projektet, melynek célja egy automatizált minőségellenőrző (Quality Control) prototípus felépítése volt. A feladat: ipari fémalkatrészek felületi hibáinak valós idejű, emberi beavatkozás nélküli felismerése kameraképek alapján.</p><p>A kísérlethez egy 15 000 képet (256x256 pixel, 8-bit grayscale) tartalmazó szintetikus adathalmazt használtam, (itt megtalálod: <a href="https://www.kaggle.com/datasets/tatheerabbas/synthetic-industrial-metal-surface-defects">https://www.kaggle.com/datasets/tatheerabbas/synthetic-industrial-metal-surface-defects)</a> amely négy fő hibatípust szimulált: karcolásokat, repedéseket, rozsdát és lyukakat. Bár az adatok szintetikusak voltak, a felmerülő infrastrukturális és tanítási kihívások nagyon is valósak.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qm9OAzaCNvf31KmJw-WArw.jpeg" /><figcaption>Train image example</figcaption></figure><p>A felismeréshez az Ultralytics legújabb YOLO26 architektúráját, abból is a Small (YOLO26s) modellt választottam. Ez a hálózat közel 9,95 millió paraméterrel és 22.5 GFLOPs számítási igénnyel rendelkezik. A verzió legnagyobb technikai újítása, hogy elhagyja a hagyományos NMS (Non-Maximum Suppression) utófeldolgozási lépést, ami sokkal tisztább kimenetet és alacsonyabb késleltetést eredményez. A munkafolyamat a saját gépem és a Google Colab (ahol egy 24 GB VRAM-mal rendelkező NVIDIA L4 GPU-t használtam) között zajlott.</p><p>A modellt 100 epoch-on keresztül tanítottam (batch size 16), MuSGD optimalizálóval (lr=0.01). A túltanulás elkerülése végett bekapcsoltam a korai leállítást (patience=20), illetve egy meglehetősen agresszív adatkiegészítési (augmentation) stratégiát alkalmaztam. A HSV színtér eltolása mellett bevezettem egy 10 fokos véletlenszerű forgatást (degrees=10.0), valamint 50%-os valószínűségű vertikális és horizontális tükrözést (flipud/fliplr).</p><p>A 4,3 órás tanítási folyamat végére a modell 76.9%-os átfogó mAP50 pontosságot ért el, a részeredmények pedig rávilágítottak a feladat vizuális komplexitására:</p><ul><li>Lyukak (hole): 99.5% mAP50 — gyakorlatilag tökéletes felismerés</li><li>Rozsda (rust): 83.1% mAP50 — rendkívül stabil detektálás</li><li>Repedések (crack): 79.4% mAP50 — itt az augmentációk hatására egyértelmű javulás történt a korábbi tesztekhez képest</li><li>Karcolások (scratch): 45.6% mAP50 — a fém textúrájába olvadó, mikroszkopikus vonalak detektálása továbbra is a legnehezebb feladat, ide a jövőben még nagyobb bemeneti felbontás (pl. 640x640) lehet indokolt</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ovKvxZM_0tPFPgrTFO2BmQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3dOdd8DBCsyOz9qf21ydkA.png" /></figure><p>A betanított modellt végül visszahúztam a saját gépemre tesztelésre.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w550b7ZTyaMMsu1RH3GfCw.png" /><figcaption>Hibák felismerése validation adathalmazon</figcaption></figure><p>Végül pedig következzen a kód, amit legújabban Microsoft Visual Studio-ban írok Jupyter extension segítségével, így mind a Visual Studio, mind a Jupyter Notebook előnyeit egyszerre tudom használni. Hangsúlyozom, hogy ez a Google Colab-ra optimalizált kód.</p><pre>!pip install ultralytics</pre><pre>import torch<br>from google.colab import files<br>from google.colab import drive<br>import os</pre><p>Az adatok eléréséhez csatlakoztatjuk a Google Drive-ot. Definiáljuk a Google Drive-on tárolt tömörített adathalmaz (dataset.zip) útvonalát, illetve a Colab helyi SSD-jén kialakítandó célkönyvtárat.</p><pre># Mount Google Drive to access the cloud storage<br>drive.mount(&#39;/content/drive&#39;)<br><br># Define source and destination paths<br># Change &#39;dataset.zip&#39; to the actual path inside your Drive if it&#39;s in a folder<br>source_path = &#39;/content/drive/MyDrive/Colab_Notebooks/Metal_Surface_Detects/dataset.zip&#39;<br>target_dir = &#39;/content/metal_dataset/&#39;<br>target_zip = &#39;/content/metal_dataset/dataset.zip&#39;</pre><p>Az I/O műveletek okozta lassúság elkerülése érdekében az adatokat a Drive-ról egyenesen a Colab gép helyi tárhelyére másoljuk, ott kicsomagoljuk, végül a helytakarékosság miatt töröljük magát a ZIP fájlt. Ezzel az apró logikai lépéssel órákat spórolunk a tanítás során!</p><pre># Create directory, copy and unzip<br>if os.path.exists(source_path):<br>    # Create the target directory if it does not exist<br>    print(f&quot;Creating directory: {target_dir}&quot;)<br>    !mkdir -p &quot;{target_dir}&quot;<br><br>    # Copy the zip file to the local directory<br>    print(&quot;Copying file from Google Drive...&quot;)<br>    !cp &quot;{source_path}&quot; &quot;{target_zip}&quot;<br><br>    # Unzip the file into the metal_dataset folder<br>    print(&quot;Extracting files...&quot;)<br>    !unzip -q &quot;{target_zip}&quot; -d &quot;{target_dir}&quot;<br><br>    # Remove the temporary zip file from the local folder to save space<br>    if os.path.exists(target_zip):<br>        os.remove(target_zip)<br>        print(&quot;Temporary zip file removed.&quot;)<br><br>    print(f&quot;Process finished. Data is ready in: {target_dir}&quot;)<br>else:<br>    print(f&quot;Error: {source_path} was not found on Google Drive.&quot;)</pre><p>A következő fázisban az adatokat a YOLO által elvárt formátumra alakítjuk. Importáljuk a műveletekhez szükséges csomagokat. Definiáljuk a könyvtárakat, beállítjuk a képfelbontást (256x256 pixel), és létrehozunk egy szótárt a hibaosztályok sorszámozásához. (A ‘normal’, azaz a hibátlan háttérképek szándékosan maradnak ki ebből a listából)</p><pre>import os<br>import ast<br>import math<br>import zipfile<br>import pandas as pd<br>import yaml</pre><pre>ZIP_PATH = &quot;dataset.zip&quot;<br>LOCAL_DATASET = &quot;/content/metal_dataset&quot;<br>LOCAL_IMAGES = os.path.join(LOCAL_DATASET, &quot;images&quot;)<br>LOCAL_LABELS = os.path.join(LOCAL_DATASET, &quot;labels&quot;)<br>CSV_PATH = os.path.join(LOCAL_DATASET, &quot;metadata.csv&quot;)<br><br>CLASS_MAP = {&#39;scratch&#39;: 0, &#39;crack&#39;: 1, &#39;rust&#39;: 2, &#39;hole&#39;: 3}<br>IMG_WIDTH = 256.0<br>IMG_HEIGHT = 256.0</pre><p>Beolvassuk a metadata.csv fájlt (dataset része), és a pixelben megadott hibaterületek alapján kiszámoljuk a határolódobozok (bounding boxes) kiterjedését. A YOLO algoritmus 0 és 1 közé normalizált értékeket vár, így a szkript elvégzi az osztásokat, és minden egyes kép mellé legenerálja a pontos .txt formátumú annotációs fájlt a megfelelő mappa-struktúrába.</p><pre>print(&quot;Generating YOLO label files...&quot;)<br><br>df = pd.read_csv(CSV_PATH)<br><br>for index, row in df.iterrows():<br>    filename = row[&#39;filename&#39;]<br>    img_class = row[&#39;class&#39;]<br>    split = row[&#39;split&#39;]<br>    txt_filename = filename.replace(&#39;.png&#39;, &#39;.txt&#39;)<br>    txt_filepath = os.path.join(LOCAL_LABELS, split, img_class, txt_filename)<br><br>    os.makedirs(os.path.dirname(txt_filepath), exist_ok=True)<br><br>    try:<br>        positions = ast.literal_eval(row[&#39;defect_positions&#39;])<br>        sizes = ast.literal_eval(row[&#39;defect_sizes_px&#39;])<br>    except (ValueError, SyntaxError):<br>        positions = []<br>        sizes = []<br><br>    yolo_lines = []<br><br>    if img_class in CLASS_MAP and len(positions) &gt; 0:<br>        class_id = CLASS_MAP[img_class]<br>        for pos, size_px in zip(positions, sizes):<br>            center_x = pos[0]<br>            center_y = pos[1]<br>            box_width = math.sqrt(size_px)<br>            box_height = math.sqrt(size_px)<br>            norm_x = min(max(center_x / IMG_WIDTH, 0.0), 1.0)<br>            norm_y = min(max(center_y / IMG_HEIGHT, 0.0), 1.0)<br>            norm_w = min(max(box_width / IMG_WIDTH, 0.0), 1.0)<br>            norm_h = min(max(box_height / IMG_HEIGHT, 0.0), 1.0)<br>            yolo_lines.append(f&quot;{class_id} {norm_x:.6f} {norm_y:.6f} {norm_w:.6f} {norm_h:.6f}&quot;)<br><br>    with open(txt_filepath, &#39;w&#39;) as f:<br>        if yolo_lines:<br>            f.write(&#39;\n&#39;.join(yolo_lines))<br><br>print(&quot;Done!&quot;)</pre><p>A modelnek szüksége van egy data.yaml fájlra, amely navigálja a beolvasás során. Ez a cella összeállítja a konfigurációt a képek helyével és a vizsgált osztályok neveivel.</p><pre>print(&quot;Creating data.yaml...&quot;)<br><br>data_yaml = {<br>    &#39;path&#39;: LOCAL_DATASET,<br>    &#39;train&#39;: &#39;images/train&#39;,<br>    &#39;val&#39;: &#39;images/val&#39;,<br>    &#39;nc&#39;: 4,<br>    &#39;names&#39;: [&#39;scratch&#39;, &#39;crack&#39;, &#39;rust&#39;, &#39;hole&#39;]<br>}<br><br>yaml_file_path = os.path.join(LOCAL_DATASET, &#39;data.yaml&#39;)<br><br>with open(yaml_file_path, &#39;w&#39;) as outfile:<br>    yaml.dump(data_yaml, outfile, default_flow_style=False)<br><br>print(&quot;Dataset preparation complete!&quot;)</pre><p>Miután előkészítettük, most jön a model tanítása. Inicializáljuk az Ultralytics legújabb, NMS (Non-Maximum Suppression) nélküli YOLO26s (Small) modelljét, és megkezdjük a tanítást. A robusztusabb felismerés érdekében bekapcsoljuk az augmentációt (például a színtér hsv finomhangolását, és a képek forgatását 10 fokkal), illetve beállítunk egy 20 epochos ‘patience’ paramétert a korai leállításhoz. Ne ijedjen meg senki, a most következő cella nekem több mint 4 órán keresztül futott és a Colab ‘Pay as You Go’ csomagját használtam.</p><pre>from ultralytics import YOLO<br><br>print(&quot;Initializing YOLO26s model for better accuracy...&quot;)<br><br>model = YOLO(&quot;yolo26s.pt&quot;)<br><br>print(&quot;Starting the extended training phase...&quot;)<br><br>results = model.train(<br>    data=&quot;/content/metal_dataset/data.yaml&quot;,<br>    epochs=100,<br>    patience=20,<br>    imgsz=256,<br>    batch=16,<br>    project=&quot;/content/runs&quot;,<br>    name=&quot;yolo26s_metal_defects&quot;,<br>    augment=True,<br>    hsv_h=0.015,<br>    hsv_s=0.7,<br>    hsv_v=0.4,<br>    degrees=10.0,<br>    flipud=0.5,<br>    fliplr=0.5<br>)<br>print(&quot;Training finished successfully!&quot;)</pre><p>Mivel a Colab helyi környezete ideiglenes, és a futtatás végeztével törlődik, a betanítás befejeztével a kész súlyfájlt (best.pt) és a futtatás naplóit egyetlen ZIP archívumba csomagoljuk, majd a files.download() segítségével azonnal letöltjük a saját számítógépünkre.</p><pre>import shutil<br><br>print(&quot;Zipping the training results and the trained model...&quot;)<br>shutil.make_archive(&quot;/content/yolo_results_final&quot;, &#39;zip&#39;, &quot;/content/runs/yolo26s_metal_defects&quot;)<br><br>print(&quot;Downloading results to your computer...&quot;)<br><br>files.download(&quot;/content/yolo_results_final.zip&quot;)</pre><p>Végül a pandas és a matplotlib segítségével grafikonokon is kiértékeljük a modell teljesítményét. Beolvassuk a results.csv-t, és bal oldalon ábrázoljuk a dobozolási hiba (Box Loss) exponenciális csökkenését, jobb oldalon pedig a modell pontosságának (mAP) növekedését az iterációk során. Egyébként a Yolo is több képet elment majd, F1 curve, PR curve stb.</p><pre>import matplotlib.pyplot as plt<br><br>print(&quot;Plotting performance metrics...&quot;)<br>results_path = &quot;/content/runs/yolo26s_metal_defects/results.csv&quot;<br><br>if os.path.exists(results_path):<br>    df = pd.read_csv(results_path)<br>    df.columns = df.columns.str.strip()<br>    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))<br><br>    if &#39;train/box_loss&#39; in df.columns:<br>        ax1.plot(df[&#39;epoch&#39;], df[&#39;train/box_loss&#39;], label=&#39;Train Box Loss&#39;, marker=&#39;o&#39;)<br>        ax1.plot(df[&#39;epoch&#39;], df[&#39;val/box_loss&#39;], label=&#39;Val Box Loss&#39;, marker=&#39;o&#39;)<br>        ax1.set_title(&#39;Training and Validation Box Loss&#39;)<br>        ax1.set_xlabel(&#39;Epoch&#39;)<br>        ax1.set_ylabel(&#39;Loss&#39;)<br>        ax1.legend()<br>        ax1.grid(True)<br><br>    if &#39;metrics/mAP50(B)&#39; in df.columns:<br>        ax2.plot(df[&#39;epoch&#39;], df[&#39;metrics/mAP50(B)&#39;], label=&#39;mAP@50&#39;, marker=&#39;o&#39;, color=&#39;green&#39;)<br>        ax2.plot(df[&#39;epoch&#39;], df[&#39;metrics/mAP50-95(B)&#39;], label=&#39;mAP@50-95&#39;, marker=&#39;o&#39;, color=&#39;purple&#39;)<br>        ax2.set_title(&#39;Mean Average Precision (mAP)&#39;)<br>        ax2.set_xlabel(&#39;Epoch&#39;)<br>        ax2.set_ylabel(&#39;mAP&#39;)<br>        ax2.legend()<br>        ax2.grid(True)<br>    plt.tight_layout()<br>    plt.show()</pre><p>És egy kis EXTRA, én így használtam a saját gépemen a model-t:</p><pre># !pip install ultralytics matplotlib opencv-python<br><br>import os<br>import random<br>import cv2<br>import matplotlib.pyplot as plt<br>from ultralytics import YOLO<br><br># Update these paths to match your local machine&#39;s directory structure<br>local_model_path = &quot;yolo_results_final/weights/best.pt&quot;  # Path to the downloaded model weights<br>local_val_dir = &quot;images/val&quot;  # Path to your local val folder<br><br>if os.path.exists(local_model_path):<br>    # Load the YOLO model<br>    model = YOLO(local_model_path)<br>    print(&quot;Model loaded successfully.&quot;)<br><br>    # Collect all image files from all subdirectories in the val folder<br>    all_image_paths = []<br>    for root, dirs, files in os.walk(local_val_dir):<br>        for file in files:<br>            if file.lower().endswith((&#39;.png&#39;, &#39;.jpg&#39;, &#39;.jpeg&#39;)):<br>                all_image_paths.append(os.path.join(root, file))<br><br>    if len(all_image_paths) &gt;= 3:<br>        # Select 3 random images<br>        selected_images = random.sample(all_image_paths, 3)<br>        <br>        # Setup the plot<br>        fig, axes = plt.subplots(1, 3, figsize=(20, 10))<br>        print(&quot;Running inference on 3 random images...&quot;)<br><br>        for i, img_path in enumerate(selected_images):<br>            # Run prediction<br>            results = model.predict(source=img_path, conf=0.25, verbose=False)<br>            <br>            # Plot results (YOLO returns BGR, matplotlib needs RGB)<br>            res_plotted = results[0].plot()<br>            res_rgb = cv2.cvtColor(res_plotted, cv2.COLOR_BGR2RGB)<br>            <br>            # Get the ground truth class name from the folder name<br>            ground_truth = os.path.basename(os.path.dirname(img_path))<br>            <br>            # Display the image<br>            axes[i].imshow(res_rgb)<br>            axes[i].set_title(f&quot;GT: {ground_truth}&quot;)<br>            axes[i].axis(&#39;off&#39;)<br>        <br>        plt.tight_layout()<br>        plt.show()<br>    else:<br>        print(f&quot;Not enough images found in {local_val_dir}. Found: {len(all_image_paths)}&quot;)<br>else:<br>    print(f&quot;Error: Model file not found at {local_model_path}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P0stg3w3cxiTFuGGaj03cA.png" /></figure><pre>### References<br><br>**Dataset:**<br>Abbas, T. (2026). *Synthetic Industrial Metal Surface Defect Dataset*. Kaggle. Licensed under CC BY 4.0.<br><br>**Citation (BibTeX):**<br>```bibtex<br>@dataset{synthetic_metal_defects_2026, <br>  title = {Synthetic Industrial Metal Surface Defect Dataset}, <br>  author = {Tatheer Abbas}, <br>  year = {2026}, <br>  url = {https://www.kaggle.com/datasets/tatheerabbas/synthetic-industrial-metal-defects}, <br>  note = {15,000 procedurally generated images for defect detection research} <br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdfdde08c1a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Szintetikus adathalmaz generálása madárfelismeréshez AI (Stable Diffusion) segítségével]]></title>
            <link>https://medium.com/@rozsit/szintetikus-adathalmaz-gener%C3%A1l%C3%A1sa-mad%C3%A1rfelismer%C3%A9shez-ai-stable-diffusion-seg%C3%ADts%C3%A9g%C3%A9vel-ba8594bb06cb?source=rss-7f595eb81d3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba8594bb06cb</guid>
            <dc:creator><![CDATA[Tamás Rózsahegyi]]></dc:creator>
            <pubDate>Sun, 22 Feb 2026 12:37:13 GMT</pubDate>
            <atom:updated>2026-02-22T12:37:13.463Z</atom:updated>
            <content:encoded><![CDATA[<p>A gépilátás-modellek tanításakor a legnagyobb kihívás a megfelelő mennyiségű és minőségű adat. Ebben a cikkben megmutatom, hogyan készítettem el a kerti vadkamerámhoz a tanító adathalmazt generatív AI segítségével. A lenti kódot Google Colab-ban futtattam (T4 GPU): mert erős lokális GPU nélkül is szerverparki teljesítménnyel generálhatok adatokat.</p><h3>0. Szükséges telepítések és a saját Google Drive mappám mount-olása</h3><pre>!pip install diffusers transformers accelerate matplotlib opencv-python<br><br>from google.colab import drive<br>drive.mount(&#39;/content/drive&#39;)<br><br># Define the root directory for our dataset<br>PROJECT_ROOT = &quot;/content/drive/MyDrive/Colab_Notebooks/Create_Own_Dataset/data&quot;<br><br>print(&quot;Drive mounted and PROJECT_ROOT set successfully.&quot;)</pre><h3>1. Környezet előkészítése és a könyvtárak importálása</h3><p>Az első lépés a szükséges eszközök betöltése. A diffusers könyvtárat használom a Stable Diffusion modell futtatásához, a torch-ot a GPU kezeléséhez, az OpenCV-t pedig a képek mentéséhez.</p><pre>import os<br>import cv2<br>import torch<br>import numpy as np<br>import random<br>from diffusers import StableDiffusionPipeline<br>import matplotlib.pyplot as plt</pre><h3>2. A kategóriák és a környezeti variációk definiálása</h3><p>A modellnek nemcsak azt kell tudnia, mi az a fekete rigó, hanem azt is, hogy mi nem az. Ezért két osztályt hozok létre, és változatos kerti környezeteket határozok meg, hogy a modellünk robusztus legyen.</p><pre># Define the classes: our target bird and everything else<br>traffic_classes = [&quot;Blackbird&quot;, &quot;No_Blackbird&quot;]<br><br># Environmental conditions to ensure the dataset is diverse<br>environments = [<br>    &quot;in a green garden with fruit trees&quot;,<br>    &quot;on a wooden fence post&quot;,<br>    &quot;on a freshly mown lawn&quot;,<br>    &quot;perched on a bird feeder&quot;,<br>    &quot;among autumn leaves on the ground&quot;,<br>    &quot;in dappled sunlight under a bush&quot;<br>]<br><br># Specific prompts for each class<br>class_prompts = {<br>    &quot;Blackbird&quot;: &quot;A detailed male blackbird (Turdus merula), jet black feathers, bright orange-yellow eye ring and beak, standing&quot;,<br>    &quot;No_Blackbird&quot;: &quot;A common garden bird like a sparrow or titmouse, or just an empty garden scene with no birds&quot;<br>}<br><br># Negative prompt to keep the quality high<br>negative_prompt = &quot;blurry, out of focus, distorted, cartoon, drawing, human, cage, extra limbs, deformed wings&quot;</pre><h3>3. Az AI modell betöltése</h3><p>A dreamlike-art/dreamlike-diffusion-1.0 modellt használom, amely híres a fotorealisztikus ábrázolásmódjáról. Fontos a torch.float16 használata, mert így a Google Colab T4 GPU-ja sokkal gyorsabban és kevesebb memóriával tud dolgozni.</p><pre># Load the model<br>model_id = &quot;dreamlike-art/dreamlike-diffusion-1.0&quot;<br>print(&quot;Loading Text-to-Image pipeline...&quot;)<br>txt2img_pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16, use_safetensors=True).to(&quot;cuda&quot;)<br><br># Set output directory using PROJECT_ROOT<br>output_dir = PROJECT_ROOT<br>os.makedirs(output_dir, exist_ok=True)</pre><h3>4. A generálási logika és a Seed kontroll</h3><p>Ez a kód szíve. Minden képhez egy egyedi véletlenszerű számot (Seed) generálunk. A torch.Generator rögzítése biztosítja, hogy a generált képek variációi kontrolláltak maradjanak, mégis egyediek legyenek minden iterációban. Első körben csak 50 képet generáltattam, de nyilván a valóságban több száz, vagy ezer kép lehet megfelelő.</p><pre># Configuration<br>num_images = 50 # Start with 50 per class (100 total)<br>image_size = 512<br><br>for traffic_class in traffic_classes:<br>    class_dir = os.path.join(output_dir, traffic_class)<br>    os.makedirs(class_dir, exist_ok=True)<br><br>    print(f&quot;\nStarting generation for class: {traffic_class}&quot;)<br><br>    for i in range(num_images):<br>        image_path = os.path.join(class_dir, f&quot;{traffic_class}_{i+1}.jpg&quot;)<br><br>        if os.path.exists(image_path):<br>            continue<br><br>        # Randomize environment and seed<br>        env = random.choice(environments)<br>        seed = random.randint(0, 2147483647)<br>        generator = torch.Generator(device=&quot;cuda&quot;).manual_seed(seed)<br><br>        # Build prompt<br>        prompt = f&quot;{class_prompts[traffic_class]} {env}, photorealistic, 8k, sharp focus.&quot;<br><br>        print(f&quot;Generating {traffic_class} {i+1}/{num_images}...&quot;)<br><br>        img = txt2img_pipe(<br>            prompt,<br>            num_inference_steps=50,<br>            width=image_size,<br>            height=image_size,<br>            negative_prompt=negative_prompt,<br>            generator=generator<br>        ).images[0]<br><br>        # Save image<br>        img_array = np.array(img)[:, :, ::-1]<br>        cv2.imwrite(image_path, img_array)<br><br>        # Display first sample<br>        if i == 0:<br>            plt.imshow(img)<br>            plt.title(f&quot;Sample: {traffic_class}&quot;)<br>            plt.axis(&quot;off&quot;)<br>            plt.show()<br><br>print(&quot;\nDataset generation complete!&quot;)</pre><h3>5. Az adatok szétválogatása: Train és Val szettek</h3><p>A modell tanítása előtt az adatokat szét kell szortírozni. A képek 80%-át a tanításhoz (Train), 20%-át pedig a modell ellenőrzéséhez (Validation) fogom használni. Ez a kód automatikusan létrehozza a mappaszerkezetet és átmozgatja a fájlokat.</p><pre>import shutil<br><br>train_ratio = 0.8<br>for category in traffic_classes:<br>    # Create directories<br>    os.makedirs(os.path.join(PROJECT_ROOT, &quot;train&quot;, category), exist_ok=True)<br>    os.makedirs(os.path.join(PROJECT_ROOT, &quot;val&quot;, category), exist_ok=True)<br>    <br>    # List and shuffle images<br>    category_path = os.path.join(PROJECT_ROOT, category)<br>    images = [f for f in os.listdir(category_path) if f.endswith(&#39;.jpg&#39;)]<br>    random.shuffle(images)<br>    <br>    # Move files based on split ratio<br>    split_idx = int(len(images) * train_ratio)<br>    for idx, img_name in enumerate(images):<br>        target_folder = &quot;train&quot; if idx &lt; split_idx else &quot;val&quot;<br>        shutil.move(<br>            os.path.join(category_path, img_name),<br>            os.path.join(PROJECT_ROOT, target_folder, category, img_name)<br>        )<br>    os.rmdir(category_path)<br><br>print(&quot;Dataset successfully split and organized!&quot;)</pre><h3>6. További felhasználás, például az iparban</h3><p>A “Synthetic Data” nem csak madármegfigyelésre jó. Ugyanezt a technológiát alkalmazhatjuk az iparban is:</p><p><strong>Minőségellenőrzés:</strong> generálhatunk képeket ritka gyártási hibákról (repedés, karcolás), amikből a valóságban szerencsére kevés van, de a modellnek ismernie kell őket.</p><p><strong>Munkavédelem:</strong> taníthatunk modelleket védőfelszerelés nélküli dolgozók felismerésére anélkül, hogy valós veszélyhelyzeteket kellene fotóznunk.</p><p><strong>Logisztika:</strong> szimulálhatunk különböző rakománytípusokat extrém fényviszonyok vagy időjárás mellett a raktári kamerák számára.</p><p>A generatív AI-val az adathiány már nem akadály, hanem optimalizációs kérdés.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba8594bb06cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Amikor a Data Science találkozik a városi napfénnyel: egy kis Python kísérlet]]></title>
            <link>https://medium.com/@rozsit/amikor-a-data-science-tal%C3%A1lkozik-a-v%C3%A1rosi-napf%C3%A9nnyel-egy-kis-python-k%C3%ADs%C3%A9rlet-dc46e8951f45?source=rss-7f595eb81d3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc46e8951f45</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Tamás Rózsahegyi]]></dc:creator>
            <pubDate>Fri, 13 Feb 2026 19:01:00 GMT</pubDate>
            <atom:updated>2026-02-13T19:01:00.585Z</atom:updated>
            <content:encoded><![CDATA[<p>Gondolkoztál már azon, hogyan változtatja meg egy város arcát a nap járása? Vagy hogy egy adott épület árnyéka hová vetül a nyári napforduló idején? Ebben a tutorialban megmutatom, hogyan készíthetsz látványos, interaktív 3D térképet Python segítségével, felhasználva az OpenStreetMap adatait és némi trigonometriát. London szívébe, a Westminster-palota környékére utazunk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ji3CwOaz-d4snT6QvHbl7g.png" /></figure><h3>1. A szükséges eszköztár betöltése</h3><p>Mielőtt belevágnánk, be kell töltenünk a Python könyvtárakat. A “nehéztüzérséget” az osmnx (térképadatok letöltése) és a pydeck (3D vizualizáció) jelenti.</p><pre>import osmnx as ox<br>import pandas as pd<br>import numpy as np<br>import pydeck as pdk<br>import geopandas as gpd<br><br># Configure osmnx to use the cache (speeds up repeated runs)<br>ox.settings.use_cache = True<br>ox.settings.log_console = True<br><br>print(&quot;Libraries loaded successfully!&quot;)</pre><p>Itt importáljuk a szükséges modulokat. Az osmnx felel az OpenStreetMap kommunikációért, a geopandas kezeli a geometriai adatokat (pl. épületek alakja), a pydeck pedig a WebGL alapú 3D megjelenítésért felel. Bekapcsoljuk a gyorsítótárazást (cache), hogy ne kelljen minden futtatásnál újra letölteni az adatokat a szerverről.</p><h3>2. Adatok letöltése London szívéből</h3><p>Nem rajzolunk kézzel. Megadjuk a koordinátákat (London, Westminster) és egy sugarat, a Python pedig elvégzi a többit.</p><pre># Data download<br># Coordinates for Westminster Palace, London<br>center_point = (51.4995, -0.1242) <br>dist = 1000  # Radius in meters<br><br>print(f&quot;Downloading data (radius: {dist}m)...&quot;)<br>print(&quot;This might take a moment due to the high density of London.&quot;)<br><br># Download building geometries<br>buildings = ox.features_from_point(center_point, tags={&#39;building&#39;: True}, dist=dist)</pre><p>Kijelöljük a középpontot (ez most a Westminster-palota koordinátája) és 1000 méteres sugarú körben letöltünk minden olyan elemet, ami az OpenStreetMap-en building (épület) címkével van ellátva. Ez London belvárosában több ezer objektumot jelent.</p><h3>3. Vetületi transzformáció: fokból méterbe</h3><p>Ez a legfontosabb technikai lépés. A GPS koordináták fokokban vannak, de nekünk méterek kellenek az árnyék számításához.</p><pre># Cleaning and transformation<br># Keep only polygons<br>buildings = buildings[buildings.geometry.type == &#39;Polygon&#39;]<br><br># Project to a metric CRS suitable for London/UK<br># UTM Zone 30N (EPSG:32630) is appropriate for London longitude<br>gdf = buildings.to_crs(epsg=32630)<br><br># Handle missing height data<br>if &#39;height&#39; not in gdf.columns:<br>    gdf[&#39;height&#39;] = np.nan<br>else:<br>    # Convert column to numeric, coercing errors to NaN<br>    gdf[&#39;height&#39;] = pd.to_numeric(gdf[&#39;height&#39;], errors=&#39;coerce&#39;)</pre><p>Először kiszűrjük a hibás adatokat (csak a zárt sokszögeket, azaz poligonokat tartjuk meg). Ezután jön a varázslat: az adatokat átkonvertáljuk az EPSG:32630 vetületi rendszerbe (UTM Zone 30N). Miért? Mert ez a szabványos méter alapú rendszer az Egyesült Királyságban. Ha fokokban számolnánk árnyékot, torz eredményt kapnánk.</p><h3>4. Hiányzó adatok pótlása</h3><p>Az OpenStreetMap közösségi adatbázis, így nem minden épületnek van megadva a magassága. Ezt pótolnunk kell a vizualizációhoz.</p><pre># Fill missing heights with random values<br># London has varied architecture, using 8-30m range for generic buildings<br>mask = gdf[&#39;height&#39;].isna()<br>gdf.loc[mask, &#39;height&#39;] = np.random.uniform(8, 30, size=mask.sum())</pre><p>Ahol hiányzik a magasság adat (NaN), oda generálunk egy véletlenszerű értéket 8 és 30 méter között. Bár ez nem felel meg a valóságnak minden egyes háznál, a 3D-s városkép hangulatának visszaadásához tökéletes, és megakadályozza, hogy &quot;lapos&quot; legyen a térképünk.</p><h3>5. Gyors ellenőrzés</h3><p>Mindig érdemes ránézni az adatokra, mielőtt tovább lépünk.</p><pre>print(f&quot;Success! {len(gdf)} buildings processed and stored in memory.&quot;)<br>print(gdf[[&#39;height&#39;, &#39;geometry&#39;]].head(3))</pre><p>Kiíratjuk, hány épületet sikerült feldolgozni (nálam ez 2497 buildings), és megnézzük az adattábla (GeoDataFrame) első pár sorát, hogy lássuk, minden rendben van-e a magasságokkal és a geometriával.</p><h3>6. Időutazás beállítása</h3><p>Most beállítjuk a szimuláció idejét. Legyen ez a nyári napforduló, amikor a leghosszabbak a nappalok!</p><pre>from pysolar.solar import get_altitude, get_azimuth<br>from shapely.affinity import translate<br>import datetime<br>import math<br><br># Configure time<br># Date: June 21, 2025, at 17:00 London time<br># So we request 16:00 UTC<br>date = datetime.datetime(2025, 6, 21, 16, 0, tzinfo=datetime.timezone.utc)<br><br># Update coordinates for solar calculation<br>lat = 51.4995<br>lon = -0.1242</pre><p>Beimportáljuk a pysolar könyvtárat, ami képes kiszámolni a Nap pontos pozícióját. A dátumot 2025. június 21-re állítjuk, délután 17:00 órára (Londoni idő szerint), ami UTC-ben 16:00.</p><h3>7. Hol a Nap?</h3><p>Kiszámoljuk a Nap pontos szögét az égen az adott időpontban.</p><pre># Calculate Sun position<br>altitude = get_altitude(lat, lon, date)<br>azimuth = get_azimuth(lat, lon, date)<br><br>print(f&quot;Sun Altitude: {altitude:.2f}°&quot;)<br>print(f&quot;Sun Azimuth: {azimuth:.2f}°&quot;)</pre><p>Két értéket kapunk:</p><ol><li><strong>Altitude (Magasság):</strong> Milyen magasan van a Nap a horizont felett (fokban)</li><li><strong>Azimuth (Irányszög):</strong> Milyen irányból süt a Nap (fokban, északhoz képest). Ezek az adatok kellenek majd az árnyékok geometriájának kiszámításához</li></ol><h3>8. Az “Árnyék-motor” függvénye</h3><p>Itt történik a matek. A trigonometria segítségével kiszámoljuk az árnyékok hosszát és irányát.</p><pre># Shadow calculation function<br>def calculate_shadow(row, sun_alt, sun_azi):<br>    &quot;&quot;&quot;<br>    Creates a shadow polygon by shifting the building footprint.<br>    &quot;&quot;&quot;<br>    if sun_alt &lt;= 0:<br>        return None<br>    <br>    # Calculate shadow length (Length = Height / tan(Altitude))<br>    height = row[&#39;height&#39;]<br>    # Add a safety check for very low sun angles to prevent infinite shadows<br>    safe_alt = max(sun_alt, 5.0) <br>    shadow_len = height / math.tan(math.radians(safe_alt))<br>    <br>    # Calculate offsets<br>    shadow_azimuth = math.radians(sun_azi - 180)<br>    x_offset = shadow_len * math.sin(shadow_azimuth)<br>    y_offset = shadow_len * math.cos(shadow_azimuth)<br>    <br>    # Translate geometry<br>    shadow_geom = translate(row[&#39;geometry&#39;], xoff=x_offset, yoff=y_offset)<br>    return shadow_geom</pre><p>Ez a függvény minden egyes épületre lefut.</p><ul><li>shadow_len: Az árnyék hossza = Épület magassága / tan(Nap magassága)</li><li>offsets: Kiszámoljuk, mennyit kell eltolni az épület alakzatát X és Y irányban a földön. Fontos: az árnyék mindig a Nappal <em>ellentétes</em> irányba vetül (ezért vonunk ki 180 fokot)</li><li>translate: A shapely könyvtárral létrehozzuk az eltolt geometriát (magát az árnyékot)</li></ul><h3>9. Árnyékok generálása</h3><p>Alkalmazzuk a függvényt az összes épületre.</p><pre># Apply to dataset<br>print(&quot;Generating shadows for all buildings (this may take time)...&quot;)<br><br>shadows = gdf.copy()<br>shadows[&#39;geometry&#39;] = shadows.apply(lambda row: <br>  calculate_shadow(row, altitude, azimuth), axis=1)<br><br># Flat height for shadows<br>shadows[&#39;height&#39;] = 0.1 <br><br>print(&quot;Shadows generated successfully!&quot;)</pre><p>Lefuttatjuk a számítást a teljes adatbázison. Létrehozunk egy shadows nevű másolatot, ahol a geometria már nem az épületet, hanem annak árnyékát jelenti. Az árnyékok magasságát 0.1 méterre állítjuk, hogy éppen csak a föld felett &quot;lebegjenek&quot;, elkerülve a grafikai hibákat (Z-fighting).</p><h3>10. Vissza a térképre (WGS84)</h3><p>A megjelenítéshez (PyDeck/Mapbox) vissza kell térnünk a szélességi/hosszúsági fokokhoz.</p><pre>import webbrowser<br>import os<br><br># Prepare layers<br># Convert back to WGS84 for PyDeck visualization<br>shadows_display = shadows.to_crs(epsg=4326)<br>gdf_display = gdf.to_crs(epsg=4326)</pre><p>A számításokhoz métereket használtunk (EPSG:32630), de a webes térképek a WGS84 szabványt (EPSG:4326, lat/lon) szeretik. Itt konvertáljuk vissza mindkét réteget (épületek és árnyékok) a megjelenítéshez.</p><h3>11. Az árnyék réteg létrehozása</h3><p>Definiáljuk, hogyan nézzenek ki az árnyékok.</p><pre># Layer 1: Shadows<br>shadow_layer = pdk.Layer(<br>    &quot;PolygonLayer&quot;,<br>    shadows_display,<br>    get_polygon=&quot;geometry.coordinates&quot;,<br>    get_elevation=&quot;0&quot;,<br>    get_fill_color=[0, 0, 0, 160], # Slightly darker shadows<br>    filled=True,<br>    extruded=False,<br>)</pre><p>Létrehozunk egy PolygonLayer-t a PyDeck-ben. Az árnyékok feketék ([0, 0, 0]) és félig átlátszóak (160-as alfa csatorna), valamint laposak (extruded=False), hiszen a földön fekszenek.</p><h3>12. Az épület réteg létrehozása</h3><p>Most jönnek a 3D házak.</p><pre># Layer 2: Buildings<br>building_layer = pdk.Layer(<br>    &quot;PolygonLayer&quot;,<br>    gdf_display,<br>    get_polygon=&quot;geometry.coordinates&quot;,<br>    get_elevation=&quot;height&quot;,<br>    elevation_scale=1,<br>    get_fill_color=[255, 140, 0, 200], # Orange<br>    get_line_color=[255, 255, 255],<br>    line_width_min_pixels=1,<br>    pickable=True,<br>    extruded=True,<br>)</pre><p>Az épületeket kiemeljük a térből (extruded=True), a magasságukat a height oszlopból vesszük. Színnek egy látványos narancssárgát választottam, fehér kerettel, hogy &quot;cyberpunk&quot; hatást keltsen a sötét térképen.</p><h3>13. A kamera beállítása</h3><p>Hová nézzen a térkép, amikor megnyitjuk?</p><pre># Camera setup<br>center_meters = gdf.geometry.centroid.iloc[0]<br>center_point = gpd.GeoSeries([center_meters], crs=gdf.crs).to_crs(epsg=4326).iloc[0]<br><br>view_state = pdk.ViewState(<br>    latitude=center_point.y,<br>    longitude=center_point.x,<br>    zoom=12.5,     # Lower value = larger area visible (try 12 or 13)<br>    pitch=45,<br>    bearing=15<br>)</pre><p>Kiszámítjuk az adathalmaz közepét. Trükkös rész: először méterben számoljuk a közepet (mert az pontosabb), majd ezt az egy pontot váltjuk át fokká a kamerának. Beállítjuk a dőlésszöget (pitch) és a forgatást (bearing), hogy valódi 3D élményt kapjunk.</p><h3>14. Renderelés HTML fájlba</h3><p>Összerakjuk a rétegeket és elmentjük az eredményt.</p><pre># Render<br>r = pdk.Deck(<br>    layers=[shadow_layer, building_layer],<br>    initial_view_state=view_state,<br>    map_style=&quot;mapbox://styles/mapbox/dark-v10&quot;,<br>    tooltip={&quot;text&quot;: &quot;Height: {height:.1f}m&quot;}<br>)<br><br># Save to file<br>filename = &quot;London_Solar.html&quot;<br>r.to_html(filename)</pre><p>A pdk.Deck objektumban egyesítjük az árnyékokat és az épületeket. Fontos a sorrend: először az árnyék, utána az épület, hogy a ház ráüljön az árnyékra. A térkép stílusát sötétre (dark-v10) állítjuk, hogy a fények jobban érvényesüljenek.</p><h3>15. Az eredmény megtekintése</h3><p>Végül automatikusan megnyitjuk az elkészült interaktív térképet a böngészőben.</p><pre># Open in browser<br>path = os.path.abspath(filename)<br>print(f&quot;Opening visualization: {filename}&quot;)<br>webbrowser.open(f&#39;file://{path}&#39;)</pre><p>Ez a kódrészlet megkeresi a fájl abszolút elérési útját a gépeden, és megnyitja az alapértelmezett böngésződben. Íme, London 3D-ben, valós idejű árnyékokkal!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc46e8951f45" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>