<?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 Keshav Tangri on Medium]]></title>
        <description><![CDATA[Stories by Keshav Tangri on Medium]]></description>
        <link>https://medium.com/@zukayu?source=rss-2f80954db0c3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*pTwL4llDcwJ38BZ5</url>
            <title>Stories by Keshav Tangri on Medium</title>
            <link>https://medium.com/@zukayu?source=rss-2f80954db0c3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 19:53:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zukayu/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[EyeAttend — Facial Recognition based Attendance System from scratch.]]></title>
            <link>https://medium.com/analytics-vidhya/eyeattend-facial-recognition-based-attendance-system-from-scratch-4c07ce9da319?source=rss-2f80954db0c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c07ce9da319</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Keshav Tangri]]></dc:creator>
            <pubDate>Sun, 21 Mar 2021 18:23:16 GMT</pubDate>
            <atom:updated>2021-03-26T07:11:53.965Z</atom:updated>
            <content:encoded><![CDATA[<h3>(Part-III)EyeAttend — Facial Recognition based Attendance System from scratch. — A complete approach.</h3><h3>Introduction</h3><p>Welcome to Part III of our blog series, EyeAttend. Finally after 2 stories on our vision and general overview of the project, we will begin our coding in this story. Without wasting much of your time, let’s dig in.</p><h3>Recap</h3><p>Before starting, let’s revise where we left in the previous story. So, we discussed about the overview of the Deep learning models and we briefed about the following models in our Project:</p><ol><li><strong>keras-facenet</strong> (Transfer Learning)</li><li><strong>mask-detector</strong></li><li><strong>real/fake detector</strong></li></ol><p>You can get familier with the project by taking a quick glance on Part-I and Part-II of this series.</p><p>Data is the main resource to train a Deep Learning Model. In our project, the first type of data required is the classroom data. In order to perform face matching, we actually need a database, from where we will draw our image comaparison. So first, we will be generating our classroom data. For that our requirement is student’s face images. Since during the development of this project, schools and college in our region were shut down due to Covid-19 outbreak, we have to come up with a way around to generate data.</p><h3>Data Generation</h3><h4>1. Collection</h4><p>We recollected our group images, local trips and other images that we had in our gallary. Next, we put them in a folder for consideration. These images do include duplicate faces, but we required collection of maximum faces so that we could to generate our classroom batch. Our trial was to get images with maximum faces to reduce this collection effort. Storing it in a directory marks the completion of this phase. See the below attached image for reference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*NhCEMLLj6bPk9fiKrxyoTQ.png" /><figcaption>Raw Data : Group photos for extracting faces</figcaption></figure><h4>2. Extraction</h4><p>Next, we need to extract the faces from these images. Some images have them in potrait mode, while some are clicked at an angle. Extracting faces manually is a tedious task. As mentioned previously that we will be using transfer learning for face extraction and facial recognition, we will use the MTCNN (Multi Task Cascaded Neural Network) model for face extraction. MTCNN module can be installed from PyPI at [1]. You can install it in your machine via terminal by executing the following command :</p><pre>pip3 install mtcnn</pre><p>Please note that before installing this, you have pip3 installed on your machine.</p><p>After installing MTCNN, we will be importing the necessary libraries for Face extraction</p><pre>import os<br>import numpy as np<br>from PIL import Image<br>from mtcnn import MTCNN</pre><p>After importing the libraries, we will store our source and target path in a variable and initialize mtcnn object. You can also use Argument Parser to input these folder and output path directly in the terminal.</p><pre>detector = MTCNN()<br>folder_path = &#39;/home/username/Eye_Attend/Eye_Attend/images&#39;<br>output_path = &#39;/home/username/Eye_Attend/Eye_Attend/FACES_224&#39;</pre><p>To understand how MTCNN works, consider the following example :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hG8hNRx3B2bPdqeqPqV2uw.jpeg" /><figcaption>Example Image</figcaption></figure><p>If we run MTCNN detector on this image (via the below code), we get the following output:</p><p><strong>Code:</strong></p><pre>img = Image.open(folder_path+os.sep+&quot;IMG_20171130_105137.jpg&quot;)<br>pixels = np.asarray(img)<br>results = detector.detect_faces(pixels)<br>print(len(results))<br>print(results)</pre><p><strong>Output:</strong></p><pre>6<br>[</pre><pre>{&#39;box&#39;: [602, 470, 358, 454], &#39;confidence&#39;: 1.0, <br>&#39;keypoints&#39;: {&#39;left_eye&#39;: (724, 643), &#39;right_eye&#39;: (888, 662), &#39;nose&#39;: (816, 743), &#39;mouth_left&#39;: (718, 807), &#39;mouth_right&#39;: (863, 825)}}, </pre><pre>{&#39;box&#39;: [1066, 401, 228, 305], &#39;confidence&#39;: 0.9999994039535522, &#39;keypoints&#39;: {&#39;left_eye&#39;: (1136, 518), &#39;right_eye&#39;: (1244, 523), &#39;nose&#39;: (1196, 571), &#39;mouth_left&#39;: (1137, 624), &#39;mouth_right&#39;: (1235, 632)}}, </pre><pre>{&#39;box&#39;: [1542, 538, 226, 283], &#39;confidence&#39;: 0.9999988079071045, &#39;keypoints&#39;: {&#39;left_eye&#39;: (1591, 645), &#39;right_eye&#39;: (1692, 646), &#39;nose&#39;: (1625, 692), &#39;mouth_left&#39;: (1596, 755), &#39;mouth_right&#39;: (1671, 758)}}, </pre><pre>{&#39;box&#39;: [1764, 844, 477, 588], &#39;confidence&#39;: 0.9999927282333374, &#39;keypoints&#39;: {&#39;left_eye&#39;: (1873, 1078), &#39;right_eye&#39;: (2096, 1067), &#39;nose&#39;: (1968, 1204), &#39;mouth_left&#39;: (1898, 1299), &#39;mouth_right&#39;: (2088, 1294)}}, </pre><pre>{&#39;box&#39;: [1038, 951, 453, 523], &#39;confidence&#39;: 0.9999831914901733, &#39;keypoints&#39;: {&#39;left_eye&#39;: (1162, 1174), &#39;right_eye&#39;: (1351, 1109), &#39;nose&#39;: (1289, 1293), &#39;mouth_left&#39;: (1244, 1375), &#39;mouth_right&#39;: (1410, 1313)}}, </pre><pre>{&#39;box&#39;: [-92, 769, 623, 850], &#39;confidence&#39;: 0.9803318977355957, &#39;keypoints&#39;: {&#39;left_eye&#39;: (86, 1089), &#39;right_eye&#39;: (375, 1070), &#39;nose&#39;: (268, 1253), &#39;mouth_left&#39;: (84, 1357), &#39;mouth_right&#39;: (392, 1330)}}</pre><pre>]</pre><p>The output is a list of dictionaries, with each dictionary having ‘box’, ‘confidence’ and ‘keypoints’ as the keys. The key ‘keypoints’ is another dictionary with ‘left_eye’, ‘right_eye’, ‘nose’, ‘mouth_left’ and‘mouth_right’ keys. The box key list consists of x1, y1, width and height. This refers to the bounding box of the face and we can use it to extract the face from the image.</p><p>In a similar way discussed above, we will iterate over the images in our source folder one by one and detect all the faces from the current image, extract their bounding box coordinates and then store the face images in the output_folder. Following code helps us to extract the faces from our input directory path and saves the images in the output path.</p><pre>for image in os.listdir(folder_path):<br>    img = Image.open(folder_path+os.sep+image)<br>    pixels = np.asarray(img)<br>    filename , extension = image.split(&quot;.&quot;)<br>    results = detector.detect_faces(pixels)<br>    for i in range(len(results)):<br>        x1, y1, width, height = results[i][&#39;box&#39;]<br>        x1, y1 = abs(x1), abs(y1)<br>        x2, y2 = x1 + width, y1 + height<br>        face = pixels[y1:y2, x1:x2]<br>        face_image = Image.fromarray(face)<br>        face_image = face_image.resize((224, 224))<br>        face_image.save(<br>            output_path+os.sep+filename+&quot;_&quot;+str(i)+&quot;.&quot;+extension<br>        )</pre><p>Upon each iteration, the image variable is converted to numpy array, which is passed as an argument to detector.detect() for extracting the face details as explained in the previous example. We also store the filename and the extension of the image to save the face image with the same prefix. We iterate on every face detected and extract the face via the bounding box coordinates from numpy array of the image. Resize it to 224,244 dimensions as we will be requiring a pretrained model at a later stage, with weights on imagenet dataset which accepts224x224 image. Finally we will save the resulting face in the output directory. Below is the result on our source folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*OSq33f0JG5HyHYpKYR4WNQ.png" /><figcaption>Output Faces of a Classroom Batch</figcaption></figure><h4>3. Segregation:</h4><p>After extracting the possible detected faces from group images, we have some unwanted, distorted, blurred and duplicate faces (due to duplicate individuals in images). Next step is to take out quality images from this dataset. This will be our segregation phase. We will pick out quality images which are visible differentiable and less pixelated from others. In a new directory, these images will be pasted and the filename will be changed to the roll number of the individual. Reason for doing this will be explained later on. The outcome is seen as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*SlIC4a-GtaTPSQBTAosQ3A.png" /><figcaption>Segregated Faces of Students</figcaption></figure><p>You might observe some roll numbers missing, thats because we were not able to find images of few individuals in our gallary. Our next aim is to export this data over the Database so that it can be used in accordance the flow of our application when required.</p><p>A question that comes to mind is, do we actually need Image data for facial recognition? If you give it a thought, then you will understand that we require the face data only for comparing the face data sent from frontend, and you think deeper, then we are actually comparing the embeddings of the image attained from frontend with the embeddings of the faces of a particular batch from backend database. So, instead of storing 60–80 images and then retrieving each of them and hence calculating their embeddings is a computational expensive task.</p><p>So, a better wayout will be uploading the embeddings per face and other student details over the MySQL Data base.</p><h4>4. Storing in Database:</h4><p>We are using MySQL database in this project and now the next move is to upload the students data on DB. Along with the face embeddings, we will upload other details too, i.e name, email, college email, batch , branch etc. To be clear, the above classroom data is for branch ‘cse’ and batch 2017–21.</p><p>Our next challenge is to store numpy array in MySQL. This challenge was tackled by converting the numpy array into bytes and storing it in a Column of type LONGBLOB. This part was tricker however this too shall pass and it did pass. Lets see the code for uploading the data on MySQL table.</p><p><strong>Student Details: </strong>Every Classroom’s details such a roll number, email id etc is kept as an Excel Record by the CR and Class Incharge. Being ex-CR for 2 years I too, had that student record list. We used the details in the excel sheet with face images (arranged in ascending order of roll number) and combined the two to automate the task of uploading the data on DB.</p><p>Before importing the libraries, we have to install the pretrained keras facenet model to be used for transfer learning.</p><pre>pip3 install keras-facenet</pre><p>After successful install, import the essential libraries and make an instance of Facenet from keras-facenet [2]:</p><pre>import os<br>import pickle<br>import numpy as np<br>import pandas as pd<br>from PIL import Image<br>import mysql.connector<br>from keras_facenet import FaceNet<br>from tensorflow.keras.preprocessing.image import img_to_array,array_to_img</pre><pre>embedder = FaceNet() </pre><p>Once everything is imported, we will open our excel file with students details. For privacy concerns, emails and personal details are omitted from the images. We use pandas library to read the data.</p><pre>df = pd.read_excel(“StudentListEmail_ccet_gmail.xlsx”)<br>       .fillna(“example@domain.com”)</pre><pre>df.head(5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*M0YFrPGjBVAOQsvrUIK7jA@2x.jpeg" /></figure><p>The above image shows output of a class’s student details. Using this and image of student’s face we will upload the same on MySQL DB.</p><p>Our next task is to calculate embeddings for each face and we store it in a list.</p><p>NOTE: The roll numbers in the excel file and the filenames of faces are same and equal in number, sorted in ascending order. There is no extra entry in excel with a roll number which is not present in our classroom folder and vice versa.</p><p>See the following code snippet for calculating embedding.</p><pre>name = list(df[&#39;First Name &#39;])<br>email = list(df[&#39;Email [Secondary]&#39;])<br>ccet_email = list(df[&#39;Email Address [CCET]&#39;])<br>roll= list(df[&#39;Roll Number&#39;])</pre><pre>class_temp_path =&quot;/home/username/Eye_Attend/Eye_Attend_Final/classroom_224&quot;</pre><pre>temp_totalEmbeddings = []<br>for faces in os.listdir(class_temp_path):<br>    face = Image.open(class_temp_path+os.sep+faces)<br>    face = img_to_array(face)<br>    face = np.expand_dims(face, axis=0)<br>    embedding = embedder.embeddings(face)<br>    temp_totalEmbeddings.append(embedding)</pre><p>The temp_totalEmbeddings list hold the embeddings of each face in our classroom. Each embedding is a 512 – dimensional Vector as shown below :</p><pre>print(temp_totalEmbeddings[0].shape)<br>print(len(temp_totalEmbeddings))<br>print(len(roll))</pre><pre>#Output <br>(1, 512)<br>40<br>40</pre><p>This shows that we have 40 students in our excel, and 40 images corresponding to them (sorted by roll number asc) in classroom folder.</p><p>Since each embedding is 512 dimensional vector, therefore our final matrix will be of dimensional 40 x 512.</p><p>Next we will see the upload code to upload all this data in the MySQL DB.</p><pre>branch_ = &#39;cse&#39;<br>batch_ = &#39;2017&#39;<br>conn = mysql.connector.connect(<br>    host=&quot;localhost&quot;,<br>    user=&quot;root&quot;,<br>    password=&quot;&quot;,<br>    database=&quot;eyeattend&quot;<br>    )<br>if conn.is_connected():<br>    print(&quot;Successfully connected&quot;)<br>    mycursor = conn.cursor()<br>    create_tab = &quot;CREATE TABLE IF NOT EXISTS `batch_2017` ( `roll_no` varchar(10) NOT NULL, \<br>                 `name` varchar(50) NOT NULL,\<br>                 `branch` text NOT NULL,\<br>                 `batch` text NOT NULL,\<br>                 `email` varchar(50) NOT NULL,\<br>                 `ccet_email` varchar(50) NOT NULL,\<br>                 `photo_embedd` longblob NOT NULL,\<br>                 PRIMARY KEY (`roll_no`) ) &quot;<br>    <br>    mycursor.execute(create_tab)<br>    conn.commit()<br>    <br>    for i in range(len(roll)):<br>        r = str(roll[i])<br>        naam = str(name[i])<br>        ema = str(email[i])<br>        ccet = str(ccet_email[i])<br>        embed = temp_totalEmbeddings[i]<br>        pickemb = embed.dumps()<br>        mycursor.execute(&quot;INSERT INTO batch_2017 VALUES (%s,%s,%s,%s,%s,%s,%s)&quot;,(r,naam,branch_,batch_,ema,ccet,pickemb))<br>        conn.commit()<br>        # Closing the connection<br>    conn.close()<br>    <br>else:<br>    print(&#39;Error in connecting with database&#39;)</pre><p>Here we utilise the mysql.connector package. branch and batch are the variables that can be used to tell which branch and batch of student data will be uploaded into the DB.</p><p>First, we try to make a connection with our backend Database. If the Connection is successful, we print out a success message and make a cursor object. Next we will run our CREATE TABLE query to make the table for the particular batch if it does not exist. Further, we iterate over the student details, and their face image embeddings one by one and insert them onto the Database. As mentioned earlier, to upload embeddings, we have to encode them in bytes form as our image_embed attribute accepts longblob. For this, we use the dumps() function and upload the data over DB. The output of this code in DB is shown below :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*kVOA745ryc2wIcm66Vu8Fg.png" /><figcaption>DB Output</figcaption></figure><p>In this way, data of other streams such as ECE, CIVIL, MECH, BIOTECH, EE etc of the same batch can be uploaded in the same way. This is how we built our Database for the project. In future blogs, you will see how we will fetch only the roll numbers and embeddings for comaprison and how we will mark the attendance via facial recognition.</p><h3>Conclusion</h3><p>So this marks the conclusion of the blog. In this blog you saw how we used the pretrained keras-facenet model for generating vector embeddings of the face images and how we created our classroom database on MySQL. In the next blog, we will build the mask detector model. Stay tuned for that and we hope that you enjoyed this blog. Do like and share with your circle.</p><h3>References</h3><p>[1] <a href="https://pypi.org/project/mtcnn/">https://pypi.org/project/mtcnn/</a></p><p>[2] <a href="https://pypi.org/project/keras-facenet/">https://pypi.org/project/keras-facenet/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c07ce9da319" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/eyeattend-facial-recognition-based-attendance-system-from-scratch-4c07ce9da319">EyeAttend — Facial Recognition based Attendance System from scratch.</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[EyeAttend – Facial Recognition based Attendance System from scratch.]]></title>
            <link>https://medium.com/analytics-vidhya/eyeattend-facial-recognition-based-attendance-system-from-scratch-c93dbab8c17?source=rss-2f80954db0c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c93dbab8c17</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Keshav Tangri]]></dc:creator>
            <pubDate>Thu, 25 Feb 2021 17:21:59 GMT</pubDate>
            <atom:updated>2021-02-25T17:21:59.211Z</atom:updated>
            <content:encoded><![CDATA[<h3>EyeAttend – Facial Recognition based Attendance System from scratch. – A complete approach. (Part-II)</h3><h3>Introduction</h3><p>Greetings readers, welcome to second part of the series EyeAttend. In this blog, we will go through the analysis of the problem statement at hand, traditional methodology, our proposed solution and the planning undertaken for the execution of the solution. We will cover the flow of events that are taking place in the whole project and represent it with the help of a flowchart. So let’s dive in.</p><h3>Understanding Problem Statement</h3><p>Before beginning with a solution to any problem, it is always advised to understand the problem first. Therefore, we begin by explaining the current/traditional methodology being undertaken for taking attendance.</p><h4>Traditional Methodology</h4><ol><li>Initially after a lectures ends, the class representative will have to stand by the podium and call out each roll number of the student and the concerned individual will revert back with present if he/she is in the class.</li><li>Next the class representative(CR) will take a note of the present and absent and/or absent students.</li><li>This list is then sent to concerned subject teacher. The authority to fill attendance is not given to the class representative.</li><li>The teacher keeps note of this in his/her register.</li><li>This cycle is repeated till the end of semester</li></ol><h4>Limitations</h4><p>There are many limitations involved with this particular mechanism. Few of them are as follows:</p><ol><li><strong>Proxy: </strong>Proxy means Fake attendance in lectures in colleges. The above methodology is prone to proxy at the CR’s level. He might mark present for his friends even though they are roaming out in the city.</li><li><strong>Sharing: </strong>It is difficult to share the attendance with the students. Some times it is due to no updation in the register, or the professor is unavailable etc. In countries like India, where 75% attendance is compulsary in colleges, this is a big issue for the students.</li><li><strong>No Softcopy: </strong>If the attendance sheet is to be forwarded after the end of the semester, it is difficult to do so as there is no softcopy maintained. This results into another time wastage for scanning the register.</li><li><strong>Extensive Manual Work</strong>: whether it is updating attendance on an excel or a register, the traditional methodology involves a lot of manual effort for accomplishing the task.</li><li><strong>Time: </strong>The whole process is somewhat time consuming.</li><li><strong>Editing: </strong>In case of an absentee due to illness, some competition or any reason which has a valid proof and has to be converted back to present, the professor has to use whitener to correct it which makes the register kinda messy.</li></ol><h4>Proposal for an Intelligent System</h4><p>Our proposal is a hassle free deployment of a system which do not require the need of CR to call out names and teacher itself can take the attendance by just clicking a photo of the students.</p><h4>Solution Overview:</h4><p>As you may have already seen in the video demonstration in Part-I, we first upload our image to the database, next the machine learning model extracts faces from the image and then based on the teacher, subject code, and batch facial recognition is performed between the extracted face and the classroom faces. Once this is done, the presentees and absentees list is generated and gets dynamically updated onthe DataBase. This final list is sent back to the front end for the teacher. The solution also provides easy download facility and in future versions, we can add graphical analytics of the data collected to visually understand trends over the years.</p><h3>Flow of the project (ML Model flow)</h3><p>Below is the attached flowchart of our project ML models. We have segregated models with different functionality for easy future updation and scalability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*dfWmAW_LdV32OtLojG5n5g@2x.jpeg" /><figcaption>Flow of ML Models</figcaption></figure><p>The above flow shows how our image is processed by the various models. Initially we thought of making the project for both masked and unmasked scenarios, but due to hardware constrains we took the path of unmasked only. However the new models can be developed and the code can updated in order to incorporate Masked version too.</p><p>So, initially when the image is given to the script, it will extract the facial regions from it. It will detect the presence of faces and will extract it in 224x224x3 dimensions. Next we iterate over the number of faces and for each face, we do the following :</p><ol><li>Check if it is masked or unmasked</li><li>Check if it is a real person or a picture of person’s face</li><li>Check who is the person from the classroom (facial recognition).</li><li>Mark his roll number and keep him in presentees record.</li></ol><h3>Models Overview</h3><p>As mentioned in the above section, we have to develop different models for our model. Now this is because as the new students arrive at campus, we might need to train the model again to make it more robust. This is the reason why the models are broken down into different segments so that one segment can be upgraded and then reused without affecting the other models. Listed below are the models which we have used and which we are going to develop:</p><ol><li><strong>keras-facenet</strong> (Transfer Learning): This is used for extracting faces and creation of embeddings of face images[1]. We have used a pretrained facenet model that converts a face image into <strong>512 dimensional vector</strong>. It detect and extract faces via the <strong>MTCNN (Multi Task Cascaded Neural Networks).</strong></li><li><strong>mask-detector: </strong>We will be developing this model to detect whether the person’s face has a mask or not. This is done to separate the different use case and with mask, the classroom database, real/fake detector etc will be developed differently.</li><li><strong>real/fake detector: </strong>The real/fake detector or liveliness detector model is used to check if the actual human is present. This is minimize the effort of proxy in our project as it might be possible the someone just opens up the laptop screen with their friend’s face image so that his/her roll number can be counted as presentess.</li></ol><h3><strong>Conclusion</strong></h3><p>In this part of the series, you learned about the general overview of how the Deep Learning/Machine Learning things are going at the backend. We are sorry that like Part — I, this part doesn’t have code too, but we will be starting with the model development in Part — III of the series. Stay tuned for that and follow us on LinkedIn : <a href="https://www.linkedin.com/in/keshav-t-7ab782104/">Keshav Tangri</a>, <a href="https://www.linkedin.com/in/abhijeet-baruah-bb1b08165/">Abhijeet Baruah</a>, &amp; <a href="https://www.linkedin.com/in/aarushi-sood-b2b11b154/">Aarushi Sood</a>.Let’s catch up in the next blog. Till then, have a great week!</p><h3>References</h3><p>[1]. <a href="https://github.com/faustomorales/keras-facenet">https://github.com/faustomorales/keras-facenet</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c93dbab8c17" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/eyeattend-facial-recognition-based-attendance-system-from-scratch-c93dbab8c17">EyeAttend – Facial Recognition based Attendance System from scratch.</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[EyeAttend — Facial Recognition based Attendance System from scratch.]]></title>
            <link>https://medium.com/analytics-vidhya/eyeattend-facial-recognition-based-attendance-system-from-scratch-16e3ece22089?source=rss-2f80954db0c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/16e3ece22089</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Keshav Tangri]]></dc:creator>
            <pubDate>Sat, 13 Feb 2021 19:26:49 GMT</pubDate>
            <atom:updated>2021-02-15T16:29:40.297Z</atom:updated>
            <content:encoded><![CDATA[<h3>EyeAttend — Facial Recognition based Attendance System from scratch. — A complete approach. (Part-I)</h3><p>— From Data Collection to Model Compilation to Backend Data Storage to Frontend Android App</p><p>The project would have been incomplete without the hardwork of my team members <a href="https://medium.com/u/84520e62b7d7">Abhijeet_Baruah</a> and <a href="https://medium.com/u/2152ba9fd292">Aarushi Sood</a>. We are thankful to our professor, Dr. Varun Gupta (HOD, Applied Sciences)for his esteemed guidance and motivation to keep us going and growing with this project.</p><h3>Before we begin…</h3><p>We would like to clarify that this won’t be one single story but a collection of stories as the project took a long time in development and with these stories, our main aim is to clarify each part of the development so that you are able to build similar, in fact more advanced version of this project for yourself.</p><p>Since the series feature is deprecated from Medium, the complete story will be divided into parts and the number will be mentioned in the title to keep a track of the post.</p><h3>Motivation</h3><p>The project is our final year’s mini project and we have chosen the domain to be Artificial Intelligence. Digging deep inside artificial intelligence lies the domain of Machine Learning and we have chosen our base to be Deep Learning (subset of ML).</p><p>We remember that during our first year of college, we felt a need of something inspiring, something that would amaze us and hence this thought became the motivation for our project. Following this motivation, we decided to give back what we thought at that time, almost after four years of B.E. in CSE via this project.</p><p>Our vision for this project is to introduce an intelligent system for motivating freshman year students in machine learning. The aim is to deploy this system in our college so that, once the freshman students observe its application in their own lives, this would definitely ignite the fire in some students to build a better version, better projects that can be used for socio-eco platforms.</p><p>The target is easy as every class has it’s own class representative and one of the main duty is taking the attendance of students. In this way we can have the direct interaction with the target audience i.e the fresh minds of college.</p><h3>Takeaway from this series</h3><ol><li>A scalable design with the focus on making the attendance system not only automatic but also intelligent.</li><li>The architecture of the system mainly focuses on its usability and scalability which will easily help us to redesign it in accordance to the future feedbacks.</li><li>With a modular approach, ML models can be plugg in/plug out.</li><li>Use machine learning and vectorization for faster results.</li><li>Android Application- “EyeAttend” for interacting with the system.</li></ol><h3>What will you learn to build</h3><p>The video given below, will demonstrate the core working of the project. The foremost step is to select an image including all the people present in the room, sending it over to the server which will run the model on the image and return the list of presentees and absentees students. The project loads the attendance table for a particular teacher of a particular subject of a specific class in the database dynamically i.e creating tables, adding roll numbers, adding the date of attendance and also marks the attendance. The attendance can be downloaded for the whole class by the teacher and a student can download his own attendance for whole semester for a specific subject of a particular teacher, just in one click. The following demo shows the core working of the project.</p><p><a href="https://drive.google.com/file/d/1BO7evOKZDRKVQ1dijzrxLdv12u3DMaIA/view?usp=sharing">EyeAttendDemo.mp4</a></p><h3>Conclusion</h3><p>It’s time to conclude the introductory story for this project. It will be our effort to provide the next part of the story once a week. We hope you will enjoy the above demo and information about our project and you are really excited to learn how to build the automated attendance system on your own. Let’s catch up in the next blog. Till then, have a great week! For getting updates about next part, follow us on medium, LinkedIn : <a href="https://www.linkedin.com/in/keshav-t-7ab782104/">Keshav Tangri</a>, <a href="https://www.linkedin.com/in/abhijeet-baruah-bb1b08165/">Abhijeet Baruah</a>, &amp; <a href="https://www.linkedin.com/in/aarushi-sood-b2b11b154/">Aarushi Sood</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R7p8TFuXnRHVZCLj_aaAJw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@sparkerz?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Barry Zhou</a> on <a href="https://unsplash.com/s/photos/classroom?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>References</h3><p><strong>[1] Logo Design </strong>: <a href="https://www.designfreelogoonline.com/logoshop/free-logo-maker-cctv-camera-logo-design-copy/">https://www.designfreelogoonline.com/logoshop/free-logo-maker-cctv-camera-logo-design-copy/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16e3ece22089" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/eyeattend-facial-recognition-based-attendance-system-from-scratch-16e3ece22089">EyeAttend — Facial Recognition based Attendance System from scratch.</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Class Image Classification using Alexnet Deep Learning Network implemented in Keras API]]></title>
            <link>https://medium.com/analytics-vidhya/multi-class-image-classification-using-alexnet-deep-learning-network-implemented-in-keras-api-c9ae7bc4c05f?source=rss-2f80954db0c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9ae7bc4c05f</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[alexnet]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Keshav Tangri]]></dc:creator>
            <pubDate>Fri, 31 Jul 2020 17:00:26 GMT</pubDate>
            <atom:updated>2023-07-16T03:32:46.293Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>Computer is an amazing machine (no doubt in that) and I am really mesmerized by the fact how computers are able to learn and classify Images. Image classification have it’s own advantages and application in various ways, for example, we can buid a pet food dispenser based on which species (cat or dog) is approaching it. I know it’s a wierd idea like they will end up eating all of the food but the system can be time controlled and can be dispensed only once. Anyways let’s move further before getting distracted and continue our discussion. So after upskilling myself with the knowledge of Deep Learning Neural Networks, I thought of building one myself. So here I am going to share building an Alexnet Convolutional Neural Network for 6 different classes built from scratch using Keras and coded in Python.</p><h3><strong>Overview of AlexNet</strong></h3><p>Before getting to AlexNet , it is recommended to go through the Wikipedia article on <a href="https://en.wikipedia.org/wiki/Convolutional_neural_network#Architecture">Convolutional Neural Network Architecture</a> to understand the terminologies in this article. Let’s dive in to get a basic overview of the AlexNet network</p><p><a href="http://Krizhevsky, Alex &amp; Sutskever, Ilya &amp; Hinton, Geoffrey. (2012). ImageNet Classification with Deep Convolutional Neural Networks. Neural Information Processing Systems. 25. 10.1145/3065386.">AlexNet</a>[1]<strong> </strong>is a Classic type of Convolutional Neural Network, and it came into existence after the 2012 ImageNet challenge. The network architecture is given below :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3B8iO-se13vA2QfZ4OBRSw.png" /><figcaption>AlexNet Architecture (courtesy of Andrew Ng on <a href="https://coursera.org/share/1fe2c4b8b8d1e3039ca6ae359b8edb30">Coursera</a>[2])</figcaption></figure><p><strong>Model Explanation : </strong>The Input to this model have the dimensions 227x227x3 follwed by a Convolutional Layer with 96 filters of 11x11 dimensions and having a ‘same’ padding and a stride of 4. The resulting output dimensions are given as :</p><p><em>floor(((n + 2*padding - filter)/stride) + 1 ) * floor(((n + 2*padding — filter)/stride) + 1)</em></p><p><strong>Note : </strong>This formula is for square input with height = width = n</p><p>Explaining the first Layer with input 227x227x3 and Convolutional layer with 96 filters of 11x11 , ‘valid’ padding and stride = 4 , output dims will be</p><p>= floor(((227 + 0–11)/4) + 1) * floor(((227 + 0–11)/4) + 1)</p><p>= floor((216/4) + 1) * floor((216/4) + 1)</p><p>= floor(54 + 1) * floor(54 + 1)</p><p>= 55 * 55</p><p>Since number of filters = 96 , thus output of first Layer is : <strong>55x55x96</strong></p><p>Continuing we have the MaxPooling layer (3, 3) with the stride of 2,making the output size decrease to 27x27x96, followed by another Convolutional Layer with 256, (5,5) filters and ‘same’ padding, that is, the output height and width are retained as the previous layer thus output from this layer is 27x27x256. Next we have the MaxPooling again ,reducing the size to 13x13x256. Another Convolutional Operation with 384, (3,3) filters having same padding is applied twice giving the output as 13x13x384, followed by another Convulutional Layer with 256 , (3,3) filters and same padding resulting in 13x13x256 output. This is MaxPooled and dimensions are reduced to 6x6x256. Further the layer is Flatten out and 2 Fully Connected Layers with 4096 units each are made which is further connected to 1000 units softmax layer. The network is used for classifying much large number of classes as per our requirement. However in our case, we will make the output softmax layer with 6 units as we ahve to classify into 6 classes. The softmax layer gives us the probablities for each class to which an Input Image might belong.</p><h3><strong>Implementing AlexNet using Keras</strong></h3><p>Keras is an API for python, built over Tensorflow 2.0,which is scalable and adapt to deployment capabilities of Tensorflow [3]. We will Build the Layers from scratch in Python using Keras API.</p><p>First, lets Import the essentials libraries</p><pre>import numpy as np<br>from keras import layers<br>from keras.layers import Input, Dense, Activation,BatchNormalization, Flatten, Conv2D, MaxPooling2D<br>from keras.models import Model<br>from keras.preprocessing import image<br>from keras.preprocessing.image import ImageDataGenerator<br>import keras.backend as K<br>K.set_image_data_format(‘channels_last’)<br>import matplotlib.pyplot as plt<br>from matplotlib.pyplot import imshow</pre><p>In this article we will use the Image Generator to build the Classifier. Next we will import the data using Image Data Generator. Before that let’s understand the Data. The dataset can be found <a href="https://www.kaggle.com/puneet6060/intel-image-classification/data#">here</a>.</p><p>This Data contains around 25k images of size 150x150 distributed under 6 categories, namely : ‘buildings’ , ‘forest’ , ‘glacier’ , ‘mountain’ , ‘sea’ , ‘street’ . There are 14K images in training set, 3K in test setand 7K in Prediction set.</p><p>The data images for all the categories are split into it’s respective directories, thus making it easy to infer the labels as according to keras documentation[4]</p><blockquote><strong>Arguments :</strong></blockquote><blockquote><strong>directory</strong>: Directory where the data is located. If labels is &quot;inferred&quot;, it should contain subdirectories, each containing images for a class. Otherwise, the directory structure is ignored.</blockquote><p>In the linked dataset also, we have a directory structure and thus the ImageDataGenerator will infer the labels. A view of dataset directory structure is shown below :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*Rk3hNskMfXQrk0I16NhF7Q.png" /><figcaption>Directory structure in dataset</figcaption></figure><p>Next we will import the dataset as shown below :</p><pre>path = &#39;C:\\Users\\Username\\Desktop\\folder\\seg_train\\seg_train&#39;<br>train_datagen = ImageDataGenerator(rescale=1. / 255)<br>train = train_datagen.flow_from_directory(path, target_size=(227,227), class_mode=&#39;categorical&#39;)</pre><p><strong>Output</strong></p><pre>Found 14034 images belonging to 6 classes.</pre><p>As explained above, the input size for AlexNet is 227x227x3 and so we will change the target size to (227,227). The by default Batch Size is 32. Lets see the type of train and train_datagen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*9UVRKGn5bzzJPKX1cqViVw.png" /></figure><p>The type keras.preprocessing.image.DirectoryIterator is an Iterator capable of reading images from a directory on disk[5]. The keras.preprocessing.image.ImageDataGenerator generate batches of tensor image data with real-time data augmentation. The by default batch_size is 32</p><p>Next let us check the dimensions of the first image and its associated output in the first batch.</p><pre>print(&quot;Batch Size for Input Image : &quot;,train[0][0].shape)<br>print(&quot;Batch Size for Output Image : &quot;,train[0][1].shape)<br>print(&quot;Image Size of first image : &quot;,train[0][0][0].shape)<br>print(&quot;Output of first image : &quot;,train[0][1][0].shape)</pre><p><strong>Output :</strong></p><pre>Batch Size for Input Image :  (32, 227, 227, 3)<br>Batch Size for Output Image :  (32, 6)<br>Image Size of first image :  (227, 227, 3)<br>Output of first image :  (6,)</pre><p>Let’s check out some Examples from the Dataset :</p><pre>fig , axs = plt.subplots(2,3 ,figsize = (10,10))</pre><pre>axs[0][0].imshow(train[0][0][12])<br>axs[0][0].set_title(train[0][1][12])</pre><pre>axs[0][1].imshow(train[0][0][10])<br>axs[0][1].set_title(train[0][1][10])</pre><pre>axs[0][2].imshow(train[0][0][5])<br>axs[0][2].set_title(train[0][1][5])</pre><pre>axs[1][0].imshow(train[0][0][20])<br>axs[1][0].set_title(train[0][1][20])</pre><pre>axs[1][1].imshow(train[0][0][25])<br>axs[1][1].set_title(train[0][1][25])</pre><pre>axs[1][2].imshow(train[0][0][3])<br>axs[1][2].set_title(train[0][1][3])</pre><blockquote>These are harcoded examples to show one pic for each category in 1st batch, The results can differ based on the shuffling done by your machine.</blockquote><p><strong>Output :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*Qic1k1fsEDA8-sVH0nzZqg.png" /><figcaption>Images from different categories, with the title as the output(category) of each image in the dataset</figcaption></figure><p>Next let’s start the construction of Model. The following code block will construct your AlexNet Deep Learning Network :</p><pre>def AlexNet(input_shape):<br>    <br>    X_input = Input(input_shape)<br>    <br>    X = Conv2D(96,(11,11),strides = 4,name=&quot;conv0&quot;)(X_input)<br>    X = BatchNormalization(axis = 3 , name = &quot;bn0&quot;)(X)<br>    X = Activation(&#39;relu&#39;)(X)<br>    <br>    X = MaxPooling2D((3,3),strides = 2,name = &#39;max0&#39;)(X)<br>    <br>    X = Conv2D(256,(5,5),padding = &#39;same&#39; , name = &#39;conv1&#39;)(X)<br>    X = BatchNormalization(axis = 3 ,name=&#39;bn1&#39;)(X)<br>    X = Activation(&#39;relu&#39;)(X)<br>    <br>    X = MaxPooling2D((3,3),strides = 2,name = &#39;max1&#39;)(X)<br>    <br>    X = Conv2D(384, (3,3) , padding = &#39;same&#39; , name=&#39;conv2&#39;)(X)<br>    X = BatchNormalization(axis = 3, name = &#39;bn2&#39;)(X)<br>    X = Activation(&#39;relu&#39;)(X)<br>    <br>    X = Conv2D(384, (3,3) , padding = &#39;same&#39; , name=&#39;conv3&#39;)(X)<br>    X = BatchNormalization(axis = 3, name = &#39;bn3&#39;)(X)<br>    X = Activation(&#39;relu&#39;)(X)<br>    <br>    X = Conv2D(256, (3,3) , padding = &#39;same&#39; , name=&#39;conv4&#39;)(X)<br>    X = BatchNormalization(axis = 3, name = &#39;bn4&#39;)(X)<br>    X = Activation(&#39;relu&#39;)(X)<br>    <br>    X = MaxPooling2D((3,3),strides = 2,name = &#39;max2&#39;)(X)<br>    <br>    X = Flatten()(X)<br>    <br>    X = Dense(4096, activation = &#39;relu&#39;, name = &quot;fc0&quot;)(X)<br>    <br>    X = Dense(4096, activation = &#39;relu&#39;, name = &#39;fc1&#39;)(X) <br>    <br>    X = Dense(6,activation=&#39;softmax&#39;,name = &#39;fc2&#39;)(X)<br>    <br>    model = Model(inputs = X_input, outputs = X, name=&#39;AlexNet&#39;)</pre><pre>return model</pre><p>Next we will call the function that will return the model. We passed in the shape as the shape of our image which we have already rescaled to 227x227</p><pre>alex = AlexNet(train[0][0].shape[1:])</pre><p>The model can be summarised using the command</p><pre>alex.summary()</pre><p><strong>Output :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*mVLgmh4E7gPkyryFEA6KxA.png" /><figcaption>Summary for our model</figcaption></figure><p>Next we will compile the model using adam optimizer and choosing loss as categorical_crossentropy , with accuracy metrics. You can study about losses in keras <a href="https://keras.io/api/losses/">here</a>[6] and quick study for optimizers in Keras can be done <a href="https://keras.io/api/optimizers/">here</a>[7].</p><pre>alex.compile(optimizer = &#39;adam&#39; , loss = &#39;categorical_crossentropy&#39; , metrics=[&#39;accuracy&#39;])</pre><p>Next we will train the model using fit_generator with the command :</p><pre>alex.fit_generator(train,epochs=50)</pre><p><strong>Output :</strong></p><pre>Epoch 50/50<br>439/439 [==============================] - 96s 219ms/step - loss: 0.0550 - accuracy: 0.9833</pre><p>To know more about fit_generator and its difference with fit, you can check out this <a href="https://www.pyimagesearch.com/2018/12/24/how-to-use-keras-fit-and-fit_generator-a-hands-on-tutorial/">website</a>. After running our model , we got a training accuracy of 98.33%. Next we will load test data to get test accuracy :</p><pre>path_test = &#39;C:\\Users\\Username\\Desktop\\folder2\\seg_test\\seg_test&#39;<br>test_datagen = ImageDataGenerator(rescale=1. / 255)<br>test = test_datagen.flow_from_directory(path_test, target_size=(227,227), class_mode=&#39;categorical&#39;)</pre><p><strong>Output</strong></p><pre>Found 3000 images belonging to 6 classes.</pre><p>Next we will evaluate our model on test data</p><pre>preds = alex.evaluate_generator(test)</pre><pre>print (&quot;Loss = &quot; + str(preds[0]))<br>print (&quot;Test Accuracy = &quot; + str(preds[1]))</pre><p><strong>Output :</strong></p><pre>Loss = 0.1878412961959839<br>Test Accuracy = 0.871999979019165</pre><p>We got a test accuracy of 87.2% Next we will run the model over prediction Images</p><pre>path_test = &#39;C:\\Users\\username\\Desktop\\folder3\\seg_pred\\&#39;<br>predict_datagen = ImageDataGenerator(rescale=1. / 255)<br>predict = predict_datagen.flow_from_directory(path_test, target_size=(227,227), batch_size = 1,class_mode=&#39;categorical&#39;)</pre><p><strong>Output:</strong></p><pre>Found 7301 images belonging to 1 classes</pre><p>Run the predict_generator on it</p><pre>predictions = alex.predict_generator(predict)</pre><p>Lets test out some predicted images :</p><pre>imshow(predict[700][0][0])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*m8TBoIlXHWMjkRtufYsi7g.png" /><figcaption>Input Image to our model</figcaption></figure><p>To get its prediction we will do :</p><pre>print(predictions[700])</pre><p><strong>Output :</strong></p><pre>[9.9999893e-01 1.2553875e-08 7.1486659e-07 4.0256100e-07 1.3809868e-08<br> 8.5458379e-10]</pre><p>This is the output of our model, since we used softmax at last layer , the model is returning the probabilities for each category for this particular image input. As seen above, the model is predicting the image as ‘building’ with a probability of 0.99999893</p><p>Now we don’t want to have this to be our output format, so we will make a function that will give us the category to which the Input Image, predicted by the model will belong to.</p><pre>import os <br>def get_category(predicted_output):<br>    path =&quot;C:\\Users\\Username\\Desktop\\folder\\seg_train\\seg_train&quot;<br>    return os.listdir(path)[np.argmax(predicted_output)]</pre><p>We will call the function as :</p><pre>print(get_category(predictions[700]))</pre><p><strong>Output :</strong></p><pre>buildings</pre><p>Thus output of some other images are shown below :</p><pre>fig , axs = plt.subplots(2,3 ,figsize = (10,10))</pre><pre>axs[0][0].imshow(predict[1002][0][0])<br>axs[0][0].set_title(get_category(predictions[1002]))</pre><pre>axs[0][1].imshow(predict[22][0][0])<br>axs[0][1].set_title(get_category(predictions[22]))</pre><pre>axs[0][2].imshow(predict[1300][0][0])<br>axs[0][2].set_title(get_category(predictions[1300]))</pre><pre>axs[1][0].imshow(predict[3300][0][0])<br>axs[1][0].set_title(get_category(predictions[3300]))</pre><pre>axs[1][1].imshow(predict[7002][0][0])<br>axs[1][1].set_title(get_category(predictions[7002]))</pre><pre>axs[1][2].imshow(predict[512][0][0])<br>axs[1][2].set_title(get_category(predictions[512]))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*yp-AE9n3bjo9196nUig8qA.png" /><figcaption>These are some output samples from our model</figcaption></figure><p>The Python Notebook for this model can be cloned/downloaded from my github <a href="https://github.com/keshav1245/Image-Classification-using-AlexNet-CNN-Model">here</a>. I hope you like this article and I hope you will be able to b uild your own model with a different data set and/or with custom layers instead of following a Classic CNN Network.</p><p>I hope this article will be able to give you an insight about AlexNet. Better networks such as VGG16 , VGG19, ResNets etc are also worth a try. I hope you find this article interesting and will definitely try some other classic CNN models on the classification problem. Feel free to share your results down in the comment box. Do clap for the article if you like it as it motivates me to write such more posts. Find me on <a href="https://www.linkedin.com/in/keshav-t-7ab782104">Linked’In</a> and <a href="https://www.instagram.com/apprentice_fotografo/?hl=en">Instagram</a> and share your feedback.</p><p><strong>References</strong></p><p>[1] Krizhevsky, Alex &amp; Sutskever, Ilya &amp; Hinton, Geoffrey. (2012). ImageNet Classification with Deep Convolutional Neural Networks. Neural Information Processing Systems. 25. 10.1145/3065386.</p><p>[2] <a href="https://coursera.org/share/1fe2c4b8b8d1e3039ca6ae359b8edb30">https://coursera.org/share/1fe2c4b8b8d1e3039ca6ae359b8edb30</a></p><p>[3] <a href="https://keras.io/">https://keras.io/</a></p><p>[4] <a href="https://keras.io/api/preprocessing/image/">https://keras.io/api/preprocessing/image/</a></p><p>[5] <a href="https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/DirectoryIterator">https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/DirectoryIterator</a></p><p>[6] <a href="https://keras.io/api/losses/">https://keras.io/api/losses/</a></p><p>[7] <a href="https://keras.io/api/optimizers/">https://keras.io/api/optimizers/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9ae7bc4c05f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/multi-class-image-classification-using-alexnet-deep-learning-network-implemented-in-keras-api-c9ae7bc4c05f">Multi-Class Image Classification using Alexnet Deep Learning Network implemented in Keras API</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Color Quantization for Image Reduction using K-Means Clustering Algorithm]]></title>
            <link>https://medium.com/analytics-vidhya/color-quantization-for-image-reduction-using-k-means-clustering-algorithm-321b33f4d5e8?source=rss-2f80954db0c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/321b33f4d5e8</guid>
            <category><![CDATA[image]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[k-means-clustering]]></category>
            <category><![CDATA[compression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Keshav Tangri]]></dc:creator>
            <pubDate>Sun, 05 Jul 2020 14:32:44 GMT</pubDate>
            <atom:updated>2020-07-08T16:56:55.941Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction :</strong></p><p>There’s a saying that ‘A picture is worth a thousand words’[1]. In today’s era of technology , we are all surrounded by images. From identifying people from images in official records, to uploading pictures on Instagram, Changing profile picture on whatsapp, facebook, using pictures to understand space galaxies, storing memories etc. , images got us covered from all sides.</p><p>The Images actually use a big amount of disk space photos from an event can sum upto a couple of GigaBytes. That’s where Image Compression comes in play. Image compression basically means reducing the disk size of the image without much of the effect on its quality. One such Image compression approach is Color Quantization.</p><p><strong>Color Quantization :</strong></p><p>Color Quantization is a process in which the number of distinct colours in an image is reduced , so as to make the resulting image similar to the original image but with a reduced size [2]. One such approach to reduce the colors of the image is via K-Means Clustering method. The algorithm is explained below</p><p><strong>K-Means Clustering</strong></p><p>This algorithm comes in play for unsupervised data (unlabelled data), which means that given some set of points , we would like to find the structure in the data. The algorithm that helps to form the clusters of similar data points is known as clustering algorithm. K-Means Clustering is a technique in which the data points are segregated into K different clusters. Each cluster is uniquely identified by the centroid of the cluster. This algorithm groups similar colour values into K clusters and each pixel value (in the final output image)is replaced by the value of the centroid of the cluster to which it belongs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*02uFILACupKcvW_FY-AGaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GbRFjlxgsytS4Y3IMfBnMw.png" /><figcaption>K Means cluster the unstructured data(left) into 2 clusters (right) (Image Courtesy : Andre Ng ML Course[3])</figcaption></figure><p>After randomly initializing the K centroids, the iterative algorithm of K-Means have mainly 2 steps:</p><ol><li><strong>Cluster Assignment : </strong>In this we allot the centroid index to the pixel values such that the euclidean distance[2] between the pixel and the centroid is minimum. The distance between 2 points (a1,b1,c1) and (a2,b2,c2) is given by : sqrt((a2-a1)² + (b2-b1)² + (c2-c1)² ) [</li><li><strong>Moving Centroids : </strong>In this, we calculate the new centroids, by taking the average of all the pixel values that is alloted to a given centroid.</li></ol><p><strong>How the size is reduced ?</strong></p><p>A coloured image has 3 different channels , i.e Red(R) , Green(G), Blue(B) or RGB and each pixel uses 24 bits (8 bits (unsigned integers fro 0 to 255) each for R,G &amp; B ) to represent a color. In this color quantization technique , say we reduce the number of colours to 32 and thus the size of image can be reduced as we can store only these 32 selected RGB values and thus for each pixel we can store the index of these colour which will take only 5 (2⁵ = 32)bits instead 24 bits. After this, we will replace the pixel values with the 32 selected colors [3].</p><p>In depth explanation of size reduction is beautifully presented by Satyam Kumar in his story[4].</p><p><strong>Results and Conclusion</strong></p><p>Now we will see the outcome of running the K-Means Algorithm. See the below Images when compressed using K-Means with number of colours ranging as 2,4,8,16,32 and 64. The Implementation for Color Quantization using K-Means is given <a href="https://github.com/keshav1245/Image-Compression-by-Color-Quantization/blob/master/COLOR%20QUANTIZATION.md">here</a>. I will discuss the implementation in the next story where how to implement it from scratch in python will be discussed and in depth explanation will be discussed. If you like the story , do check out my <a href="https://www.linkedin.com/in/keshav-t-7ab782104">LinkedIn</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*fK9saN-Cax3u6GYOMbe6jA.jpeg" /><figcaption>Original Image (Image Courtesy : <a href="https://www.instagram.com/apprentice_fotografo/">apprentice_fotografo</a>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*0xJ2Y0guIkr1ZrOaG0mX7Q.jpeg" /><figcaption>Number of Clusters (K) = 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ZyxE-EbxGcA3EeMkLQbXww.jpeg" /><figcaption>Number of Clusters (K) = 4</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*uleCgdD-wY-7HJio-Sb3ew.jpeg" /><figcaption>Number of Clusters (K) = 8</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*4gASRMJ5sI2mcAH-CBn0HQ.jpeg" /><figcaption>Number of Clusters (K) = 16</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*6xRQc-l_xKNqCe2Qqv2XXQ.jpeg" /><figcaption>Number of Clusters (K) = 32</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*AbaK82S4kNkT7xLft1kIRA.jpeg" /><figcaption>Number of Clusters (K) = 64</figcaption></figure><p><strong>References</strong></p><p>[1] <a href="https://en.wikipedia.org/wiki/A_picture_is_worth_a_thousand_words">https://en.wikipedia.org/wiki/A_picture_is_worth_a_thousand_words</a></p><p>[2] <a href="https://en.wikipedia.org/wiki/Color_quantization">https://en.wikipedia.org/wiki/Color_quantization</a></p><p>[3] <a href="https://coursera.org/share/f5010265b57b1dd841eb6dde1c554e4b">https://coursera.org/share/f5010265b57b1dd841eb6dde1c554e4b</a></p><p>[4]<a href="https://towardsdatascience.com/image-compression-using-k-means-clustering-aa0c91bb0eeb">https://towardsdatascience.com/image-compression-using-k-means-clustering-aa0c91bb0eeb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=321b33f4d5e8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/color-quantization-for-image-reduction-using-k-means-clustering-algorithm-321b33f4d5e8">Color Quantization for Image Reduction using K-Means Clustering Algorithm</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>