<?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 Mohamed Hasan on Medium]]></title>
        <description><![CDATA[Stories by Mohamed Hasan on Medium]]></description>
        <link>https://medium.com/@eng-mhasan?source=rss-1074291f25ec------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*C10Q7_RA5aymV31OEtD3PA.jpeg</url>
            <title>Stories by Mohamed Hasan on Medium</title>
            <link>https://medium.com/@eng-mhasan?source=rss-1074291f25ec------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 08:10:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@eng-mhasan/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[Grounded-SAM in 2026: Why It Still Matters (Even in the SAM3 Era)?]]></title>
            <link>https://eng-mhasan.medium.com/grounded-sam-in-2026-why-it-still-matters-even-in-the-sam3-era-15315532365a?source=rss-1074291f25ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/15315532365a</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[segmentation]]></category>
            <category><![CDATA[autonomous-cars]]></category>
            <category><![CDATA[object-detection]]></category>
            <dc:creator><![CDATA[Mohamed Hasan]]></dc:creator>
            <pubDate>Sat, 03 Jan 2026 23:56:52 GMT</pubDate>
            <atom:updated>2026-01-04T14:01:05.408Z</atom:updated>
            <content:encoded><![CDATA[<p>When the first Segment Anything Model (SAM) was released, it changed the way we approach image segmentation. Suddenly, we had a general-purpose model capable of segmenting almost anything using prompts of points or bounding boxes. However, text-prompted segmentation was missing whether in SAM or SAM2.</p><p><strong>Grounded-SAM</strong> introduced a nice work-around solution using Grounding DINO + SAM/SAM2. With<em> </em>few <strong><em>modifications to the original pipeline</em></strong>, I managed to segment and analyze massive volumes of road images with text-prompted segmentation e.g. “road”, “vehicle” or “person”.</p><p>Recently Meta released <strong>SAM3 with native text prompts</strong>. This raised the question: Does Grounded-SAM still matter? Should I even write about it? I will address these points, explaining my work on text-driven segmentation with Grounded-SAM which surprisingly still matters.</p><h3>Grounded SAM</h3><p>Grounded SAM is an open-vocabulary <strong><em>detection and segmentation</em> </strong>pipeline that combines two strong open-set foundational models: Grounding DINO and SAM.</p><p><strong>Grounding DINO</strong> is an open-set object detector that can detect any objects using text prompts. The model was trained on over 10 million images, including detection data, visual grounding data, and image-text pairs. It has a strong <strong><em>zero-shot</em></strong> detection performance.</p><p><strong>Segment Anything Model (SAM) </strong>is an open-world segmentation model that can “cut out” objects in images with proper prompts, like points, boxes, or text. It has been trained on over 11 million images and 1.1 billion masks. Despite of its strong <strong><em>zero-shot</em></strong> performance, the released SAM and SAM2 cannot identify the masked objects based on arbitrary text inputs.</p><h3><strong>My Custom Grounded-SAM Pipeline</strong></h3><p>I built an <strong>Interface layer</strong> between GroundingDINO and SAM to make text-driven segmentation reliable in practice. GroundingDINO takes text prompts as input and produces bounding boxes with associated textual phrases. However, in real deployments, <em>these output phrases are often noisy or inconsistent</em>.</p><p>For example, when using a prompt like “car”, the model may return correct bounding boxes but attach phrases such as “car truck”, “car car”, or even “car car car”. While the detections themselves are valid, this variability in textual outputs makes downstream processing brittle if left unhandled.</p><p>To address this, I designed a <strong>custom pipeline with the interface layer</strong> as follows:</p><ul><li>Define <strong>M</strong>, the set of <em>main target classes</em> (e.g. <em>road</em>, <em>vehicle</em>, <em>sidewalk</em>, etc).</li><li>Define <strong>E</strong>, an <em>extended set of target classes</em> that includes likely textual variations and composites (e.g. <em>road</em>, <em>car</em>, <em>bus</em>, <em>truck</em>, <em>car truck</em>, <em>footpath sidewalk</em>, etc).</li><li>Run <strong>GroundingDINO</strong> using the extended class set <strong>E</strong> as text prompts.</li></ul><pre># detect objects<br>detections, phrases = grounding_dino_model.predict_with_classes(<br>            image=image,<br>            classes=E)</pre><ul><li>Filter and normalize the predicted text phrases by mapping them back to <strong>E</strong> using text-similarity matching (a lightweight approach such as SequenceMatcher is sufficient).</li><li>Use the bounding boxes associated with the filtered and normalized classes as prompts for <strong>SAM</strong> to generate segmentation masks.</li></ul><pre># convert detections to masks<br>detections.mask = segment(<br>    sam_predictor=sam_predictor,<br>    image=cv2.cvtColor(image, cv2.COLOR_BGR2RGB),<br>    xyxy=detections.xyxy)</pre><ul><li>Finally, map the resulting SAM outputs back to the main class set <strong>M</strong>.</li></ul><p>The interface layer significantly improves robustness, enabling consistent class labeling while retaining the flexibility of open-vocabulary detection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*36Xleb1C7B0_qcvMUqG6KQ.jpeg" /><figcaption><strong>Pipeline of the Custom Grounded-SAM</strong></figcaption></figure><h3>Why I Built this Pipeline?</h3><p>Having a stable and modular solution with well-tested components is required in production in areas like:</p><ul><li>Road analytics and asset mapping</li><li>Driving scene understanding</li><li>Visual infrastructure surveys</li><li>Robotics perception</li></ul><p>This pipeline efficiently provided text-prompted segmentation on SAM and SAM2 long before SAM3 existed.</p><h3>Why it still Matters even with SAM3?</h3><p>Even though SAM3 introduced text prompting, the industry hasn’t instantly moved away from SAM/SAM2.</p><ul><li>Lightweight, modular pipelines win in real deployments</li><li>Open-vocabulary detection remains crucial for fine-grained control</li><li>SAM3 doesn’t yet solve every problem Grounded-SAM solved (lighter pipeline - detection + segmentation - license issues in production)</li></ul><h3>References</h3><ul><li>The main paper explaining Grounded-SAM is “<a href="https://arxiv.org/pdf/2401.14159">Grounded SAM: Assembling Open-World Models for Diverse Visual Tasks</a>”.</li><li>For implementation, I mainly used the repos from <a href="https://github.com/IDEA-Research">IDEA-Research</a> for this project, namely <a href="https://github.com/IDEA-Research/Grounded-Segment-Anything">Grounded-Segment-Anything</a> and <a href="https://github.com/IDEA-Research/Grounded-SAM-2">Grounded-SAM-2</a> employing SAM and SAM2 models repectively.</li></ul><p>I believe this solution still fills a practical gap for most real-world computer vision pipelines today, and is far from obsolete. Would love to hear your thoughts, especially if you’re using text prompts in vision pipelines!</p><blockquote><a href="https://www.linkedin.com/in/drmhasan/">LinkedIn</a><br><a href="https://github.com/m-hasan-n">GitHub</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15315532365a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Multimodal LLM Pipeline for Video Understanding]]></title>
            <link>https://eng-mhasan.medium.com/a-multimodal-llm-pipeline-for-video-understanding-b1738304f96d?source=rss-1074291f25ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1738304f96d</guid>
            <category><![CDATA[video-understanding]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[multimodal-ai]]></category>
            <dc:creator><![CDATA[Mohamed Hasan]]></dc:creator>
            <pubDate>Wed, 18 Jun 2025 16:28:02 GMT</pubDate>
            <atom:updated>2025-06-18T16:31:59.423Z</atom:updated>
            <content:encoded><![CDATA[<p>Artificial intelligence has made major steps in processing modalities like text, images, and speech independently. But humans don’t learn from isolated data — we <strong>see, hear, and interpret simultaneously</strong>.</p><p>This tutorial is a small step towards <strong>multimodal AI</strong> — where models understand the world through <strong>both vision and language</strong>. Using the power of <strong>large language models (LLMs)</strong>, I built a lightweight pipeline that takes a video and produces a human-like summary based on <strong>what’s seen and heard</strong>.</p><blockquote>🔗 Try it in <a href="https://github.com/m-hasan-n/Tutorials/blob/main/MultiModal/Video_Understanding.ipynb">Google Colab</a></blockquote><h3>The Goal</h3><p>Building an intelligent system that:</p><ul><li>Accepts a short video clip as input</li><li>Understands both <strong>visual scenes</strong> and <strong>spoken content</strong></li><li>Produces a <strong>natural-language summary</strong> using a large language model</li></ul><h3>Multimodal AI: Why It Matters</h3><p>Multimodal AI is about integrating multiple streams of information — such as <strong>images, audio, and text</strong> — into a unified understanding. It reflects how humans perceive and reason, and it’s central to applications like:</p><ul><li>Video summarization</li><li>AI assistants</li><li>Human-robot interaction</li><li>Healthcare and surgery automation</li></ul><p>In this project, vision, audio, and language are combined in one intelligent pipeline, using LLMs not just as generators of text, but as <strong>reasoning engines that integrate modalities</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*KtR6RgMe5gxqtNFhU5Gg7A.png" /><figcaption><strong>Pipeline overview.</strong></figcaption></figure><h3>Pipeline</h3><ul><li><strong>Input</strong>: a short video clip .</li></ul><pre># Load video using moviepy.editor<br>import moviepy.editor as mp<br>clip = mp.VideoFileClip(video_path)</pre><ul><li><strong>Frame Extraction</strong>: keyframes are extracted to capture visual highlights.</li></ul><pre># Extract a frame every 2 seconds.<br>from PIL import Image<br>skip=2<br>extracted_frames = []<br>for t in range(0, int(clip.duration), skip):<br>  frame = clip.get_frame(t)<br>  img = Image.fromarray(frame)<br>  extracted_frames.append(img)</pre><ul><li><strong>Audio Extraction:</strong> separate the audio track for transcription.</li></ul><pre>import ffmpeg, torchaudio<br><br># Use ffmpeg to extract audio directly into memory as bytes<br>def extract_audio_from_video(video_path, sr=16000):<br>    out, _ = (<br>        ffmpeg<br>        .input(video_path)<br>        .output(&quot;pipe:&quot;, format=&quot;wav&quot;, ac=1, ar=sr)<br>        .run(capture_stdout=True, capture_stderr=True)<br>    )<br>    audio_tensor, sample_rate = torchaudio.load(io.BytesIO(out))<br>    return audio_tensor.squeeze(0), sample_rate</pre><ul><li><strong>Audio Transcription</strong>: OpenAI’s <strong>Whisper </strong>converts audio into text.</li></ul><pre># Load Whisper Automayic Speech Recognition model via HF pipeline<br>asr = pipeline(&quot;automatic-speech-recognition&quot;, model=&quot;openai/whisper-small&quot;)<br><br># Transcribe<br>transcription = asr(audio_tensor.numpy(), return_timestamps=True)</pre><ul><li><strong>Image Captioning</strong>: A vision-language model (<strong>BLIP</strong>) generates descriptions of each frame.</li></ul><pre>from transformers import BlipProcessor, BlipForConditionalGeneration<br><br># load the pretrained BLIP caption model and caption processor<br>caption_model = BlipForConditionalGeneration.from_pretrained(&quot;Salesforce/blip-image-captioning-base&quot;).to(device)<br><br>caption_processor = BlipProcessor.from_pretrained(&quot;Salesforce/blip-image-captioning-base&quot;)<br><br># captions of the extracted key frames<br>for img in extrated_frames:<br>    inputs = caption_processor(images=img, return_tensors=&quot;pt&quot;).to(device)<br>    out = caption_model.generate(**inputs)<br>    caption = caption_processor.decode(out[0], skip_special_tokens=True)<br>    frame_captions.append(caption)</pre><ul><li><strong>Filter Unique Captions:</strong> compute <strong>sentence embeddings</strong> of the frame captions and <strong>remove similar ones</strong>.</li></ul><pre>from sentence_transformers import SentenceTransformer, util<br><br>model = SentenceTransformer(&quot;all-MiniLM-L6-v2&quot;)<br>embeddings = model.encode(frame_captions, convert_to_tensor=True)<br>sim_threshold = 0.9<br><br>unique_captions = []<br>for i, emb in enumerate(embeddings):<br>    if not any(util.pytorch_cos_sim(emb, e) &gt; sim_threshold for e in model.encode(unique_captions, convert_to_tensor=True)):<br>        unique_captions.append(frame_captions[i])</pre><ul><li><strong>Multimodal Reasoning with Microsoft Phi-2 Model</strong>: the <strong>LLM receives both image captions and audio transcription</strong> and produces a <strong>unified summary</strong> that reflects understanding across modalities.</li></ul><pre>from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline<br><br># Load Phi-2 model and tokenizer<br>model_id = &quot;microsoft/phi-2&quot;<br><br>tokenizer = AutoTokenizer.from_pretrained(model_id)<br>model = AutoModelForCausalLM.from_pretrained(<br>    model_id,<br>    device_map=&quot;auto&quot;,<br>    torch_dtype=&quot;auto&quot;<br>)<br><br># Construct the prompt<br>prompt = f&quot;&quot;&quot;### Instruction:<br>Summarize the video using both the visual description and spoken transcript.<br><br>Visual Description: {&#39;; &#39;.join(unique_captions)}<br><br>Spoken Transcript: {transcription[&#39;text&#39;]}<br><br>Video Summary:&quot;&quot;&quot;<br><br># Generate output<br>pipe = pipeline(&quot;text-generation&quot;, model=model, tokenizer=tokenizer, max_new_tokens=150)</pre><h3>Sample Input</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7X4G7iiQTFy_mmJPKjx1Vw.png" /></figure><h3>Sample Output</h3><blockquote><em>“Video Summary: A man is fixing a car tire with a sealant bottle and a compressor. He is also inflating the tire using the compressor. He suggests rolling the car forward to help the sealant spread around if the tire is not inflating properly.”</em></blockquote><h3>Notes</h3><ul><li>Keyframes can be detected from the video to represent a <strong>scene change</strong> or a <strong>visual transition</strong>. I tried here a different approach by conditioning on the image <strong>caption embeddings</strong>.</li><li>The <strong>prompt </strong>used to summarize the video can be <strong>engineered to fit your</strong> <strong>application </strong>e.g. “Write a clinical report summary based on …”</li><li>This simple pipeline can be <strong>advanced </strong>in many ways:<br>- Support for <strong>longer-form videos</strong> using temporal segmentation.<br>- Summarization in a <strong>style </strong>(e.g. clinical reports, or educational scripts).<br>- Integrating object <strong>tracking </strong>for more dynamic visual understanding.</li></ul><h3>Key Takeaways</h3><ul><li><strong>Multimodal pipelines boost AI capability</strong> — the combination of vision and speech adds more depth.</li><li><strong>LLMs are more than language tools</strong> — they can reason over structured and unstructured data from diverse sources.</li><li><strong>Prompt design</strong> matters — guiding Phi-2 to weigh both visual and audio context leads to more balanced and meaningful outputs.</li></ul><h3>Final Thoughts</h3><p>This demo reflects my broader interest to <strong>make LLMs interact with the real world, beyond static text </strong>— toward systems that can see, hear, and understand. I’d love to connect with others exploring multimodal AI, applied LLMs, and real-world perception systems.</p><blockquote><em>Feel free to reach out, share your thoughts, or ask about the code and design choices behind the scene.</em></blockquote><blockquote><a href="https://github.com/m-hasan-n/Tutorials/tree/main/MultiModal">Code on GitHub</a></blockquote><blockquote><a href="https://www.linkedin.com/in/drmhasan/">My LinkedIn</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1738304f96d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OCR with Deep Learning in PyTorch (Low Resolution OCR in the Wild)]]></title>
            <link>https://eng-mhasan.medium.com/ocr-with-deep-learning-in-pytorch-95a347e2ef29?source=rss-1074291f25ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/95a347e2ef29</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Mohamed Hasan]]></dc:creator>
            <pubDate>Fri, 12 May 2023 21:16:15 GMT</pubDate>
            <atom:updated>2023-05-19T17:33:40.527Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 3: Recognizing Low-Resolution Text Images in the Wild</h4><p>This is the last part of the series explaining Optical Character Recognition OCR with deep learning. <a href="https://eng-mhasan.medium.com/ocr-with-deep-learning-in-python-e443970d09e4">The first part</a> introduced the topic with Python implementation, whereas <a href="https://eng-mhasan.medium.com/ocr-with-deep-learning-in-pytorch-b8a481c604fc">the second part</a> presented more advanced scene text recognition methods.</p><p>In this part, we will discuss the challenges of low-resolution text images that are often seen in natural scenes. Scene texts are of arbitrary shapes, distributed illumination, and different backgrounds, which makes the recognition even harder at the low resolution.</p><h3>Introduction</h3><p>The performances of most OCR methods drop sharply when recognizing low-resolution (LR) text images. This is because the shape of LR characters is extremely blurred due to optical degradation. The following figure shows examples of such degradation. Try to guess the text inside the images before reading the answer below!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*qJU4O2EQ7TnsPXTFI_ZdYQ.png" /><figcaption>Hard examples of low-resolution text images.</figcaption></figure><p>As you can see, it is even hard for a human to recognize the text in such images (2018, CONSTRUCTION, Nutrition, author). It is straightforward then to think of boosting the image resolution before text recognition. The line of research working on this problem is called Super Resolution (SR).</p><p><strong>Super Resolution</strong> aims at generating a high-resolution (HR) image consistent with a given low-resolution input. Traditional approaches employed filters (e.g. bilinear or bicubic) which generate a HR output for each pixel by interpolating the colors of its neighbors. Deep learning SR is casted as a regression problem, where the input is the LR image, and the output is the HR image. A deep network is thus trained on pairs of LR input and HR target to minimize some distance metric between the prediction and groundtruth.</p><p>The question now is how to collect/generate such pairs of LR and HR images? There are <em>two main types of datasets</em> used to train and evaluate SR networks. In the first type, LR images are synthesized by a down-sample interpolation or Gaussian blur filtering of given HR images. This kind of uniform degradation isn’t enough to generalize the real LR in the wild, as real blur scene text images are more varied in degradation formation.</p><p>Datasets of the other type are collected through capturing LR-HR image pairs by adjusting the focal length of the cameras. This generates real (not synthesized) LR text images. Thus, models trained on such datasets can better generalize to real scene challenges.</p><p>We will go through one of these challenging datasets (<em>TextZoom</em>) and the model (<em>TSRN</em>) trained to predict texts in such LR images.</p><h3>TextZoom</h3><p>This can be considered as the first real text SR dataset. TextZoom contains paired LR and HR text images of the same text content. Images are captured by cameras with different focal lengths in the wild, that is more authentic and challenging than synthetic data. The next figure compares the synthetic vs the real LR text images, where it is clear that the real LR images are much more challenging than the synthetic ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y8LmnayLYVBoYmcxXA_LqA.png" /><figcaption>Comparison between synthetic LR, real LR, and HR images in TextZoom. ‘Syn LR’ denotes BICUBIC down-sampled image of HR. ‘Real LR’ and ‘HR’ denotes LR and HR images captured by camera with different focal lengths.</figcaption></figure><p>TextZoom is well annotated by providing the direction, the text content and the original focal length of the text images. The dataset contains abundant text from different natural scenes, including street views, libraries, shops, vehicle interiors and so on. Text images are divided into three subsets based on difficulty: easy, medium and hard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/0*YZPEM2D10Wvt8_TJ" /><figcaption>Subsets of TextZoom data based on difficulty.</figcaption></figure><p>More details of the dataset collection and statistics can be found in the <a href="https://arxiv.org/pdf/2005.03341.pdf">paper</a>.</p><h3>TSRN</h3><p>Text Super-Resolution Network (TSRN) is a text-oriented end-to-end model trained to reconstruct LR text images. The input to the model is the LR image, and the output is the HR result. The pipeline of the TSRN is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w9qIWZoCgIawbQ0sLv9YOA.png" /><figcaption>Overview of TSRN model.</figcaption></figure><p>The pipeline can be explained through the following steps:</p><ul><li>The LR input (RGBM) is a concatenation of RGB channels with a binary mask.</li><li>The RGBM input is rectified by the central alignment module (<em>Align</em>). This modules solve the problem of misalignment of the paired images.</li><li>CNN layers are then applied to extract shallow features from the rectified image.</li><li>A stack of five Sequential Residual Blocks (SRBs) extract deeper and sequential dependent feature. As shown above each SRB includes convolutional layers (CNN to extract the deeper image features) and recurrent layers (bi-directional LSTM to extract the sequential features). A residual skip connection similar to ResNet is also used.</li><li>The SR images are finally generated by up-sampling block and CNN.</li><li>The output is a super-resolved RGB image.</li></ul><p>The output of the network is supervised by MSE Loss (L2) and gradient profile loss (LGP) which is a boundary-aware loss term designed to reconstruct the sharp boundary of the characters.</p><h3>Code</h3><p>TextZoom dataset and TSRN code can be accessed from <a href="https://github.com/WenjiaWang0312/TextZoom">this GitHub repo</a>. Follow the instructions on there to install the requirements and download the data and/or pre-trained models. You can easily train and test TSRN model in addition to other architectures (CRNN, ASTER, MORAN).</p><p>I tested TSRN on the hard images shown at the first figure in this article, and got the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*b9jU6ukk70STxKBeFUmiPw.png" /><figcaption>Testing TSRN on images from the hard subset of TextZoom.</figcaption></figure><p>The left column shows the LR input images, whereas the middle column shows the HR groundtruth images with groundtruth text above each image. The SR images restored from TSRN are shown in the right column, where the predicted text is written above each image.</p><p>If you want to run a demo of TSRN on your images, you need to run the following:</p><pre>python main.py --demo --demo_dir=&#39;./images/&#39;  --resume=&#39;your-model.pth&#39; --STN --mask</pre><h3>Conclusions</h3><p>Recognizing low-resolution text images in the wild is a challenging task. This is mainly due to the optical degradation of text characters in natural images at such LR. It is intuitive then to boost the resolution of such images before text recognition. TSRN is a text-oriented end-to-end model that jointly outputs high-resolution text images and predict the characters inside. The model is trained on TextZoom, a dataset of paired LR and HR text images that were captured by cameras with different focal lengths in the wild. Testing TSRN on the hard examples of TextZoom verifies the effectiveness of this approach. The results also clarify its limitations with severely hard images.</p><p>To integrate this framework into your work and get better results, you will need to train/fine-tune these models on your images. If you have any questions, please write in the comments.</p><h3>References</h3><p><a href="https://arxiv.org/pdf/2005.03341.pdf"><strong>Paper</strong></a></p><p><a href="https://github.com/WenjiaWang0312/TextZoom"><strong>Code</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95a347e2ef29" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OCR with Deep Learning in PyTorch (Recognizing Irregular Text)]]></title>
            <link>https://eng-mhasan.medium.com/ocr-with-deep-learning-in-pytorch-b8a481c604fc?source=rss-1074291f25ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8a481c604fc</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ocr]]></category>
            <dc:creator><![CDATA[Mohamed Hasan]]></dc:creator>
            <pubDate>Mon, 08 May 2023 12:23:00 GMT</pubDate>
            <atom:updated>2023-05-19T17:32:37.315Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 2: Advanced Scene Text Recognition</h4><p>This is the second tutorial of the series explaining Optical Character Recognition OCR with deep learning. <a href="https://eng-mhasan.medium.com/ocr-with-deep-learning-in-python-e443970d09e4">The first part</a> of this series introduced the topic with Python code implementation. In this part, we will go through more advanced scene text recognition methods.</p><h4>Introduction</h4><p>Scene text recognition is essential in several computer vision tasks such as traffic sign reading, product recognition, intelligent inspection, and image searching. In spite of the success of Convolutional CNN and Recurrent RNN neural networks in advancing OCR, the simple recognition methods do not address the challenges of <em>irregular </em>text inside images. The following figure compares regular (horizontal and frontal) vs irregular texts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*0DrCG57Z5Gj1b8u3ueG6Gg.png" /><figcaption>Examples of regular and irregular scene text. (a) Regular (b) Slanted and perspective text. (c) Curved text. This is Figure 1 in MORAN paper.</figcaption></figure><p>Irregular text widely appear in natural scenes. However, it is difficult to recognize due to the large variance in its shapes and distorted patterns. The following figure depicts more instances of irregular texts, which are typical cases of oriented, perspective and curved texts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*th9A1Jt1kACuh4Rlmza4-A.png" /><figcaption>Examples of irregular text (Figure 1 of ASTER paper).</figcaption></figure><p>Several techniques have been introduced to tackle the aforementioned challenges of irregular text recognition. The basic idea behind tackling these challenges is to rectify the image before text recognition. Image rectification helps to transform the irregular text into an easier regular one. In this tutorial, we will go through two of such methods of scene text recognition: Attentional Scene TExt Recognizer with flexible rectification (<em>ASTER</em>) and Multi-Object Rectified Attention Network (<em>MORAN</em>).</p><h4>ASTER</h4><p>ASTER tackles the irregular text problem with an explicit rectification mechanism. As depicted in the next figure, the model comprises two parts: the rectification network and the recognition network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*7pPUL5KlwsHXBu657CrwAA.png" /><figcaption>Overview of ASTER model (dashed lines show the flow of gradients).</figcaption></figure><p>Given an input image, the <em>rectification network</em> transforms the image to rectify the text inside it. The resulting rectified image is passed to the <em>recognition network</em> that predicts the output character sequence.</p><p>More specifically, the <strong><em>rectification network</em></strong> is trained to predict the transformation parameters required to rectify the irregular text into a regular version. During inference, the rectification network predicts the transformation parameters and apply them to the image as shown in the next figure. This network is based on Thin Plate Spline (TPS) transformation and the Spatial Transformer Networks (STN) framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*lp2a6oyiejWNEmiUtjQ0vg.png" /><figcaption>TPS transformation of irregular texts. The green + show the control points used to estimate the transformation parameters. For more details, check ASTER paper.</figcaption></figure><p>The <strong><em>recognition network</em></strong> predicts a character sequence directly from the rectified image in an attentional sequence-tosequence manner. The following figure depicts the structure of model following the classical sequence-to-sequence architectures consisting of an encoder and a decoder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*xUXeD4zgXpL4C2eftQaJJw.png" /><figcaption>Structure of the basic text recognition network.</figcaption></figure><p>The <em>sequence-to-sequence</em> model translates the feature sequence output by the encoder into a character sequence output by the decoder. The encoder takes the rectified image as its input, to which it applies the CNNs (ConvNet above) to extract the image features. These features are sent to the Bi-directional LSTM (BLSTM) that maps/encodes them into a sequence. The decoder transforms the features sequence output from the encoder into a sequence of characters (text) of arbitrary lengths. For more details (including the attention mechanism), you may check the ASTER paper.</p><h4>ASTER Code</h4><p>ASTER is built with PyTorch and the code is available <a href="https://github.com/ayumiymk/aster.pytorch">here on GitHub</a> . After cloning the repo and installing the required packages, head to the <a href="https://github.com/bgshih/aster#demo">demo </a>section, where you can test the code on your images. First, you need to download the pre-trained models from the <a href="https://github.com/bgshih/aster/releases">release page</a>. Then edit <em>config.py </em>to set the relevant parameters e.g. path to the model, path to your images, etc. Finally, run the following command from the terminal:</p><pre>python aster/demo.py</pre><h4>MORAN</h4><p>MORAN was presented to read rotated, scaled and stretched characters in different scene texts. Similar to ASTER, it consists of two parts: a multi-object rectification network (<em>MORN</em>) to rectify images, and an attention-based sequence recognition network (<em>ASRN</em>) to read the text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*qlrUDkD3lNxooR7_KDclDA.png" /><figcaption>Overall structure of MORAN.</figcaption></figure><p>In contrast to ASTER, the rectification introduced inside the <strong><em>MORN </em></strong>network is not based on geometric constraints/transformation. The rectification network in MORN employs convolutional layers (along with the pooling, batch normalization and ReLU) to predict the offset of each part of the image. The next figure shows example rectification results with the computed offsets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*3jrIRu2fdTVTP6MssK6uZw.png" /><figcaption>The input images are shown on the left and the resulting rectified images are shown on the right. The heat maps at the middle visualize the computed offset maps</figcaption></figure><p>Similar to ASTER, the structure of the recognition network <strong><em>ASRN </em></strong>is a CNN-BLSTM encoder-decoder framework with an attention mechanism. However, Gated Recurrent Units (GRUs) are used instead of LSTMs to build the decoder. For more details (including the fractional pickup), please check the paper.</p><h4>MORAN Code</h4><p>MORAN is also built with PyTorch and the code is <a href="https://github.com/Canjie-Luo/MORAN_v2">available on GitHub</a>. Follow the instructions on the page to clone the repo and install the requirements. Then, download the pretrained model <em>demo.pth </em>to your local drive. Modify <em>model_path </em>and <em>img_path </em>in <em>demo.py</em> before running the following from your terminal:</p><pre> python demo.py</pre><h3>Conclusions</h3><p>For regular text recognition, you can use the <a href="https://eng-mhasan.medium.com/ocr-with-deep-learning-in-python-e443970d09e4">EasyOCR code explained in the first part</a> of this series. However, recognition of irregular texts in natural scenes is challenging due to the large variance of distortions in the text shapes and patterns. We have reviewed two of the techniques tackling such challenges: ASTER and MORAN. Both methods solve the task through two separate networks: rectification and recognition. The rectification network rectifies the image batch of the text before passing the result to the recognition network, which is structured as an encoder-decoder framework with attention. You are encouraged to test the codes of ASTER and MORAN on several images before deciding the best choice for your business.</p><p>The <strong><em>next part</em></strong> of this series will handle the severe case of text recognition in the wild (also with PyTorch in Python).</p><h3>References</h3><p><a href="https://ieeexplore.ieee.org/abstract/document/8395027">ASTER paper</a>.</p><p><a href="https://github.com/ayumiymk/aster.pytorch">ASTER on GitHub.</a></p><p><a href="https://arxiv.org/pdf/1901.03003.pdf">MORAN paper</a>.</p><p><a href="https://github.com/Canjie-Luo/MORAN_v2">MORAN on GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8a481c604fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OCR with Deep Learning in PyTorch (EasyOCR)]]></title>
            <link>https://eng-mhasan.medium.com/ocr-with-deep-learning-in-python-e443970d09e4?source=rss-1074291f25ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/e443970d09e4</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[easyocr]]></category>
            <category><![CDATA[ocr]]></category>
            <dc:creator><![CDATA[Mohamed Hasan]]></dc:creator>
            <pubDate>Sun, 30 Apr 2023 23:42:19 GMT</pubDate>
            <atom:updated>2023-05-19T17:31:49.108Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 1: A Beginner Guide of OCR with Python Code</h4><h4>1. Introduction</h4><p>If your business workflow involves extracting text from images, you need a process called Optical Character Recognition (OCR). This is the extraction and recognition of text from images such as scanned documents, camera images, image-only pdfs, posters, street signs or receipts.</p><p>Modern OCR uses machine learning techniques to train computers to read the text inside images. Specifically, deep Neural Networks (NN) are trained to analyze the text in images over many levels, and combine that to get the final text result as a sequence of characters. In general, two types of networks are required: 1) a network to extract features from the images e.g. Convolutional NN (CNN), and 2) a network to generate the output sequence of characters e.g. Recurrent NN (RNN).</p><p>Next, we briefly outline <strong><em>EasyOCR</em></strong>, one of the most straightforward Python packages for text recognition. Then, a simple Python code implementation is explained.</p><h4>2. EasyOCR</h4><p>Ready-to-use OCR package with 80+ supported languages and all popular writing scripts including: Latin, Chinese, Arabic, etc. All deep learning execution is based on PyTorch. The following framework outlines the pipeline of the package:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*lsRINnDDR3PY9gYU" /></figure><p>As shown, the project is based on research and code from several papers (e.g. CRAFT and CRNN) and open-source repositories. <a href="https://arxiv.org/pdf/1507.05717.pdf"><strong><em>CRNN</em></strong></a><strong><em> </em></strong>combines convolutional and recurrent neural networks. The network architecture consists of three parts: 1) <em>convolutional</em> layers, which extract a feature sequence from the input image; 2) <em>recurrent</em> layers, which predict a label distribution for each frame; 3) <em>transcription </em>layer, which translates the per-frame predictions into the final label sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*zeqBrP_Kqt5ellyCGjnIqw.png" /><figcaption>CRNN network architecture (LSTM in the recurrent layer stands for Long Short-Term Memory, and is a common example of RNNs).</figcaption></figure><h4>3. Code</h4><p>The following lines of code recognize the text(s) existing in a given image (image_filename) and display the results:</p><pre>import cv2<br>import easyocr<br>import matplotlib.pyplot as plt<br><br># This needs to run only once to load the model into memory<br>reader = easyocr.Reader([&#39;en&#39;])<br><br># reading the image<br>img = cv2.imread(image_filename)<br><br># run OCR<br>results = reader.readtext(img)<br><br># show the image and plot the results<br>plt.imshow(img)<br>for res in results:<br>    # bbox coordinates of the detected text<br>    xy = res[0]<br>    xy1, xy2, xy3, xy4 = xy[0], xy[1], xy[2], xy[3]<br>    # text results and confidence of detection<br>    det, conf = res[1], res[2]<br>    # show time :)<br>    plt.plot([xy1[0], xy2[0], xy3[0], xy4[0], xy1[0]], [xy1[1], xy2[1], xy3[1], xy4[1], xy1[1]], &#39;r-&#39;)<br>    plt.text(xy1[0], xy1[1], f&#39;{det} [{round(conf, 2)}]&#39;)</pre><p>The code starts by importing the required packages (<em>opencv </em>to read the image, <em>easyocr </em>for the main job and <em>matplotlib </em>to show the results). The pre-trained model that will be used for text recognition is loaded into memory by <em>easyocr.Reader(), </em>where we choose <em>‘en’</em> to set the required language to English. In case you plan to run this script on several images, please note that this line needs to be run only once.</p><p>After reading the image into <em>img (</em>using <em>cv2.imread()</em>), <em>reader.readtext</em> runs OCR to detect and recognize all instances of text inside the image. The output is saved into a list of detections (<em>results</em>). We then show the image (using <em>plt.imshow()</em>) before displaying the detected text(s).</p><p>For each detection <em>res </em>in <em>results, </em>the first item <em>res[0] </em>represents the <em>xy </em>image<em> </em>coordinates of the bounding box containing the detected text. The next two items <em>res[1]</em> and <em>res[2]</em> represent the detected text and confidence of detection, respectively. The last two lines of the code plots a red rectangle around each text detection, and prints the text and detection confidence at the top left corner of the rectangle.</p><h4>References</h4><p><a href="https://github.com/JaidedAI/EasyOCR">EasyOCR on GitHub</a>.</p><p><a href="https://arxiv.org/pdf/1507.05717.pdf">CRNN Paper.</a></p><p>OCR by <a href="https://learn.microsoft.com/en-us/azure/cognitive-services/computer-vision/overview-ocr">Microsoft</a>, <a href="https://www.ibm.com/cloud/blog/optical-character-recognition">IBM</a> and <a href="https://aws.amazon.com/what-is/ocr/">Amazon</a>.</p><p>Stay tuned for the next tutorial explaining more advanced OCR (with Python implementation).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e443970d09e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pooling Strategies in Vehicle Trajectory Prediction]]></title>
            <link>https://eng-mhasan.medium.com/pooling-strategies-in-vehicle-trajectory-prediction-77b566221c8d?source=rss-1074291f25ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/77b566221c8d</guid>
            <dc:creator><![CDATA[Mohamed Hasan]]></dc:creator>
            <pubDate>Fri, 23 Dec 2022 21:48:31 GMT</pubDate>
            <atom:updated>2022-12-23T21:48:31.184Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the second post in a series covering several topics on trajectory prediction using LSTM generative models. The series summarizes a number of recent publications of my work at the Institute for Transport Studies, University of Leeds. This should be useful for researchers and machine learning engineers working on vehicle (pedestrian) trajectory prediction. At the resources section, interested readers can find links to research papers and code on GitHub. The previous posts:</p><ul><li><a href="https://eng-mhasan.medium.com/vehicle-trajectory-prediction-using-lstm-encoder-decoder-models-d1163eb03f8c">Vehicle Trajectory Prediction using LSTM Encoder-Decoder Models.</a></li></ul><h3>Introduction</h3><p>A typical generative model was described in the <a href="https://eng-mhasan.medium.com/vehicle-trajectory-prediction-using-lstm-encoder-decoder-models-d1163eb03f8c">previous post</a>, with the following building blocks: (1) an LSTM encoder, (2) a pooling module, and an (3) LSTM decoder. This post covers the <strong>pooling module</strong> whose function is capturing the <strong>interaction</strong> among vehicles in a given scene. This is achieved by pooling the LSTM states of the <strong>neighbor</strong> vehicles around the <strong>ego</strong> vehicle. The output from this module is a pooling vector summarizing the information needed by the ego vehicle to make a maneuver decision.</p><h3>Pooling Strategies</h3><p>There are three main pooling strategies in the literature:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HsVSrSEoDqd1bLzQZtWz1Q.png" /><figcaption><strong>Fig 1</strong> Visualizing <strong>pooling mechanisms</strong> (A green vehicle shows the ego, a yellow vehicle shows a neighbor covered by the pooling strategy, and a grey vehicle shows a non-covered neighbor). Left: grid-based pooling, Center: global pooling, and Right: maneuver-based pooling.</figcaption></figure><h3>Grid-based Pooling</h3><p>A spatial grid is centered around the ego vehicle (Fig 1 Left). For example, the shown grid works for a highway environment where the ego vehicle (green) is at the center. The shown grid is designed to laterally cover three lanes (ego lane and the next right and left lanes). The grid is designed to covers a specific distance in the longitudinal direction as well. Each grid cell is assumed to include one vehicle.</p><p>A tensor is structured according to the grid design and populated with LSTM states of the ego and existing neighbor vehicles. This is called a <strong>social tensor</strong> and was used in <a href="http://vision.stanford.edu/pdf/alahi2016cvpr.pdf">Social LSTM</a> (S-LSTM) and <a href="https://arxiv.org/pdf/1805.06771.pdf">Convolutional Social Pooling</a> (CSP) works. In <strong><em>S-LSTM</em></strong>, a <em>fully connected and a SUM pooling</em> layers are applied to the social tensor to produce the pooling vector. In <strong><em>CSP</em></strong>, <em>convolutional and Max-pooling</em> layers are used to embed the LSTM states populated in the social tensor. The following figure shows how the social tensor (<em>taken from </em><a href="https://arxiv.org/pdf/1805.06771.pdf"><em>CSP paper</em></a>) is populated with states of four neighbor vehicles around the ego.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gPilRRePp25nvE2POCzb4g.png" /><figcaption><strong>Fig 2</strong> <strong>Social tensor</strong> used in the grid-based pooling. LSTM states of the ego and four neighboring vehicles are populated.</figcaption></figure><h3>Global Pooling</h3><p>In <a href="https://arxiv.org/pdf/1803.10892.pdf">Social GAN</a> (S-GAN) work, the authors argued that the previous grid-based pooling scheme is a hand-crafted solution that is slow and fails to capture global context. They proposed to concatenate the <em>relative position</em> between the ego and <strong>all its neighbors</strong> (Fig.1 center) with the LSTM state of each agent. The concatenated tensor is then processed independently by a Multi-Layer Perceptron and a Max-pooling layer. They proposed this scheme for pedestrian trajectory, which <a href="https://arxiv.org/pdf/2104.14079.pdf"><strong>we extended to vehicle trajectory prediction</strong></a> as shown in the next figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nJt-_Tpq1q0gfnCnqbGEVQ.png" /><figcaption><strong>Fig 3</strong> <strong>Global pooling</strong> mechanism. Relative position is computed with respect to the ego vehicle. The embeddings of the relative position and vehicle trajectory history for each vehicle are concatenated, before being applied to the pooling layers. Pooling layers here include Multi-Layer Perceptron and a Max-pooling.</figcaption></figure><h3>Maneuver-based Pooling</h3><p>This is <a href="https://arxiv.org/pdf/2104.14079.pdf">our recently proposed</a> pooling mechanism. Similar to S-GAN, we employ the <strong>global pooling</strong> scheme depicted in Fig 3. We do not restrict the neighborhood to the handcrafted structure of the spatial grid. However, we limit it by<strong> lateral and longitudinal distance thresholds </strong>(Fig 1 Right) around the ego vehicle, considered as design parameters.</p><p>We are motivated by improving the prediction accuracy when vehicles perform <strong>lane change and highway merging maneuvers</strong>. The previous approaches depend solely on the lateral and longitudinal positions to represent the vehicle trajectories. In contrast, we employ<strong> polar coordinates, vehicles orientation and radial motion velocity</strong> to represent the vehicle trajectories.</p><p>Using higher-order information of orientation and radial velocity resulted in an implicitly <strong>maneuver-aware pooling strategy</strong>, that proved to outperform the state-of-art pooling approaches in terms of the prediction accuracy. This is shown in our preprint with both overall and maneuver-based (merging and lane change) evaluation.</p><h3>Conclusions</h3><ul><li>To be aware of the interaction among the surrounding vehicles, a pooling module is employed by the LSTM generative models.</li><li>Pooling strategies can be categorized into two main types: grid-based and global.</li><li>Maneuver-based pooling (<em>our preprint under review</em>) employs polar coordinates and radial motion velocity to improve the prediction accuracy when vehicles perform merging and lane-change maneuvers on highways.</li><li>Future posts will address more practical code-related topics like preprocessing the driving datasets before the deep learning training, in addition to other topics.</li></ul><h3>Resources</h3><p>This post is summarizing one part of our <em>preprint</em> “<strong>Maneuver-Aware Pooling for Vehicle Trajectory Prediction</strong>”. If you are interested in more details, please check the <a href="https://arxiv.org/pdf/2104.14079.pdf"><strong>paper on arXiv</strong></a> and <a href="https://github.com/m-hasan-n/pooling"><strong>code on GitHub</strong></a>.</p><p><strong>More resources:</strong></p><ol><li>Deo, Nachiket, and Mohan M. Trivedi. “Convolutional social pooling for vehicle trajectory prediction.” <em>CVPR,</em> 2018.</li><li><a href="https://github.com/nachiket92/conv-social-pooling">Convolutional social pooling on Github</a>.</li><li>Alahi, Alexandre, et al. “Social lstm: Human trajectory prediction in crowded spaces.” <em>CVPR,</em> 2016.</li><li>Gupta, Agrim, et al. “Social gan: Socially acceptable trajectories with generative adversarial networks.” <em>CVPR, </em>2018.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77b566221c8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vehicle Trajectory Prediction using LSTM Encoder-Decoder Models]]></title>
            <link>https://eng-mhasan.medium.com/vehicle-trajectory-prediction-using-lstm-encoder-decoder-models-d1163eb03f8c?source=rss-1074291f25ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1163eb03f8c</guid>
            <category><![CDATA[autonomous-vehicles]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[trajectory-prediction]]></category>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Mohamed Hasan]]></dc:creator>
            <pubDate>Mon, 10 May 2021 16:49:00 GMT</pubDate>
            <atom:updated>2021-05-10T16:49:00.569Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the first post of a series that will cover several topics on trajectory prediction using LSTM generative models. This should be useful for researchers and machine learning engineers working on vehicle (pedestrian) trajectory prediction. The series will mainly summarize a number of recent publications of my work at the Institute for Transport Studies, University of Leeds. I will try my best to keep each post self-contained and simple. At the resources section, interested readers can find links to research papers and code on GitHub. Please comment with any ideas or questions that may improve this work.</p><h3>Introduction</h3><p><strong>Human drivers</strong> need to predict the intentions of other road users to safely drive vehicles and navigate through other traffic. This is critical when making decisions like yielding to a coming vehicle or merging into traffic. Similarly, an <strong>Autonomous Vehicle (AV) </strong>should be able to predict the future states of its environment and respond appropriately. Predicting the behavior of human drivers becomes necessary for AVs to share the same road with humans.</p><p>Human driver behavior is highly <strong>influenced by the other neighboring drivers</strong>. While experienced human drivers are able to confidently predict future behaviors of other drivers, it is still an open problem for AVs due to the inherent <strong>challenges of maneuver prediction</strong>. For example: (1) it is complex to predict such trajectories over long time horizons, (2) there is uncertainty about latent variables such as drivers’ motivations and goals, and (3) , drivers can take multiple possible decisions under the same traffic situation (multi-modality nature of the decision-making processes).</p><h3>Trajectory Prediction Problem</h3><p>This article addresses the problem of trajectory prediction of the human-driven vehicles surrounding an autonomous vehicle. This is commonly achieved by iteratively predicting the trajectory of each surrounding vehicle around the AV. We call the subject surrounding vehicle to be predicted as <strong><em>ego</em></strong> and the vehicles around the ego vehicle as <strong><em>neighbors</em></strong>.</p><p>Specifically,<em> given the observed motion trajectories</em> of human drivers for the immediate past (e.g. <strong><em>t_h=3</em></strong> <strong><em>seconds</em></strong>) of an ego vehicle and all its neighbor vehicles, <em>predict the future trajectory </em>(e.g. <strong><em>t_f=5 seconds</em></strong>) of the ego vehicle considering all its neighboring vehicles.</p><p>Trajectories are usually represented by the vehicle <strong><em>position, </em></strong>and<strong><em> </em></strong>can also be augmented by their <strong><em>velocity</em></strong>. Naturalistic<strong> human driver datasets</strong> provide the data required to train deep neural networks to predict vehicle trajectories.</p><h3>Vehicle Trajectory Prediction in the Literature</h3><p>This problem has been tackled from two broad aspects:</p><p>(1) using <strong>generative models</strong> that output multimodal probability distribution over the future trajectory of the ego agent.</p><p>(2) encoding the status of the neighbors by a <strong>pooling vector</strong> that captures their inter-dependencies.</p><p><strong>This article focuses on the first aspect</strong> and briefly explains the building blocks of the generative models employed in vehicle trajectory prediction. The second and other aspects will be covered later.</p><h3>Generative Encoder-Decoder Models</h3><p>Recurrent Neural Networks (<strong>RNNs</strong>) represent a rich class of dynamic models that extend feedforward networks for sequence generation in diverse domains like speech recognition, machine translation and image captioning. Long-Short Term Memory (<strong>LSTM</strong>) is an instance of RNNs that has been proved successful in sequence learning and generation tasks. Since motion prediction can be considered as a <strong>sequence generation</strong> task, and inspired by the LSTM success in this domain, a number of RNN-based approaches have been proposed for trajectory prediction.</p><p><strong>A typical generative model</strong> is shown in Fig.1, with the following building blocks: (1) an LSTM encoder, (2) a pooling module, and an (3) LSTM decoder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E8b7DhZgO9McLRIdAig2tA.png" /><figcaption><strong>Fig.1 </strong>Overview of the LSTM-based encoder-decoder generative model with the encoder, pooling and decoder modules.</figcaption></figure><h4>LSTM Encoder</h4><p>The state of motion of each vehicle is encoded using an LSTM encoder. At any time <strong><em>t</em></strong>, a sequence of <strong><em>t_h</em></strong> time steps of the track <strong><em>history</em></strong> is passed through the encoder. The LSTM states for each vehicle are updated frame by frame over the <em>t_h</em> past frames. Note that the LSTM weights are shared across the sequences of all vehicles.</p><h4><strong>Pooling Module</strong></h4><p>The <strong>interaction</strong> of vehicles in a given scene is captured by the pooling module. This is achieved by pooling the LSTM states of the <strong>neighbor</strong> vehicles around the ego vehicle. The output is a pooling vector summarizing the information needed by the ego vehicle to make a maneuver decision. There are <strong>several</strong> <strong>pooling strategies</strong> <strong>that will be covered in a next post</strong>.</p><h4>LSTM Decoder</h4><p>An LSTM decoder is used to generate the distribution over <strong>future</strong> trajectories of the ego vehicle. At any time <strong><em>t</em></strong>, The decoder generates the future trajectories over the next <strong><em>t_f </em></strong>time steps.</p><h3>Maneuver Recognition and Multimodal <strong>Probability Distribution</strong></h3><p>Since a human driver may take possible several decisions under one traffic conditions, it is desirable that generative models can output <strong>multimodal probability distribution</strong> over the future trajectory. Augmenting such models by a maneuver recognition module is one way to achieve this goal. Specifically, the models can be designed to output a multimodal distribution of predictions conditioned on a set of <strong>maneuvers or driver intentions</strong>. An example of such generative models is shown in Fig.2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PjjEnt4LARggkUlnp8Rrqw.png" /><figcaption><strong>Fig.2 </strong>Overview of the generative model with a maneuver recognition module. The LSTM decoder can predict the future trajectory of the ego vehicle conditioned on the both track histories and the predicted maneuvers.</figcaption></figure><h4>Maneuver Recognition Module</h4><p>The objective of this module is predicting the<strong> maneuvers intended by the ego</strong> vehicle, based on the track histories of both the ego and neighbor vehicles. One possible way to model the intended maneuvers (driver intentions) is by classifying the driver intention over both location and acceleration. For example <strong>location maneuvers</strong> on highways may include keeping same lane, lane change to the right and lane change to the left. Similarly, <strong>acceleration maneuvers</strong> can represent driving with constant speed, speeding up (accelerating) and speeding down (braking).</p><p>The maneuver recognition module generally consists of a number of <strong>softmax layers </strong>equal to the number of maneuver types. The input to this module is the LSTM state of the ego vehicle augmented by the pooling vector from the pooling module. Each softmax layer outputs the class probabilities of every maneuver type.</p><p>The <strong>maneuver-encoding block</strong> in Fig.2 encodes the outputs from the softmax layers into <strong>one-hot vectors</strong>, that are then concatenated with the trajectory encoding. The resulting tensor is passed to the decoder module. The future <strong>trajectory output by the decoder is based on three inputs</strong>: (1) ego history from the LSTM encoder module, (2) neighbor vehicle histories from the pooling module, and (3) ego intended maneuvers from the maneuver module.</p><h4>Example</h4><p>Having two maneuver types as the aforementioned location and acceleration, requires two softmax layers. The output from the location softmax layer may be [0.7, 0.1, 0.2], which are the probabilities of the [keep, right, left] lane location classes. Similarly, the output from the second layer may be [0.1, 0.1, 0.8] for the [constant, speeding up, speeding dow] acceleration classes.</p><p>Following the location and acceleration example, we have a <strong>joint 3 by 3 </strong>maneuver classes. Accordingly, the LSTM outputs a multi-modal distribution conditioned on these 9 maneuver classes. We can compute the LSTM decoder output based on each possible maneuver case. For example, a <strong>left</strong> <strong>lane change </strong>maneuver has an encoding of <strong>[0, 0, 1</strong>], whereas a <strong>speeding up</strong> maneuver has an encoding of <strong>[0, 1, 0]</strong>. Feeding the decoder with these inputs will generate an output conditioned on this case of (<strong>changing lane to the left while speeding up</strong>). Similarly, we can compute the decoder output for all the nine possibilities.</p><p><strong>At the prediction time</strong>, we have <strong>nine different estimates</strong> of the ego future trajectory given by the decoder output conditioned on each maneuver possibility. Then, we find the intended maneuvers having the <strong>maximum class probability</strong> (keep lane probability is 0.7 and braking probability is 0.8). The final predicted future trajectory can be given by the trajectory associated with this joint case (keep same lane while braking).</p><h3>Conclusions</h3><ul><li>The problem of vehicle trajectory prediction can be cast as a sequence generation problem.</li><li>Specifically, given the vehicle track history for a number of time steps, predict the vehicle future trajectory for a next (horizon) number of time steps.</li><li>Being successful in sequence generation problems, LSTMs constitute the main building blocks of the models that predict vehicle future trajectory. A typical model includes an LSTM encoder to encode vehicles history and a decoder to generate its future.</li><li>To be aware of the interaction among the surrounding vehicles, a pooling module is added to the encoder-decoder models.</li><li>Such models can output a multimodal distribution over the predicted trajectory, that is conditioned on a set of driving maneuvers. These maneuvers or intentions may represent semantic concepts like a lane change or a speed profile, and can be estimated by softmax layers.</li><li>Future posts will address the pooling strategies, driver dataset pre-processing, pooling toolbox code, in addition to other topics in this series.</li></ul><h3>Resources</h3><p>This post is summarizing one part of our <em>preprint</em> “<strong>Maneuver-Aware Pooling for Vehicle Trajectory Prediction</strong>”. If you are interested in more details, please check the <a href="https://arxiv.org/pdf/2104.14079.pdf"><strong>paper on arXiv</strong></a> and <a href="https://github.com/m-hasan-n/pooling"><strong>code on GitHub</strong></a>.</p><p>Naturalistic human driver <strong>datasets</strong> provide the data required to train the models explained in this post. <a href="https://ops.fhwa.dot.gov/trafficanalysistools/ngsim.htm">NGSIM</a> is the most popular dataset for highways and <a href="https://www.round-dataset.com/">rounD</a> is a good recent example for roundabouts.</p><p><strong>More resources:</strong></p><ol><li>Deo, Nachiket, and Mohan M. Trivedi. “Convolutional social pooling for vehicle trajectory prediction.” <em>CVPR,</em> 2018.</li><li><a href="https://github.com/nachiket92/conv-social-pooling">Convolutional social pooling on Github</a>.</li><li>Alahi, Alexandre, et al. “Social lstm: Human trajectory prediction in crowded spaces.” <em>CVPR,</em> 2016.</li><li>Gupta, Agrim, et al. “Social gan: Socially acceptable trajectories with generative adversarial networks.” <em>CVPR, </em>2018.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1163eb03f8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>