<?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 Nirmal Hasantha on Medium]]></title>
        <description><![CDATA[Stories by Nirmal Hasantha on Medium]]></description>
        <link>https://medium.com/@hasanthakdu?source=rss-2a65a53bfc1e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*T8KozzUu3dlZ3TPW1WKzUg.png</url>
            <title>Stories by Nirmal Hasantha on Medium</title>
            <link>https://medium.com/@hasanthakdu?source=rss-2a65a53bfc1e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:43:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hasanthakdu/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[Step-by-Step Guide to How to Build and Deploy AWS DataSync in Your On-Premises Computer- Part 2]]></title>
            <link>https://awstip.com/step-by-step-guide-to-how-to-build-and-deploy-aws-datasync-in-your-on-premises-computer-part-2-f7fc3dc1adc1?source=rss-2a65a53bfc1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7fc3dc1adc1</guid>
            <category><![CDATA[aws-datasync]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Nirmal Hasantha]]></dc:creator>
            <pubDate>Wed, 13 Apr 2022 18:01:35 GMT</pubDate>
            <atom:updated>2022-04-18T06:22:08.217Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi guys !! Welcome back to the final part of the AWS DataSync configuration</p><p>So, from the last article, I have shown you, step by step, how to successfully configure AWS DataSync Agent. From this section, let me show you how the syncing really happens between the AWS S3 bucket and the on-prem NFS server.</p><p>First things first. We need to configure the NFS server. Because I’m absolutely certain anyone can log into their AWS management console and create a folder, in this case I have already created a S3 bucket called <strong>datasync-test123</strong> and inside that bucket, I have created a folder called the <strong>samples</strong>. So basically, the NFS mount point of my computer (The folder that I have configured to store our files in the NFS) and the my S3 buckets <strong>datasync-test123</strong> folder is gonna sync with each other. Meaning that, the agent going to check what are the files at the NFS and S3 and, only upload or download the difference between 2 places. Imagine you have the exact same file in both S3 bucket and your mount folder in NFS. When the sync started, the DataSync agent does not replicate that same file again to either direction. It only downloads or uploads the content that are unique at either end.</p><p>For linux users, following articles provides you a complete guide of how to implement a NFS server on your machine and give the required permissions for the mount folder, respectively.</p><ul><li><a href="https://mateuszholowieszko.com/aws-datasync-nfs-to-s3-over-public-internet/">AWS DataSync NFS to S3 data transfer</a></li><li><a href="https://www.pluralsight.com/blog/it-ops/linux-file-permissions">How to change directory permissions in Linux</a></li></ul><p>But, this article has some contradictions with the NFS server configurations that supports the AWS DataSync. Hence, to be safe, Let me redo the code for you. Simply open the terminal and give the following commands.</p><pre>1. sudo apt update -y<br>2. sudo apt upgrade -y<br>3. sudo apt install nfs-kernel-server -y<br>4. sudo mkdir mnt<br>5. chmod 777 mnt<br>6. sudo nano /etc/exports<br>7. /mnt 192.168.1.0/24(rw,sync,no_subtree_check,crossmnt,no_wdelay)<br>8. sudo exportfs -ar<br>9. sudo exportfs -v</pre><p>And you are done. Now let me explain line-by-line.</p><p>For the first 3 commands, you basically install a nfs server in your linux (mine’s ubuntu) machine. Then for the fourth command, you need to create a folder in your root directory. You know, the one with /home, /var etc. folders. The following image might gives an idea, if you aren’t familiar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*wt2bATysHWmy495bukRS8g.png" /></figure><p>The reason you need create your mount point for the server at root directory is because, AWS DataSync gives an error saying it won’t support the temporary directories, if you attempt to sync with a folder created, for an example, in your Desktop or in Documents. The task may still says available even after you created it, pointing those temporary folders. But when you execute that task, it will gives the aforementioned error.</p><p>Then after creating /mnt directory in the root folder, you need to give it the read and write access. To do so, use the 5th command, which not only gives the read and write, but also exec access as well. (In this case, don’t mind the extra privilege ;). Then, you have to open the configuration file for the NFS server you have installed, to change the mount directory, as to that freshly created /mnt folder. By executing line 6, you will open the relevant config file in the nano text editor. At the very bottom, insert the 7th line. In there, the first “/mnt” is the mount folder that is created in the root directory. The IPv4 Address range is your private ip address range which belongs your AWS DataSync agent and the NFS server. (Must be in the same private network).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*kTyzYIgo2cHwE5axvCSNEw.png" /></figure><p>Then finally, execute the 8th and 9th command and restart your linux instance. (Or you can simply restart the nfs server only, which I’m too lazy to find the command for it). Well done. Now you have successfully created your NFS server on your on-premises computer which supports the AWS DataSync process.</p><p>This syncing process consists of 2 main parts.</p><ol><li>Source is the S3 bucket and the Destination is the NFS</li><li>Source is the NFS and the destination is the S3 bucket</li></ol><p>The source and destination here stands like this. When the source is S3 and the destination is NFS, the DataSync agent downloads all the content of the s3 bucket (except for the same files in the NFS) to the NFS mount point. And likewise, for the second part, the DataSync agent checks the NFS mount path and upload all the files from that NFS mount folder to the s3 bucket, with the exception of the similar files between both endpoints.</p><p>Let’s start with the first one. To start syncing, for either of the 2 parts, we need to create a task and specify the source and the destination. But first, check your agent is available. If not recheck your AWS DataSync agent (VM) status. When you go to the “Agents” tab, it should be displayed as follows. (Sometimes, it tends to display “Online” even if the DataSync agent VM is shutdown. To make sure the agent has a healthy network connectivity, test the network connections on the AWS DataSync agent (VM) from you end)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wlPJiY87i-6aBvUMg8nvhA.png" /></figure><p>When the agent is all up and running, go to the “Tasks”. In the “Create Task”, you will be greeted with the following page. Since, for the first task, we gonna download all the files that are on the s3 bucket to the on-prem NFS (except of course the similar files that already exits in the NFS) , following are the configuration for the source as the S3 bucket and the destination as the NFS server. Remember, we are not syncing the entire S3 bucket, but a folder inside it called “samples”, for the sake of simplicity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yqx5czW8mkbLWIMsVmSt2g.png" /></figure><p>The latter part is as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aKnlWMjP1vKAmRncmaOMfQ.png" /></figure><p>For the IAM role, simply click Autogenerate button and let the AWS create a role for you that only gives access specifically to this task only. (Which is safe :). Then click next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aguUACDL8Hv1qzDmUJ7kkQ.png" /></figure><p>In here, you will be greeted a similar page as before, but for the destination. Do the selections appropriately . (Select “Create a new location” option at here too). For the “NFS Server” option, insert the ip address of your linux instance. You can easily find it using “ip -a” command execution at the terminal as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*JL9zAIaRxkVy2p9_9dq8Zg.png" /></figure><p>As you can see, in here, my ip address is 192.168.1.33, which is highlighted in white. Then for the mount path, simply give /mnt and click next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZD6fUosJF5rjbNtNoVt5XQ.png" /></figure><p>Now as displayed above, give an appropriate name and select the Transfer mode as you wish. Here, I went with the default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pn0T7AWKW3eCdgOLQiTagw.png" /></figure><p>As you can see, you can schedule the syncing process too :) I didn’t enable the CloudWatch log entries for this one, but feel free to do so, if you wish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HUkr4C0F8BhE--IKphrF1A.png" /></figure><p>The finally, you will be greeted with the review page. Check all the configurations are correct. If so, click on <strong>Create Task</strong> button. My review page configs are as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ny8_keBJ2RQSlWird3H-SA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TAD0n7eLYXbF3ldagXeh5A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y7zGJkjDPa6Y_dJzP-OvMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1BGVpmIiMiPCFNwWXZ_cIg.png" /></figure><p>And you are done !!! Congratulations :) You have made it this far. You can see the link is available or not, just after few minutes of creating. Refresh the page few times until you see that beautiful green message. Initially it would be displayed as <strong>Creating</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kgvJRXiumSJwVNjbXP5IZA.png" /></figure><p>But few minutes (for me around 45s, depends on your internet speed), you will get the “Task status” as “Available”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NHd2OJYxXKlCYOcGgemZyQ.png" /></figure><p>To start the syncing process, click on “Start” button at the top right corner. Then you can go to the task execution page, which is as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uPyJvCiubx5RE_xama5WAA.png" /></figure><p>Initially, it will displays the “Execution status” as Launching. But friends, this definitely gonna take some time. In here I have got the following error message. Though it says, <strong><em>Transfer and Verification completes</em></strong>, we need to dig into the error message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MciKxAjr6pnAhPZZafLt6g.png" /></figure><p>So, in my s3 bucket, I have placed 3 different types of files. An image, a word document and a video. I needed to see if they are corrupted when they are synced with the NFS server. Despite the message, they were all fine and there weren’t any corruptions whatsoever. Since I didn’t enable CloudWatch, I couldn’t looked into it. But I can assure you, there weren’t any crashes or corruptions. Still I have no idea why it says some files are skipped due to errors, since all the 3 files are downloaded successfully without any fault. If any of you find-out, please let me know in the comment.</p><p>Following is my s3 bucket’s “samples” folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KH4MH82cGOdZN80IK38kQQ.png" /></figure><p>And this is my on-prem /mnt folder after the syncing completed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*aQUSjN_idiipyNhMVEP1Dg.png" /></figure><p>But this error/warning message only seems to be appear at for the first task only. For the second task, when the source is NFS at on-prem and the destination is the s3 bucket, the execution completes successfully without any error message whatsoever as follows.</p><p>First it goes from <strong>Launching</strong> to <strong>Transferring</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_xor-86f5bC5UTy1quGffQ.png" /></figure><p>After when the Transferring hits 100%, it displayed as “<strong>Success</strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jf-77YlVByax9dTO2huBtA.png" /></figure><p>So my dear readers, that conclude both the tasks that I have promised. For the second task, simply reverse the source and destination details which you have inserted for the first task. Hence, in the “Tasks” tab, now you will be greeted the following 2 tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p9moFIvzN7qP1tJTbsOrig.png" /></figure><p>Thanks for reading guys. I love you all !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7fc3dc1adc1" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/step-by-step-guide-to-how-to-build-and-deploy-aws-datasync-in-your-on-premises-computer-part-2-f7fc3dc1adc1">Step-by-Step Guide to How to Build and Deploy AWS DataSync in Your On-Premises Computer- Part 2</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step by Step Guidance to How to Build and Deploy AWS DataSync in Your On-Premises Computer- Part 1]]></title>
            <link>https://awstip.com/step-by-step-guidance-to-how-to-build-and-deploy-aws-datasync-in-your-on-premises-computer-part-1-54014b9f6987?source=rss-2a65a53bfc1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/54014b9f6987</guid>
            <category><![CDATA[vmware]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[data-sync]]></category>
            <dc:creator><![CDATA[Nirmal Hasantha]]></dc:creator>
            <pubDate>Sat, 09 Apr 2022 06:49:00 GMT</pubDate>
            <atom:updated>2022-04-18T06:21:12.952Z</atom:updated>
            <content:encoded><![CDATA[<h3>Step-by-Step Guide to How to Build and Deploy AWS DataSync in Your On-Premises Computer- Part 1</h3><p>Hello guys !! It’s been a while. Today I’m gonna write about something bit different from ML. So, relax, get set, and let’s go!!</p><p>For those who don’t have a keen idea about what is AWS DataSync (including myself), it is, as name suggested, sync your AWS Storage units, such as an S3 bucket, AWS EFS or AWS FSx (Whatever that means :(), with your On premises storage units. (Specific folder or location on your computer) . For the explanations, I will proceed with syncing data between an S3 bucket and my on premises NFS Server.</p><p>In order to begin, there are certain tools you need to install on your on premises computer. Because we can’t expect these files at On-prem or at S3 to magically sync between each other, right? So for that, the first tool we need is an AWS Agent. This agent basically builds a connection between your on premises network storage and the AWS data storages. Following diagram is a clear illustration for that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4oG4PryYtDUKHZoH.png" /></figure><p>But the thing is, this process is not that easy. Because this agent is not another program we can install on our system. This is basically a Virtual machine. So if you want keep the link between AWS and On-prem to be up and alive, you need this DataSync agent to be up and running. (At least it needs to be at running state, when the syncing process starts)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kMB3J8m-0xSBwIYqxwEn9Q.png" /></figure><p>Let’s start by downloading the agent, shall we?. Ok, first log in to your AWS Account in Management console and search DataSync from the options. Now you can see there’s 2 options. One for the sync between on prem and AWS storages. Other one for the sync between AWS resources themselves (Like an S3 bucket and Amazon EFS). Since we don’t want the latter one for this explanation, select the first option, “ Between on-premises storage and AWS”. By selecting that, you will be directed to following page. Do not close this page from this point onwards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YAe4cWQGlOcu5FSbwXaZyQ.png" /></figure><p>First topic you might see is the “Deploy agent”, under the “Create agent”. Bare with me here. This part is tricky. From the drop down menu, you could see there are several hypervisors which support the virtual machine (AWS DataSync Agent). So theoretically, you need either VMware ESXi, KVM or Microsoft Hyper-V, in order to deploy the agent. (Amazon EC2 doesn’t belong in our activity, since we need an on-premises agent, so ignore it. This is for linking cloud EC2, to your on-prem or another AWS storage unit). If you observe, VirtualBox is not in the list. But again, to be honest, even I’m not comfortable with working with those given hypervisors. Specially with that Windows one. Yikes :(. So, being a good mate, I selected the VMware ESXi and downloaded it’s compatible version of the DataSync agent. Remember, you can’t use the same image for each of the hypervisor. If you choose VMware, you need it’s own version of the DataSync agent. Same goes with the Windows Hyper-V and the KVM. So, after first downloading the VMWare ESXi version, I needed the ESXi itself to deploy this image as the VM right? Then that’s where the harsh truth struck me.</p><p>This is a type one hypervisor. If you dual boot windows and linux in your computer, right after when you turn it on, you will be brought to boot menu to select either windows or ubuntu, right? Yeah, that platform is a type 1 hypervisor. If you want to run windows inside your macOS, then that VirtualBox I mentioned, that is type 2 one. So how can I go with this? And not to mention this is very complicated process, the ESXi installation. You need to mount the ESXi image first into a pen-drive, boot the computer with it, install it in a local drive. Then you need another computer, within the same private ip address range, in order to log into that hypervisor and do the configs, Partitioning a disk and install the DataSync agent.</p><p>Guys, I don’t think most of you are willing to take this much of effort. But for the sake of the experiment, I launched the type 1 hypervisor, inside my type 2 one, just to see if the hypervisor works. It does, but again this is insane. If you want to learn more about doing this, be my guest. I learnt a lot from the following video from our good old youtube.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FYhXsX4kJS3M%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DYhXsX4kJS3M&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FYhXsX4kJS3M%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1b0a1540ee977196968d926674ddbff/href">https://medium.com/media/c1b0a1540ee977196968d926674ddbff/href</a></iframe><p>One of the best explanations so far. But this article is to avoid the AWS official obstacles and achieve the task with minimum effort.(With maximum satisfaction :)</p><p>Then after skipping that, I chose Windows Hyper-V. I again downloaded it’s own compatible DataSync agent and ran it. Dear friends, that didn’t even pass the first milestone. It was stuck on message saying, “Start PXE over IPv4”. After few minutes, it gave me a boot error message . If any of you are interested about proceeding with Hyper-V hypervisor and resolve that error, try the following <em>stackoverflow</em> post. I didn’t try all these solutions, (cause I’m pretty lazy), so try if you could resolve it using the suggestions given.</p><p><a href="https://stackoverflow.com/questions/58073852/when-trying-to-install-os-in-hyper-v-it-ignores-boot-order-and-goes-to-start-p"><em>https://stackoverflow.com/questions/58073852/when-trying-to-install-os-in-hyper-v-it-ignores-boot-order-and-goes-to-start-p</em></a></p><p>Then, since my first choice, ESXi hypervisor is from VMware, I tried to run the DataSync agent on one of their type 2 hypervisors. My poison of choice was VMWare Fusion (VMware Workstation also works with the agent without any trouble. But I didn’t test it. But pretty sure it works.). And as you guessed it. It worked :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/0*hNHDjL6ZgSajmvFm.jpg" /></figure><p>Now, let’s walk through with the steps. Go back to the “Create agent” page. When you click on “Download the image” link, you will get a .zip file. In order to extract it, for mac users, I recommend a free tool called “Keka”, which helps to extract the image file without corruption. (Because the native mac zip tool tend to corrupt the image.) Simply create a new virtual machine and give the DataSync agent as the image file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*qSabAm4FF72gnSQgQBQxZQ.png" /></figure><p>Select <strong>Continue</strong> and it will import the image as a Virtual Machine</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*f1QD3hcA_jpAGyeM0xt4hA.png" /></figure><p>Then finally, you will be redirected to the Finishing step. Before click on the <strong>Finish</strong> button, there are some configurations to be done. Click on “Customize Settings” to launch the virtual machine configurations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*X8Cmmf3t10aVxP6okCIWBQ.png" /></figure><p>From the following panel, you first need to set the number of CPU cores to 4. It is the minimum recommended vCPU specs to run this agent. So from the panel, select <strong>Processors and Memory</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*As5WUSP0rpxEg8u3Ga6U5Q.png" /></figure><p>Then from the drop down menu, select <strong>4 processor cores</strong>(at minimum).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*b4UrgF0lf4LEDdllg33trQ.png" /></figure><p>There’s two more configurations left. The first one is to <strong>Disable the side channel mitigation</strong>. Frankly, I don’t think it’s necessary. But it suggests that, enabling this might increase the speed of the process. So, I recommend you to go with it, because we don’t want any timeout errors at our first try. Savvy?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*tmsdXIZfvdsNa8cElgA8IQ.png" /></figure><p>Our last configuration is to select the right network settings. To do so, from the panel, choose “Network Adapter”. Then under “Bridge Networking”, select “Wi-fi”. Because the “Autodetect” bridge networking configuration sometimes tends to give a different private ip range from your usual private network. So, by selecting the wi-fi, you will get a fresh private ip address from the DHCP pool of your home router, without any anomalies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*OogDHFdkCTMNrHdpF6DhWw.png" /></figure><p>Then finally, click the <strong>Finish</strong> button and the vm will start immediately. In few seconds you will be prompted to a screen like this;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*7tQG7gKmDft2I3hTsFCq8w.png" /></figure><p>In here, you could either wait for few minutes, or just click on Esc button, which will drag you to this loading bar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*2yrFkjfZLzPwmo4SY_izDg.png" /></figure><p>Then after it’s completed, (the bar :), you will be prompted to following page, asking you to input the login details. Simply type “admin” as the user name. Then as password, enter “password” as the password. :()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*ZidXA1-v2I-xQut4dn7moA.png" /></figure><p>That’s it! You are now greeted with the home page of the DataSync agent. It might looks as follows. Ignore the warning for this test, as it basically recommend you to go with recommended specs, instead of minimum as I configured. Moreover, this only applies to large quantitates of files. So go with the recommendations as you wish, but first, let’s establish the agent, shall we?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*RdpLZGF7iKm61oyoaMTJ-A.png" /></figure><p>So, if you notice, for the <strong>eth0</strong> address, there’s a private ip address, which need to be in the same range as your local pc/Mac. If not, double check the Network Adapter configurations or select option 1 form home page, “<strong>Network Configurations</strong>” and select 4 to “<strong>Reset all DHCP</strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*DjNcjM1sEauLAePof6JniQ.png" /></figure><p>If it’s detected your DHCP server, the prompt will be displayed as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*B7kqKk3nfIqOzdH5jLPxHg.png" /></figure><p>Then come back to home page. If you want to check your connection in general to the AWS, select second option from home page, “<strong>Test Network Connectivity</strong>”. Select the first option, “<strong>Public endpoint</strong>”. Then enter the region that you wish to check the connection. This should be the region you have deployed your AWS storage instances. In here, I tried “<strong><em>ap-southeast-1</em></strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*EOR4W23TDBrqr0_97NnWug.png" /></figure><p>After hitting Enter, you could see whether the connections are passed or failed. It is possible for some of these tests to fail at the first try. But this is normal. Try again for the second time for the same region by following those steps again. This time I will assure you, all test will be passed. Like follows,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*Qpig1_LXxiblxKiEwkWd4g.png" /></figure><p>Now after testing the connections to AWS, we need to link this agent with our account. From the very first web page, the “Deploy agent” one, scroll down to its bottom, and enter the private ip address of the DataSync agent, which we saw earlier at the home page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*tUKGAv_RI1YenMiWX8hMbA.png" /></figure><p>Insert the same address under the “Agent Address” option. And finally. Select the “Get Key” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n4Lia4LKRWuI4yr8rbIx2w.png" /></figure><p>In few seconds, you will be greeted with the following page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x3NE-Pdq18W4UG6iCiP4DQ.png" /></figure><p>Under the “Agent name”, give it a name of your choice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FVwY6MtBx13ahc8SvzTn_Q.png" /></figure><p>Then finally, you will be prompted to this page, which says agent is created successfully. You can also observer the agent is alive, thanks to the green “Online” agent status. And make sure it is online !!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EWnRHDkiXLQWFsQQmIyjiA.png" /></figure><p>Then go back to the agent home screen. The 0th option is still there right? Don’t worry. Select the test network connectivity again. Now instead of you to select the region, the DataSync agent will automatically only check the connections to the region you have attached it. After that, go back to the home screen and BOOM!. That 0th option is no longer there. My friend, you have now successfully created an DataSync agent and linked it with your region of interest. Congratulations!!! From the second part, let’s see how we use an NFS server to sync files from the both ends. (On-prem and AWS-S3).</p><p>And as always. Thanks for reading. Don’t hesitate ask any questions ;)</p><p>Bye!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54014b9f6987" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/step-by-step-guidance-to-how-to-build-and-deploy-aws-datasync-in-your-on-premises-computer-part-1-54014b9f6987">Step by Step Guidance to How to Build and Deploy AWS DataSync in Your On-Premises Computer- Part 1</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parking Violation Detection System using Computer Vision]]></title>
            <link>https://medium.com/@hasanthakdu/parking-violation-detection-system-using-computer-vision-3ee784cb5d43?source=rss-2a65a53bfc1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ee784cb5d43</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[yolov4]]></category>
            <category><![CDATA[deep-sort]]></category>
            <dc:creator><![CDATA[Nirmal Hasantha]]></dc:creator>
            <pubDate>Thu, 30 Dec 2021 10:43:47 GMT</pubDate>
            <atom:updated>2021-12-30T10:53:09.987Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi guys. This is the last traffic violation detection of my final year project. I’m so excited to share how I have done it. This is a parking violation detection system. Not going to lie, the logics and conditions that I have used here are little bit difficult to understand, especially the way it has programmed. But don’t worry. Bear with me until this explanation and I will guarantee you, you will understand it like cheese. (Probably should use a better metaphor). Who knows, maybe you could build a better version of this.</p><p>And I highly recommend to any of you who’s going to go with this to read my 2 previous articles about the Speed and Lane line violation detection, because it covered a significant portion of the codes and techniques I have used, which I might have used here too without mentioning. Links are as follows.</p><ul><li><a href="https://medium.com/@hasanthakdu/speed-violation-detection-of-real-time-video-footage-using-computer-vision-8bab662cf8b4">Speed Violation Detection of Real-Time Video footage using Computer Vision</a></li><li><a href="https://medium.com/@hasanthakdu/lane-line-violation-detection-using-yolo-and-deep-sort-f19774b3c739">Lane Line Violation Detection using Yolo and Deep-Sort</a></li></ul><p>You can find all the codes and repos from following GitHub link;</p><p><a href="https://github.com/hasantha-nirmal/Traffic_Violation_Detection_Yolov4_Deep-Sort">https://github.com/hasantha-nirmal/Traffic_Violation_Detection_Yolov4_Deep-Sort</a></p><p>Let’s get started, shall we?</p><p>First, let me give you a brief understanding of what I have meant by the Parking violation detection in this project. Imagine we have a region of interest/certain place that vehicles aren’t supposed to park. But we can’t detect a vehicle as a violator if it is just stopped there’s for a little moment, right? Because if this area we are talking about, if it is too close to a road, a pass by vehicle might intersect with this region of interest and immediately would be considered as it has done a violation. So first, we must eliminate such scenarios. But how?</p><p>Well, the easiest solution is to introduce timers for each individual vehicle. From that, we can not only assure that vehicle has been in that restricted area for certain amount of time, but also, we can determine how long that vehicle has been there. Isn’t that awesome? I mean we can totally use the same system for systematic parking system, instead of taking tickets and all that. By introducing the regions of interest as parking slots, just by using one CCTV camera, we can not only simultaneously monitor and detect how long that specific vehicle has occupied that parking space, but also, we can calculate how much each individual vehicle must pay for the parking.</p><p>Ok let’s go back to the violation detection. As I mentioned before, timers are the key word here. But taking many vehicles into account at the same time is surely going to complicate the task. But luckily, we have a way to implement our system by assuming there’s only one vehicle in the region of interest but in real, there are several simultaneous vehicles who are doing that violation at the same time. You can get an idea of this mechanism in my speed violation detection article.</p><blockquote><strong># Parking space coordinates; #line 113<br> parking_co = []<br> <br> #blanked = np.zeros((658,1024), dtype=np.uint8)<br> blanked = np.zeros((2048, 1024), dtype=np.uint8)<br> #pts = np.array(([156, 704], [2, 893], [476, 932], [270, 708]))<br> pts = np.array(([513, 716], [321, 943], [884, 979], [630, 701]))<br> #blanked = np.zeros((720,1280), dtype=np.uint8)<br> #pts = np.array(([38, 433], [95, 322], [1246, 570], [1065, 709]))<br> cv2.fillPoly(blanked, np.int32([pts]), 255)</strong></blockquote><p>First, let me show you how to select the parking space pixel coordinates as our interest. I have first introduced a blank array called <strong><em>parking_co</em></strong> and then created a zero array as same as the video resolution. (One of the frames’ widths and Hight). Then select the coordinates of the shape of the polygon that you have selected as the region of interest (ROI). The attributes see in the <strong><em>pts</em></strong> array are the edge coordinates of the polygon that we have selected. But this is not enough. We need the pixel coordinates that covers inner area of this polygon, so we can determine when vehicle (bounding box) coordinates intersect with them. For that I have used an OpenCV function called <em>fillPoly</em> and gave the <strong><em>pts</em></strong> array coordinates as one of its attributes.</p><p>Then I have extracted the x and y coordinates points from the blanked mask, which now has filled with pixel values of the region of interest.</p><blockquote><strong>x_cord = np.where(blanked == 255)[1] #line 124<br> y_cord = np.where(blanked == 255)[0]</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*ms0z5OWR-FeNvCQwi86W-Q.png" /><figcaption>Region of interest. (Red polygon)</figcaption></figure><p>Now we have all the coordinates points of the pixels in the region of interest or the place where the vehicles are prohibited to park. Then let’s take the bounding box coordinates of the vehicle itself. But again, this rises a problem. If the camera is too close to this region of interest, when a vehicle approached to that area, its bounding box is occupying a very large number of coordinate points and when there are simultaneous vehicles, this process must be repeated for each frame of the video, the frame rate drops drastically. So, I have taken an argument for this case that if a vehicle/bounding box is intersecting this ROI, it most definitely intersecting with the bottom line of the bounding box too. So just like in the lane line violation, instead of taking all the bounding box coordinates of the vehicle, I have taken only the coordinate of the bottom line of the bounding box, which not only fits to my argument but increase the frame rate(performance).</p><p><strong><em>#Note that if the camera is far away, this problem might not occur, and you can use the whole bounding box without any performance issues.</em></strong></p><blockquote><strong>#line 284</strong></blockquote><blockquote><strong>bbox_bottom_line_co = list(zip(*line(*(int(bbox[0])+50,int(bbox[3])), *(int(bbox[2])-50,int(bbox[3])))))</strong></blockquote><p>Here is the code of extracting bottom line coordinates and as you can see, I have reduce the line length by removing 50 pixel coordinates from each side of the line for better representation of the vehicle. So, the line always stays in the region of vehicle and doesn’t occupy any free space around it.</p><p>Ok everyone. Now begins the tricky part. So, hold it tight.!!</p><blockquote><strong>#line 294</strong></blockquote><blockquote><strong>if len(intersection(parking_co, bbox_bottom_line_co)) &gt; 0:<br> frame_matrix.append((str(frame_num) + class_name + str(t),<br> (<br> str(int(bbox[0])).zfill(4), str(int(bbox[1])).zfill(4), str(int(bbox[2])).zfill(4),<br> str(int(bbox[3])).zfill(4))))</strong></blockquote><p>Imagine a vehicle intersect with the region for the first time. The moment it happens within a specific frame, I immediately append the frame number of that incident, <strong><em>frame_num</em></strong>, vehicle type(<strong><em>class_name</em></strong>), the vehicle tracking id (<strong><em>str(t)</em></strong>) and the bounding box coordinates of that vehicle at that frame, when it does the intersection of ROI.</p><blockquote><strong>chk_index = str(frame_matrix).find(str(frame_num — 1) + class_name + str(t))</strong></blockquote><p>Then it immediately checks with the previous frame if a same sort of intersection has occurred for the same vehicle. If this intersection happened for the first time, this condition is not satisfied, and the program go to the next frame without any further interaction. But imagine, if this is the second frame after the vehicle has intersected with the region of interest, there’s indeed a value is obtained for this <strong><em>chk_index</em></strong> variable.</p><blockquote><strong>if bool(chk_index + 1) == True:<br> previous_bbox_co_str = str(frame_matrix)[<br> (chk_index — 1) + len(str(frame_num — 1)) + len(class_name + str(t)) + 5:(chk_index — 1) + len(str(frame_num — 1)) + len(class_name + str(t)) + 5 + 30]</strong></blockquote><p>The Boolean value of (<strong><em>chk_index+1</em></strong>) gives a positive value. The reason for the addition of 1 is that it is possible for a specific vehicle, its logging details starts from very beginning of the array and hence making its placement value in array as 0. If that happened, <strong><em>bool(0)</em></strong> makes the condition false even though it is True. If there is no such a log entry, <strong><em>chk_index</em></strong> simply returns -1 and when a +1 is added, it gives the desired False output.</p><p>When that condition is true, as you can see, they obtained the previous frame log details about the bounding box to a different variable called, <strong><em>previous_bbox_co_str</em></strong>.</p><p>Now we know the bounding box coordinates of the vehicle at current intersection as well as in the previous intersection. Since we know for all these times, the vehicle has been in the ROI, we need to determine whether the vehicle is stationary (immobile) or whether the vehicle is moving. To check that I have declared a new function called <em>immobile</em></p><blockquote><strong># Check the immobility of vehicle #line 99<br> def immobile(bbox, previous_bbox_str):<br> previous_bbox0 = int(previous_bbox_str[1:5])<br> previous_bbox1 = int(previous_bbox_str[9:13])<br> previous_bbox2 = int(previous_bbox_str[17:21])<br> previous_bbox3 = int(previous_bbox_str[25:29])<br> <br> total = abs(bbox[0] — previous_bbox0) + abs(bbox[1] — previous_bbox1) + abs(bbox[2] — previous_bbox2) + abs(<br> bbox[3] — previous_bbox3)<br> if total &lt;= 4:<br> return True<br> else:<br> return False</strong></blockquote><p>So here I have used the <strong><em>previous_bbox_co_str</em></strong> as an attribute to the function, as well as the current bounding box coordinates. I have taken the difference of respective xmin, ymin, xmax and ymax values and if the absolute different is less than 4, I have outputted True, as the vehicle is immobile and False as the countermeasure.</p><p>Keep in mind that YOLO tends to give a fluctuating bounding box coordinates even though if a vehicle or any object is in complete stop. To avoid and make this process robust, I suggest you use a higher value for the <strong><em>tota</em></strong>l variable here. Higher the value, more robust the program gets to the random fluctuations of the bounding boxes.</p><p>So, if the function output as the vehicle is immobile (stationary), then I immediately checked, is there any previous logged entry in the <strong><em>cache_matrix</em></strong> and if not, I append the current time(<strong><em>t_start</em></strong>) and the vehicle type(<strong><em>class_name</em></strong>) and tracking id(<strong><em>str(t)</em></strong>).</p><blockquote><strong>if str((class_name + str(t))) not in str(cache_matrix): #line 310<br> t_start = datetime.now()<br> cache_matrix.append((str(t_start), class_name + str(t)))<br> print(cache_matrix)</strong></blockquote><p>In the next condition, I have checked if the vehicle is in <strong><em>cache matrix</em></strong>. (Now it is). Also check if the same vehicle is NOT in the <strong><em>viol_matrix</em></strong> too. (Because I have introduced the violation matrix to logged vehicles, who have been stationary and exceeded the time limit.). If not, I immediately retrieve the <strong><em>t_start</em></strong> value of that specific vehicle and check the time different using the current time.</p><blockquote><strong>index = (str(cache_matrix).find(str((class_name + str(t))))) #line 318<br> t_start_cm = str(cache_matrix)[index — 28:index — 11]<br> t_spending = (datetime.now() — datetime.strptime(t_start_cm,<br> ‘%y-%m-%d %H:%M:%S’)).total_seconds()</strong></blockquote><p>If the time different(<strong><em>t_spending</em></strong>) has increased more than the desired time limit, then I logged the details to a spreadsheet, which included vehicle first intersection time(<strong><em>t_start_cm</em></strong>), vehicle type (<strong><em>class_name</em></strong>) and vehicle tracking ID (<strong><em>str(t)</em></strong>). In this case, for demonstration purposes, I have set the timer as 10s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rt_CYs8JxecXSLEdtkx4kQ.png" /><figcaption>Ex: Timer has started for this specific Vehicle</figcaption></figure><blockquote><strong>sheet.write(row_num, 0, str(t_start_cm), style) #line 328<br> # sheet.write(row_num, 1, str(round(t_spending, 2)), style)<br> sheet.write(row_num, 1, str(class_name) + str(t), style)<br> row_num += 1<br> workbook.save(‘outputs/xlsx/parking/details.xls’)</strong></blockquote><p>Then we must put this specific vehicle into the <strong><em>viol_matrix</em></strong> array as a log entry because the vehicle has done a violation now. And this avoid further repetition and false log entries that vehicle been here even after the violation has occurred. Then you can snap an image of that violated vehicle and save it as its own vehicle type and tracking id as its name.</p><blockquote><strong>viol_matrix.append((str((class_name + str(t))))) #line 334<br> # print(t_start_cm, t_spending, datetime.now())<br> cropped = image.crop((int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])))<br> cropped.save(<br> ‘outputs/caps_of_detections/parking/’ + str(<br> class_name) + str(t) + str(‘.jpg’))</strong></blockquote><p>Now this is basically the idea of the parking violation detection system that I have implemented. To avoid memory overload of the <strong><em>frame_matrix</em></strong>, flush that array using following function for every 107 entries.</p><blockquote><strong>#Avoid buffer overflow #line 353<br> if len(frame_matrix)&gt;10⁷:<br> frame_matrix=[]</strong></blockquote><p>Thank you so much for reading. :). Don’t hesitate to post any comment or question.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ee784cb5d43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lane Line Violation Detection using Yolo and Deep-Sort]]></title>
            <link>https://medium.com/@hasanthakdu/lane-line-violation-detection-using-yolo-and-deep-sort-f19774b3c739?source=rss-2a65a53bfc1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f19774b3c739</guid>
            <category><![CDATA[traffic-management]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[yolov4]]></category>
            <category><![CDATA[lane-line-detection]]></category>
            <category><![CDATA[deep-sort]]></category>
            <dc:creator><![CDATA[Nirmal Hasantha]]></dc:creator>
            <pubDate>Wed, 29 Dec 2021 06:10:40 GMT</pubDate>
            <atom:updated>2021-12-31T12:55:48.143Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi again my friends. This time I’m going to explain to you how we can detect and track lane line violation of real-time (video) footage. This activity mainly consists of 2 parts.</p><p>1. Lane-Line Coordinates Abstraction</p><p>2. Tracking the Lane-line violated vehicle</p><p>Just to be clarified, this is my second article related to my Traffic Violation Detection project. If you interested in how to perform Speed Violation Detection, please read that on following article. You will find the associate repository and the code too!!</p><p>You can find the code to this article from then same place as well!</p><p><a href="https://github.com/hasantha-nirmal/Traffic_Violation_Detection_Yolov4_Deep-Sort">https://github.com/hasantha-nirmal/Traffic_Violation_Detection_Yolov4_Deep-Sort</a></p><p>And the Speed Violation Detection Article from here!!</p><p><a href="https://medium.com/@hasanthakdu/speed-violation-detection-of-real-time-video-footage-using-computer-vision-8bab662cf8b4">https://medium.com/@hasanthakdu/speed-violation-detection-of-real-time-video-footage-using-computer-vision-8bab662cf8b4</a></p><p>Let’s go to the first part, shall we?</p><p>In lane line violation detection, our first challenge would be to detect and identify the lane line first. It could be curved, near straight line or sometime maybe snake like. We need the exact coordinate points of that lane line, regardless of how the shape or how hard to extract that pixel coordinates from the video frame. (Assuming the camera is fixed in a position). So, what is the easier and more efficient way to do it?</p><p>Well, we can always use some standard functions of OpenCV library to extract the lane line, like starting with selecting the region of interest (reduce environment noise), use RGB to HLS color transformation to better appeal the lane line (Because that tends to do that) and finally use Hough line transformations and other various techniques. You can find such a tutorial from my GitHub profile with the following link.</p><ul><li><a href="https://github.com/hasantha-nirmal/SimpleLaneDetection">GitHub - hasantha-nirmal/SimpleLaneDetection: This is an initial approach to detect lane lines of a road when the noises are minimum(Straight roads)</a></li><li><a href="https://github.com/hasantha-nirmal/Advance-Lane-Line-Detection">GitHub - hasantha-nirmal/Advance-Lane-Line-Detection: This gives a more robust output than the SimpleLaneLine Finder</a></li></ul><p>But these methods do not guarantee you the EXACT coordinates. Imagine, there’s a small noise is caused by some sort of small pixel cluster. When we adjust our thresholds, it might disappear. But so will be a part of the lane line itself. I’m pretty sure you have experienced it too. So let me show you an easier method to that. You might still need a simple OpenCV functions. But I assure you this is one-shot.</p><p>First open the video footage and select a frame that we can see the lane line very clearly without any vehicles or any other obstacle covering it. Then take that frame without changing the frame size. You can simply use VLC media player to take a snapshot with the same resolution as the video. Afterwards go find this simple online tool. Link is down here.</p><p><a href="https://www.gifgit.com/image/eraser-tool">https://www.gifgit.com/image/eraser-tool</a></p><p>This is a free online tool which let you erase all the unnecessary potions and noises of the image and let you preserve only the lane line itself. So, upload the image to the tool. Select the eraser and adjust its size appropriately and start to carefully erase the image but the lane line. Following shows you before and after images of a selected frame. Make sure you don’t change the image size/resolution in this process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/183/1*y8OP-ejua9yyih9BmvXi2w.png" /><figcaption>Frame contains lane line with minimum noise (Original Snapshot)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/176/1*g_El7ZrCZTZmfrbiIuLW5Q.png" /><figcaption>Extracted line through the eraser-tool online</figcaption></figure><p>After Downloading the finished image from the tool, now the life is much easier :). I have created a custom python script called <em>lane_line_extract.py</em> to get all the coordinate points from this newly extracted image.</p><p>So let me walk you through with the code.</p><blockquote><strong>img=cv2.imread(‘downloaded_image,png’ ,0) #line 5 <br> ret, bw_img = cv2.threshold(img, 200, 255, cv2.THRESH_BINARY) #165<br> kernel = np.ones((1,1),np.uint8)<br> #erosion = cv2.erode(img,kernel,iterations = 1)<br> opening = cv2.morphologyEx(bw_img, cv2.MORPH_OPEN, kernel)<br> #closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel)</strong></blockquote><p>First read the image as a grayscale image like any other. Then binarize the image with an appropriate threshold value. Here I have used (200,255) but you need to change this threshold until it fits your need by running trials which best indicate only the lane line. Then you can always use some help with the Morphology Transformations from OpenCV such as <em>erode</em>, <em>morphologyEx</em> etc.</p><p>Follow this link for detailed examples. What you need with these functions is to remove any noise even further and get a clean view of the lane line itself.</p><p><a href="https://docs.opencv.org/3.4/d9/d61/tutorial_py_morphological_ops.html">https://docs.opencv.org/3.4/d9/d61/tutorial_py_morphological_ops.html</a></p><blockquote><strong>#Append lane line coordinates to a matrix #line 14<br> lane_line_co=[]<br> x_cord_lane = np.where(opening == 255)[1]#+806 #+805<br> y_cord_lane = np.where(opening == 255)[0]#+423 #+389<br> <br> for q in range(0, len(x_cord_lane)):<br> lane_line_co.append((x_cord_lane[q],y_cord_lane[q]))</strong></blockquote><p>After outputting a smooth image with the lane line, now we can extract the coordinates. Since we used a binarized image, we can simply extract all the pixel points that are equal to the max value, which is 255. I have first introduced an empty array called <em>lane_line_co</em> and extracted the x and y coordinates points of pixels that are valued 255. (<strong><em>x_cord_lane</em></strong> and <strong><em>y_cord_lane</em></strong> respectively). Then appended those x and y coordinates to that empty array, <strong><em>lane_line_co</em></strong>.</p><p>Now we are almost done. All we must do is create a caller function to extract these coordinate points from our main python file. (<em>lane_line_viol.py</em>). So, I have created one as follows.</p><blockquote><strong>def get_lane_line_co(): #line 23<br> return x_cord_lane,y_cord_lane,lane_line_co</strong></blockquote><p>Ok! Wow! we are done here. Not let’s deep dive into the <em>lane_line_viol.py</em></p><p>The first task we need to do is call to the function from the main script.</p><blockquote><strong>from lane_line_extract import get_lane_line_co #line 31</strong></blockquote><p>Now this lane line violation is bit different from the speed violation. If you recall, we had 2 reference lines for that. But in this case, violation occurs as soon as only one line (lane line) intersect with the vehicle (bounding box) itself. But if this occurs far away from camera feed, even though we started to capture each frame of the vehicle from that point, it would be useless due to bad resolution. It could be easily processed by us, but we can’t use those images to detect and read the license plate because of the very smaller size of that image. So those snaps we going to take, frame by frame, would be useless until the vehicle is a clear sight with the camera. So, we need a mechanism to detect when the vehicle violated lane line at any given point but to start capturing snapshot only from a point beyond when the vehicle is clearly visible with its features such as a readable license plate. Throughout this time the tracking must be maintained too.</p><p>To achieve this, I have created 2 arrays. The first array would be the pixel coordinates from the lane line that we have extracted from the separate python script. Those coordinates are called from this main script (<em>lane_line_viol.py</em>) and it would be saved to <strong><em>poly_co_strat</em></strong> array. Since we return 3 values from the <em>get_lane_line_co</em> function and we needed only the last value (instead of separate x and y coordinates of the lane line, in the last value I combined the respective x value with y values which ultimately gives us the coordinates in (x, y) format), we must mention that by adding [2] at the end of the <em>get_lane_line_co()</em></p><blockquote><strong>poly_co_start = get_lane_line_co()[2] #line 115</strong></blockquote><p>So, my second array would be the pixel coordinates that consists of the reference line that I have placed close to the camera. So, in this case even though a vehicle did a violation far away from the camera itself, which only gives details to track the vehicle but nothing else, capturing snapshots of that vehicle won’t start until the vehicle intersect with this second array’s coordinates. Think it as stripe or line of pixels. Then ultimately, we have something like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*u-jvw45KskCSIAIZwWBuAg.png" /><figcaption>Lane line and the Reference Line/Stripe</figcaption></figure><p>As you can see the lane line coordinates are successfully marked as well as that second reference stripe I mentioned before, where the vehicle snaps are started to capture only when the violated vehicle interest with this second array of pixels. Keep in mind that the vehicle tracking occurred throughout the way of vehicle first started to appear in the footage until, vehicle goes out of the camera sight. Following lines show how I extracted and placed the pixel coordinates of this reference stripe/line.</p><blockquote><strong>poly_co_finish = [] #line 100<br> <br> blanked = np.zeros((1024, 2048), dtype=np.uint8)<br> pts_finish = np.array(([1065, 517], [1656, 481], [1808, 504], [1175, 616]))<br> <br> <br> cv2.fillPoly(blanked, np.int32([pts_finish]), 255)<br> # print(np.where(blanked == 255))<br> <br> x_cord_finish = np.where(blanked == 255)[1]<br> y_cord_finish = np.where(blanked == 255)[0]<br> <br> for q in range(0, len(x_cord_finish)):<br> poly_co_finish.append((x_cord_finish[q], y_cord_finish[q]))</strong></blockquote><p>Just like in the speed violation detection I have first created an empty array called <strong><em>poly_co_finish</em></strong>. Then I created a zero array, a blank mask with the same resolution as one of the frames in the video. Then I created another array called <strong><em>pts_finish</em></strong> and inputed the 4 edge location coordinates of that rectangular shape reference stripe. Then I created a polynomial which includes all the inner area of pixels in the reference stripe. Because in the <strong><em>pts_finish</em></strong> array, I’m only considering the shape of the stripe, not the area covered inside it. Then of course I extracted x and y coordinates from that area of stripe and using a for loop, I appended all this pixel coordinates of that reference stripe in (x, y) format to the <strong><em>poly_co_finish</em></strong> array.</p><p>This is where the things take a very different route compared to the speed violation detection. So, stay with me ;)</p><p>In here I have introduced 2 new arrays call <strong><em>viol_matrix</em></strong> and <strong><em>final_detect</em></strong>, where when a lane line violation occurred at any point by any vehicle, an entry will be logged into the <strong><em>viol_matrix</em></strong>. And, for the sake of evidence, I have also created a folder call “/<em>on_the_spot</em>” where all these instances which vehicle do these violations would be captured and saved regardless of their very low resolution and image quality because even though they have bad quality, they still more than good enough for manual review by human eye.</p><blockquote><strong>if len(intersection(poly_co_start, bbox_bottom_line_co)) &gt; 0 and (str((class_name+str(t))) not in str(viol_matrix)):<br> t_start = datetime.now()<br> #t_start_global=t_start<br> viol_matrix.append((str(t_start), class_name+str(t)))<br> cropped_at_spot = image.crop((int(bbox[0])-100, int(bbox[1])-100, int(bbox[2]) + 100, int(bbox[3]) + 100))<br> cropped_at_spot.save(<br> ‘outputs/on_the_spot/’ + str(<br> class_name) + str(t) + str(‘_’) + str(frame_num) + str(‘.jpg’))</strong></blockquote><p>This is the respective code for that segment. The if-condition goes as, if there’s at least one pixel coordinate is in common with the vehicle bounding box and the lane line and if that vehicle is not logged into the <strong><em>viol_matrix</em></strong> before, take the current time now and input it to the <strong><em>t_start</em></strong> variable. Then append the <strong><em>t_start</em></strong> along with vehicle type (<em>class_name</em>) and vehicle tracking ID (<em>str(t)</em>) to the <strong><em>viol_matrix</em></strong>. Then we can crop the image at the spot. I have increased the xmax and ymax values by 100 to better capture the area that covers the license plate (vehicle front). Notice that this <em>on_the_spot</em> vehicle capture and event log occurs only for the first time when a vehicle intersects with the lane line. If a vehicle does this violation more than once (which is extremely possible), it won’t be considered since this if condition won’t allow to go through the commands when the <strong><em>viol_matrix</em></strong> has a previous entry. But it won’t be a big issue since this is only a narrow view of sight. But if you want to, you can separate the <em>cropped_at_spot</em> function from current if loop and put it to a new if loop within the same alignment.</p><p>#Please note that these functions are written as there’s only one vehicle in the video footage, but they apply to all the vehicles simultaneously. Only thing is that complexity is hidden by the parent for-loop that we are working on. (Line 265)</p><p>For the bounding box coordinates, the process happens exactly as we did in the speed violation detection but only this time, instead of taking center point and taking a very small bounding box, we need a much bigger one which intersect with the lane line coordinates. Also, since YOLO doesn’t do semantic segmentation, this often gives false positives when the bounding box intersect the lane line, but not the vehicle itself. So, to satisfy both these conditions we must use the original bounding box coordinates and reduce it to a point where the bounding box is completely within the vehicle but not a constant one, unlike in the speed violation detection. So, its size will change when the vehicle moves but the increment won’t lead to a false positive since we calibrate it to be within the vehicle all the time. So, in this case I have reduced 30 points pixels from each side of the bounding box to fit it within the vehicle.</p><blockquote><strong>b_box_co = [] #line 314<br> <br> # Change accordingly<br> X, Y = np.mgrid[centre_cord_x — 30:centre_cord_x + 30, centre_cord_y — 30:centre_cord_y + 30]<br> for m in range(0, len(X)):<br> for n in range(0, len(X[0])):<br> b_box_co.append((X[m][n], Y[m][n]))</strong></blockquote><p>But now we have a bit of a performance issue. Unlike the few pixels in mini-bounding boxes we used in the speed violation, now for every frame, the program must memorize large number of pixel coordinates for simultaneous vehicles which cause the frame rate to drop drastically. To avoid that, I have only used the bottom line of bounding box pixel coordinates because when a violation occurs, it is the bottom line of the bounding box which always intersect first. Below is the code to extract only the bottom bounding box coordinates.</p><blockquote><strong>#line 306</strong></blockquote><blockquote><strong>bbox_bottom_line_co = list(<br> zip(*line(*(int(bbox[0]), int(bbox[3])), *(int(bbox[2]) , int(bbox[3])))))</strong></blockquote><p>This is very less computer intensive compared to the previous approach. (Quadruple checked ;)</p><blockquote><strong>#line 327</strong></blockquote><blockquote><strong>if len(intersection(poly_co_finish, bbox_bottom_line_co)) &gt; 0 and (str((class_name+str(t))) in str(viol_matrix)) and (str((class_name+str(t))) not in str(final_detect)) :<br> <br> <br> #Extract start time from viol matrix<br> index=str(viol_matrix).find(str((class_name+ str(t))))<br> t_start_cm=str(viol_matrix)[index-28:index-11]<br> <br> sheet.write(row_num, 0, str(t_start_cm), style)<br> sheet.write(row_num, 1, str(class_name) + str(t), style)<br> row_num += 1<br> workbook.save(‘outputs/xlsx/lane_line/details.xls’)</strong></blockquote><p>Now we have somewhat similar condition as the speed violation detection. This if condition state if a vehicle already did a violation (there should be an entry in <strong><em>viol_matrix</em></strong>) and if it not already intersected with the reference stripe (not in the <strong><em>final_detect</em></strong>) extract the start time from the <strong><em>viol_matrix</em></strong> and logged the <strong><em>t_start_cm</em></strong>, <strong><em>class_name</em></strong>(vehicle type) and <strong><em>str(t)</em></strong> (tracking id) to a spreadsheet. I have used separate columns to input this logged entry. (One for violated time and one for vehicle type and tracking id).</p><p>#To configure spreadsheet declaration, please check out the speed violation detection explanation.</p><blockquote><strong>final_detect.append((class_name + str(t))) #line 339<br> print(final_detect)<br> cropped = image.crop((int(bbox[0]), int(bbox[1]), int(bbox[2])+100, int(bbox[3])+100))<br> cropped.save(‘outputs/caps_of_detections/lane_line/’ + str(<br> class_name) + str(t) + str(‘.jpg’))</strong></blockquote><p>Then we do our usual append to the <strong><em>final_detect</em></strong> array (to avoid repetition) and cropped the higher resolution image which is very close to the camera and save the crop to a common folder of violation detected vehicles. Also, for further analysis, the following code will not only capture the vehicle frame by frame, if it has done a violation and passed the reference stripe, but also save it to a dedicated folder.</p><blockquote><strong>#line 349</strong></blockquote><blockquote><strong>if (str((class_name+ str(t))) in str(final_detect)):<br> cropped = image.crop((int(bbox[0]), int(bbox[1]), int(bbox[2])+100, int(bbox[3])+100))<br> if not os.path.isdir(‘outputs/caps_of_detections_all/lane_line/’ + str(class_name) + str(t)):<br> os.makedirs(‘outputs/caps_of_detections_all/lane_line/’+ str(class_name) + str(t))<br> cropped.save(<br> ‘outputs/caps_of_detections_all/lane_line/’ + str(class_name) + str(t) +str(‘/’)+str(frame_num)+ str(‘.jpg’))<br> <br> if os.path.isdir(<br> ‘outputs/caps_of_detections_all/lane_line/’ + str(class_name) + str(t)):<br> cropped.save(<br> ‘outputs/caps_of_detections_all/lane_line/’ + str(<br> class_name) + str(t) + str(‘/’) + str(frame_num) + str(‘.jpg’))</strong></blockquote><p>Again, this is clearly elaborated in speed violation detection article. If you are looking for more explanation, kindly check it out.</p><p>And as always Thanks for reading. :-)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f19774b3c739" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Speed Violation Detection of Real-Time Video footage using Computer Vision]]></title>
            <link>https://medium.com/@hasanthakdu/speed-violation-detection-of-real-time-video-footage-using-computer-vision-8bab662cf8b4?source=rss-2a65a53bfc1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bab662cf8b4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[yolov4]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-sort]]></category>
            <category><![CDATA[real-time-analytics]]></category>
            <dc:creator><![CDATA[Nirmal Hasantha]]></dc:creator>
            <pubDate>Tue, 28 Dec 2021 14:13:42 GMT</pubDate>
            <atom:updated>2022-01-13T08:56:26.372Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone, this is one of my projects that I have done for my Final Year Project. Basically, the project is about detecting traffic violation detection in real time just by using a (CCTV) camera. In this project I mainly focused in 3 violations, which are,</p><p>1. Speed Violation Detection</p><p>2. Lane Line Violation Detection and</p><p>3. Parking Violation Detection.</p><p>And finally;</p><p>*License Plate detection and reading</p><p>So let me give you a step-by-step guidance including all the code and repository so you can change them and might also improve them as your preference and your application.</p><p>You can find the relevant repository for the Speed violation detection from following link. Rest is coming soon!!</p><p><a href="https://github.com/hasantha-nirmal/Traffic_Violation_Detection_Yolov4_Deep-Sort">https://github.com/hasantha-nirmal/Traffic_Violation_Detection_Yolov4_Deep-Sort</a></p><p>Huge shout-out goes to theAIGuysCode, hunglc007 and nwojke for creating the backbones of this repository. Definitely check them out at:</p><p><a href="https://github.com/theAIGuysCode">https://github.com/theAIGuysCode</a></p><p><a href="https://github.com/hunglc007/tensorflow-yolov4-tflite">GitHub - hunglc007/tensorflow-yolov4-tflite: YOLOv4, YOLOv4-tiny, YOLOv3, YOLOv3-tiny Implemented in Tensorflow 2.0, Android. Convert YOLO v4 .weights tensorflow, tensorrt and tflite</a></p><p><a href="https://github.com/nwojke/deep_sort">https://github.com/nwojke/deep_sort</a></p><p>Let’s first start with the speed violation Detection system.</p><p>After the tracking system is implemented using Deep-Sort Algorithm and testing the associated object detection with per-trained Yolov4 weights, now we can distinguish each vehicle. For an example as you can see in this GIF below, each vehicle and its routine are detected and tracked as a separate entity to each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*aFmJpGXqDliXFO3zu3WTAA.gif" /><figcaption>Vehicle Detection and Tracking using Deep-sort Algorithm</figcaption></figure><p>Now the real fun begins here :)</p><p>Forget the real time scenario for now. If we narrow our problem to its core, our initial goal should be to detect the speed of those moving vehicles right after implementing the tracking. So how can we detect vehicle speed?</p><p>Well first we need to find 2 reference points, or 2 reference lines to be more correct. And we need to know the distance between those 2 lines. This distance needs to be per-known since our camera input has no information whatsoever about the depth information. After deciding that, we must somehow mark, when a vehicle first approached to the first line and again when it passed the second reference line.</p><p>In order to mark when the vehicle intersected the first reference line, I appended the vehicle name and it’s tracking ID to an array, including its timestamp from “<strong>datetime</strong>”<strong> </strong>library in python. I named this array as the “<strong><em>cache_matrix</em></strong>” (because I like the movie ;)) and when the intersection occurs at the first line, it would be appended to the array in following format.</p><blockquote><strong>cache_matrix.append((str(t_start), class_name+str(t)))</strong></blockquote><p>Here, <strong><em>t_start</em></strong> is the timestamp that is taken from the computer local time, at that point of intersection.</p><p>Now we must consider when the vehicle intersects the second reference point. This is the place where we finally calculate the speed of the vehicle to detect whether it’s passed the regulated speed limit. So, the moment when the second line was intersected by the vehicle, I’m appending that value to another variable called “<strong><em>t_finish</em></strong>”. Then immediately after that, cache matrix is checked and retrieved the “<strong><em>t_start</em></strong>” value that we appended at the first place. Then we can easily get the difference between those 2 values that calculate the time difference. Since we know the distance between those 2 lines in real-world, we can easily apply <strong><em>velocity=distance/time </em></strong>equation and calculate the speed. (And yes, this algorithm is best suited for straight roads but by narrowing the distance between 2 intersection we can use it to calculate the speed in curved roads too).</p><p>Now it’s time to go with the code itself. Basically, in this project, I was in need to record the vehicle type, vehicle tracking ID and the vehicle speed in the spreadsheet too for the license plate recognition. Also, I must capture a snapshot of the violated vehicle and save it too. Also in this case, if a vehicle did a violation, a snapshot of that vehicle is saved to a directory with its own vehicle type and tracking id, and this would continue capturing snaps of the vehicle until it goes out-of-sight of the camera footage.</p><p>Let’s go the <strong><em>speed_violation_detection.py</em></strong> inside the repository. Starting from the line 289.</p><blockquote><strong># update tracks. #line 289<br> for track in tracker.tracks:<br> if not track.is_confirmed() or track.time_since_update &gt; 1:<br> continue<br> bbox = track.to_tlbr()<br> class_name = track.get_class()<br> t = int(str(track.track_id))<br> <br> centre_cord_x = int((int(bbox[0]) + int(bbox[2])) / 2)<br> centre_cord_y = int((int(bbox[1]) + int(bbox[3])) / 2)</strong></blockquote><p>As you can see, there are several variables introduced here. Keep in mind in this for-loop, only one vehicle is considered. All the vehicles are tracked simultaneously, but for the easiness, within this loop, we can consider it like there’s only one vehicle in the road and all the functions that we write only applies to it. Of course, this functionality applies to all the vehicle simultaneous but again you don’t have to bother thinking all of them at the same time. This helps to reduce the complexity of thinking, not the code itself.</p><p>So, imagine now we have one vehicle approaching to the first reference line. Its bounding box coordinates (xmin, ymin, xmax, ymax format) are in the variable <strong><em>bbox</em>. </strong>Vehicle type and it’s tracking id is in the<strong> <em>class_name</em> </strong>and<strong> <em>t</em> </strong>variables<strong> </strong>respectively<strong>.</strong></p><p>Then I have calculated the central coordinates of that bounding box. As you can see, I have appended the x and y coordinates of the center points of bounding box to <strong><em>centre_cord_x</em></strong> and <strong><em>centre_cord_y</em></strong>. But why? Well in YOLO object detection, the bounding box is much larger in the vehicles that are close to the camera than the vehicles that are far away from the camera sight. When calculating the speed, this introduces a problem by causing additional acceleration. Since in YOLO, the bounding box itself represent the vehicle itself, I have noticed situation such as the increased bounding box (due to getting close to the camera) intersect the second reference line, way before the actual vehicle approach to the reference line, hence giving a very high speed than it supposed to. This can be eradicated if we the bounding box we have is constant and which represent only the vehicle, not even the free space around it. This is achieved by taking the central x and y coordinates and creating a mini-bounding box that always stays withing the middle of the vehicle and does not represent any free space around the vehicle or getting bigger and bigger every time when the vehicle is close to the camera.</p><blockquote><strong>#Define the speed detection fns #line 313<br> b_box_co = []<br> <br> # Change accordingly<br> X, Y = np.mgrid[centre_cord_x — 10:centre_cord_x + 10, centre_cord_y — 10:centre_cord_y + 10]<br> for m in range(0, len(X)):<br> for n in range(0, len(X[0])):<br> b_box_co.append((X[m][n], Y[m][n]))</strong></blockquote><p>As it is shown here that, first I have introduced an array called <strong><em>b_box_co</em></strong> and appended only that mini, constant bounding box coordinates of the vehicle to it. In order to make the mini box, I have taken 10-pixel points from up, down, left and right to the center coordinates points of x, y which mentioned above. The reason I have taken all the coordinates points on mini bounding box into account is that to create an array of pixel coordinate to intersection between the reference line coordinates and the newly created mini- bounding box coordinates.</p><p>Creating of those 2 reference points/lines and append their coordinates points are as follows. Starting from line 88.</p><blockquote><strong>poly_co_finish = [] #line 88<br> <br> blanked = np.zeros((1024,2048), dtype=np.uint8)<br> pts_finish = np.array(([634,800], [1279,638], [1330,641], [722,851]))<br> cv2.fillPoly(blanked, np.int32([pts_finish]), 255)<br> #print(np.where(blanked == 255))<br> <br> x_cord_finish = np.where(blanked == 255)[1]<br> y_cord_finish = np.where(blanked == 255)[0]<br> <br> for q in range(0, len(x_cord_finish)):<br> poly_co_finish.append((x_cord_finish[q],y_cord_finish[q]))</strong></blockquote><p>First, I have created 2 empty arrays for append the pixel coordinates of the 2 reference points as <strong><em>poly_co_start</em></strong> and <strong><em>poly_co_finish</em></strong>. Here instead of taking a single pixel line as a reference line I have taken a stripe of pixel coordinates because sometime the intersection doesn’t occur if the reference lines are too slim. Hence the vehicle passes the reference line without any intersection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*C_t-xR30nKGAQeDxfJjbYQ.png" /><figcaption>Reference Lines/Stripes</figcaption></figure><p>So, I have first created a blank mask which the size matches to the video resolution. (Which also fit to the frame size) and gave the coordinate points of my rectangular stripe as an array in <strong><em>pts_finish</em></strong>. Then using the <em>fillpoly</em> function in <em>cv2</em>, I have marked all that pixel coordinates in that blanked image with the pixel value of 255.</p><p>Then I introduced <strong><em>x_cord_finish</em></strong> and <strong><em>y_cord_finish</em></strong> to acquire all the pixel coordinates at binary image, that has a pixel value equal to 255. Now we have right coordinates values of the pixels of the reference line (stripe) that matched to the appropriate location of the original video footage. So, I have iterated all the coordinates values of the pixels in the reference stripe to an array called <strong><em>poly_co_finish</em></strong>, which we can later use for the intersection of vehicle mini-bounding box.</p><p><em>#I have only shown here the pixel coordinated extraction for the last reference stripe. Similar procedure applies to the first reference line too for the coordinate extraction.</em></p><p>Since we have successfully extracted the coordinates of the reference lines and the mini-bounding box coordinates, now it’s time to write the conditions of what to do when they intersect each other.</p><p>Let’s start with our first intersection.</p><blockquote><strong>#line 323</strong></blockquote><blockquote><strong>if len(intersection(poly_co_start, b_box_co)) &gt; 0 and (str((class_name+str(t))) not in str(cache_matrix)):<br> t_start = datetime.now()<br> cache_matrix.append((str(t_start), class_name+str(t)))</strong></blockquote><p>As you can see, I have created the conditions as when a vehicle first intersect with the first reference line. Which is programmed as if there are any similar coordinate points between the <strong><em>poly_co_start</em></strong> and the <strong><em>b_box_co</em></strong> and if there’s at least 1 coordinate point in common, append the <strong><em>t_start</em></strong>, vehicle type (<strong><em>class_name</em></strong>) and it’s tracking id (<strong><em>str(t)</em></strong>) to the cache matrix only if it is not appended to the cache matrix before. Because we have more than one frame that intersect the bounding box with the referenced stripe, which cause to append several entries to the cache matrix which cause errors. So, we must make sure that the append occurs only one time and that time would be when the vehicle intersect with the reference stripe for the first time.</p><p>Then imagine after the first intersection and the entry logging, the vehicle keeps moving toward the second reference stripe. When the vehicle intersected immediately after the second intersection, the following conditions and tasks need to perform.</p><blockquote><strong>#line 332</strong></blockquote><blockquote><strong>if len(intersection(poly_co_finish, b_box_co)) &gt; 0 and (str((class_name+str(t))) in str(cache_matrix)) and (str((class_name+str(t))) not in str(viol_detect)) :<br> t_finish = datetime.now()<br> <br> #Extract start time from cache matrix<br> index=str(cache_matrix).find(str((class_name+ str(t))))<br> t_start_cm=str(cache_matrix)[index-28:index-11]<br> date_time_obj = datetime.strptime(t_start_cm, ‘%y-%m-%d %H:%M:%S’)</strong></blockquote><p>This if-condition is little bit complex compared to the previous one. As you can see, I have introduced an array called “<strong><em>viol_detect</em></strong>” to finally detect the violators who violated the given speed limit.</p><p>Condition stands for if there’s at least one pixel coordinate that is found in common with the <strong><em>poly_co_finish</em></strong> and <strong><em>b_box_co</em></strong> pixel coordinate values, check if that vehicle has done it first intersection by checking the vehicle type (<strong><em>class_name</em></strong>) and vehicle tracking id (<strong><em>str(t)</em></strong>) in the <strong><em>cache_matrix</em></strong> and to again avoid more than one intersections, check for any previous append entries in the violation matrix about the same intersection.</p><p>If this if-condition is <em>True</em>, then immediately check the current time and append the value to a variable call <strong><em>t_finish</em></strong>. Then we must extract the <strong><em>t_start</em></strong> value from the cache matrix, since we passed the if condition, we surely know such an entry exits in the <strong><em>cache_matrix</em></strong> array. To make the extraction easier first I introduced a variable called index which act as a milestone. Within this, read the <strong><em>cache_matrix</em></strong> as a string and using the <em>find</em> function we can get the position of the starting string of the vehicle type and the tracking id of the cache matrix. Since the time we recorded in is in one of the standard-time formats (‘%y-%m-%d %H:%M:%S’), that value is positioned from certain and constant positions away from the string of the vehicle class. In this case we can find the <strong><em>t_start</em></strong> in its standard format by taking in-between 28 characters to the left and 11 characters to the left from the index value that we have calculated before. But this value, <strong><em>t_start_cm</em></strong> is again a string and in order to calculate the time difference, we have to turn this back to a standard timestamp and that was done by <em>datetime.strptime</em> function and appended it to a variable called <strong><em>date_time_obj</em></strong>.</p><p>Now we can calculate the speed since we can calculate the time difference.</p><blockquote><strong>def speed(time_diff,distance): #line 131<br> return distance/float(time_diff)</strong></blockquote><p>As you can see, I have created a very simple speed function and gave the time as an attribute and since we need the time difference in seconds, used the <em>total_seconds()</em> when gives the input to the function. The distance between 2 reference stripes is taken as 10m in this case.</p><blockquote><strong>velocity=speed((t_finish-date_time_obj).total_seconds(),10) #line 346<br> if velocity&gt;0:#meters per second</strong></blockquote><p>Since now we have successfully obtained the vehicle velocity, we can perform an if condition to detect violators who exceeded the speed limit. For demonstration purposes, I have taken all the vehicles that have speed limit above 0.</p><blockquote><strong>sheet.write(row_num, 0, str(t_start_cm),style) #line 348<br> sheet.write(row_num, 1, str(round(velocity,2)),style)<br> sheet.write(row_num, 2,str(class_name)+str(t),style)<br> row_num += 1<br> workbook.save(‘outputs/xlsx/speed/vehicle_details.xls’)</strong></blockquote><p>This is where we going to log our outcomes to a spreadsheet so later anyone can see when the vehicle first detected, vehicle speed when it did the violation and the vehicle class and the vehicle type. I have placed these 3 entries in 3 columns in a single row and make sure to increase the row number by one to avoid the log replacements due to more than one vehicle are considered simultaneously. The spreadsheet declaration is as follows.</p><blockquote><strong># open existing workbook #line 122<br> workbook = xlwt.Workbook()<br> sheet = workbook.add_sheet(“Sheet1”)<br> <br> # Specifying style<br> style = xlwt.easyxf(‘font: bold 1’)<br> row_num=0</strong></blockquote><p>Now we can append the violated vehicle details such as start time, rounded velocity and class name and tracking id to <strong><em>viol_detect</em></strong> array so we can make sure no multiple detection of the same vehicle has occurred. (Related to the if-condition)</p><blockquote><strong>viol_detect.append((t_start_cm,round(velocity,2), class_name+str(t))) #line(355)</strong></blockquote><p>So, in order to feed this vehicle to the license plate recognition system and for manual review as evidence, we must capture a snap of this vehicle, the moment it has done the violation. The respective code is as follows.</p><blockquote><strong>#line 358</strong></blockquote><blockquote><strong>cropped=image.crop((int(bbox[0]), int(bbox[1]), int(bbox[2])+100, int(bbox[3])+100))<br> cropped.save(‘outputs/caps_of_detections/speed/’ +str(class_name)+str(t)+str(‘.jpg’))</strong></blockquote><p>So, I cropped the image using the original bounding box coordinates (not the mini-bounding box coordinates) and increased its size (xmax and ymax) coordinates by 100 pixels to make sure the cropping has captured all the details required for the license plate detection and recognition. Then I saved the crop to an output folder by naming the image by its class name and tracking id. (Ex: car3.jpg)</p><blockquote><strong>#line 369</strong></blockquote><blockquote><strong>if (str((class_name+ str(t))) in str(viol_detect)):<br> cropped = image.crop((int(bbox[0]), int(bbox[1]), int(bbox[2])+100, int(bbox[3])+100))<br> if not os.path.isdir(‘outputs/caps_of_detections_all/speed/’ + str(class_name) + str(t)):<br> os.makedirs(‘outputs/caps_of_detections_all/speed/’+ str(class_name) + str(t))<br> cropped.save(<br> ‘outputs/caps_of_detections_all/speed/’ + str(class_name) + str(t) +str(‘/’)+str(frame_num)+ str(‘.jpg’))</strong></blockquote><p>This above code is highly optional. Basically, it’s going to capture the violated vehicles frame by frame and save those captures to a dedicated folder which named after the vehicle’s class type and the tracking id. So, if a vehicle is detected and appended to the <strong><em>viol_detect</em></strong> array, it’s going to crop the image first. Then it first search is there a directory created before with the name and the vehicle type. If there’s no such a path exits, the program first creates that directory and then save the image with its name as the frame number, in order to avoid any replacements from new detection. (Since the same vehicle can’t be in a single frame more than once).</p><p>The following code is just a follow-up which says that if the folder exits, then go ahead and save the image as the frame id as its image name. You can change the image type as you like. (Ex: png, jpg)</p><blockquote><strong>#line 376</strong></blockquote><blockquote><strong>if os.path.isdir(<br> ‘outputs/caps_of_detections_all/speed/’ + str(class_name) + str(t)):<br> cropped.save(<br> ‘outputs/caps_of_detections_all/speed/’ + str(<br> class_name) + str(t) + str(‘/’) + str(frame_num) + str(‘.jpg’))</strong></blockquote><p>This is a test output video from the program. (Not showing the real time performance). In order to get this video-like frame rate you must use the GPU acceleration either by using CUDA or openGL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*dIzkzCQEWgun_kX7HSRLwQ.gif" /><figcaption>Final Outcome</figcaption></figure><p>Thank you so much for reading :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bab662cf8b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>