<?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 Jon Siu on Medium]]></title>
        <description><![CDATA[Stories by Jon Siu on Medium]]></description>
        <link>https://medium.com/@siucy814?source=rss-237a893e21ef------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*sUB9KC0Ai_67OJt4jgTkVA.jpeg</url>
            <title>Stories by Jon Siu on Medium</title>
            <link>https://medium.com/@siucy814?source=rss-237a893e21ef------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 09:32:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@siucy814/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[Training a facial recognition model by OpenCV]]></title>
            <link>https://medium.com/@siucy814/training-a-facial-recognition-model-by-opencv-e4717d86b7ec?source=rss-237a893e21ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4717d86b7ec</guid>
            <category><![CDATA[facial-recognition]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[opencv]]></category>
            <dc:creator><![CDATA[Jon Siu]]></dc:creator>
            <pubDate>Sun, 19 Jan 2020 04:54:01 GMT</pubDate>
            <atom:updated>2020-01-19T05:27:58.455Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let the <strong>OpenCV </strong>to tell you look like Beckham, Trump or Kim</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*hrCgxxl4S4j68fRqf_IOWQ.jpeg" /></figure><h3><strong>Introduction to OpenCV</strong></h3><p><strong>OpenCV </strong>(Open Source Computer Vision Library) is an open source computer vision and machine learning software library. It is commonly used in the industry for facial recognition. In the following example, I am going to demonstrate how to build a model to identify David Beckham, Donald Trump and Kim Jong-Un by using <strong>OpenCV </strong>in Python. First, I have to google the pictures and rename the file name accordingly. In the example, for simplicity, I would assign 0 for Beckham, 1 for Trump and 2 for Kim. The pictures for Beckham would be named as 0.0, 0.1, 0.2 and so on.</p><p>After prepared all the 15 pictures, I have to call the cascade “<em>haarcascade_frontalface_default</em>” to detect the frontal face of the images.</p><pre><strong>import</strong> <strong>cv2</strong><br><strong>import</strong> <strong>os</strong> <br><strong>from</strong> <strong>PIL</strong> <strong>import</strong> Image, ImageDraw<br><strong>import</strong> <strong>numpy</strong> <strong>as</strong> <strong>np</strong><br><strong>from</strong> <strong>matplotlib</strong> <strong>import</strong> pyplot <strong>as</strong> plt<br><strong>from</strong> <strong>matplotlib.image</strong> <strong>import</strong> imread<br>imagePath = &#39;C:<strong>\\</strong>Users<strong>\\</strong>Jonathan<strong>\\</strong>data analytics<strong>\\</strong>computer vision<strong>\\</strong>beckhamtrumpkim<strong>\\</strong>&#39;<br><br>cascPath = &#39;C:<strong>\\</strong>Users<strong>\\</strong>Jonathan<strong>\\</strong>AppData<strong>\\</strong>Local<strong>\\</strong>Programs<strong>\\</strong>Python<strong>\\</strong>Python37<strong>\\</strong>Lib<strong>\\</strong>site-packages<strong>\\</strong>cv2<strong>\\</strong>data<strong>\\</strong>haarcascade_frontalface_default.xml&#39;<br>detector = cv2.CascadeClassifier(cascPath)<br><br>recognizer = cv2.face.LBPHFaceRecognizer_create()<br><br>cv2.__version__</pre><pre>imagePath = &#39;C:<strong>\\</strong>Users<strong>\\</strong>Jonathan<strong>\\</strong>data analytics<strong>\\</strong>computer vision<strong>\\</strong>beckhamtrumpkim<strong>\\</strong>&#39;<br><br>imagefulllist = [&#39;0.0&#39;, &#39;0.1&#39;, &#39;0.2&#39;, &#39;0.3&#39;, &#39;0.4&#39;, &#39;0.5&#39;, &#39;1.0&#39;, &#39;1.1&#39;, &#39;1.2&#39;, &#39;1.3&#39;, &#39;1.4&#39;, &#39;1.5&#39;<br>                , &#39;2.0&#39;, &#39;2.1&#39;, &#39;2.2&#39;]<br><br>plt.figure(figsize=(20, 20))<br><strong>for</strong> count, item <strong>in</strong> enumerate(imagefulllist): <br>    id = item.split(&quot;.&quot;)[0]<br>    <em>#print(id)</em><br>    plt.subplot(6,6,count+1)<br>    filename = imagePath + item + &#39;.jpg&#39;<br>    image = imread(filename)</pre><pre>    <em>#print(filename)</em><br>    plt.imshow(image)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GrkIBO2xqLM1zXngAb7I9A.png" /></figure><p>Then I have to use the “<em>detectMultiScale</em>” method to detect the frontal face of the image and draw a rectangle on the faces detected. The facial detection algorithms begin by searching for human eyes, eyebrows, the mouth, nose, nostrils and the iris. Once the algorithm surmises that it has detected a facial region, additional tests are applied to validate whether it has detected a face. The facial detection is not a new technology, in fact it has been implemented widely in digital camera since 90s.</p><p>Note the <strong>OpenCV </strong>by default reads images in BGR format. In fact, you can also view all color space available in <strong>OpenCV </strong>and use the <em>cvtColor(image, flag)</em> to fix this.</p><pre>imgloc = imagePath+&#39;1.2.JPG&#39;<br>img1 = cv2.imread(imgloc)<br>faces = detector.detectMultiScale(img1) <em>#OpenCV by default reads images in BGR format</em><br><strong>for</strong> (x, y, w, h) <strong>in</strong> faces: <br>    <em># Draw rectangle around the face</em><br>    cv2.rectangle(img1, (x, y), (x+w, y+h), (255, 255, 255), 3)<br><br>plt.imshow(img1, cmap=&#39;gray&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*1mbfNsqI9kfUEBamEmtxbg.png" /></figure><pre>flags = [i <strong>for</strong> i <strong>in</strong> dir(cv2) <strong>if</strong> i.startswith(&#39;COLOR_BGR2&#39;)] <em>#Check color space<br></em>print(flags)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vkOjXOJy0GJoXSBPEFJc2w.png" /><figcaption>Color Space in OpenCV</figcaption></figure><h3>Multiple faces detected</h3><p>In some pictures the facial detection may not be able to detect all the faces correctly. The photo of Kim Jong-Un below has been detected 2 faces by mistake. There are multiple reasons for the mistake and we will discuss on the remediation in the future.</p><pre><strong>def</strong> facedetection(test_img):<br>    faces = detector.detectMultiScale(test_img,scaleFactor=1.1, minNeighbors = 5)<br>    <strong>return</strong>(faces,test_img)</pre><pre>imgloc = &quot;C:<strong>\\</strong>Users<strong>\\</strong>Jonathan<strong>\\</strong>data analytics<strong>\\</strong>computer vision<strong>\\</strong>facial_recognition xml<strong>\\</strong>prediction<strong>\\</strong>&quot;+&#39;2.7.JPG&#39;<br>gray = cv2.imread(imgloc)<br>testface, testimage2 = facedetection(gray)<br>print(&#39;number of faces = <strong>{0}</strong> &#39;.format(len(testface)))<br><br><strong>for</strong> (x, y, w, h) <strong>in</strong> testface: <br>    <em># Draw rectangle around the face</em><br>    cv2.rectangle(testimage2, (x, y), (x+w, y+h), (255, 255, 255), 3)<br><br>plt.clf()<br>plt.figure(figsize=(12,8))<br>testimage3 = cv2.cvtColor(testimage2,cv2.COLOR_BGR2RGB)<br>plt.imshow(testimage3)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZqBHHioPlq9IarHnjW4lYg.png" /></figure><p>Running the following codes to detect if there are multiple faces detected in each of the 15 pictures. Result shows :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*ncOY1GMEv3cjPPa634__Jw.png" /></figure><p>It means only 1 face detected for each picture. By transforming the detected faces into the training data by using <strong>Numpy </strong>array function, now we have the all the faces data stored in the list “faces” and the all person id stored in list “ids”.</p><pre>path = &#39;C:<strong>\\</strong>Users<strong>\\</strong>Jonathan<strong>\\</strong>data analytics<strong>\\</strong>computer vision<strong>\\</strong>beckhamtrumpkim&#39;<br><br><strong>def</strong> getImagesAndLabels(path):<br>    imagePaths = [os.path.join(path,f) <strong>for</strong> f <strong>in</strong> os.listdir(path)] <br>    faceSamples=[]<br>    ids = []<br>    <strong>for</strong> imagePath <strong>in</strong> imagePaths:<br>        PIL_img = Image.open(imagePath).convert(&#39;L&#39;) <em>#Luminance  ==&gt; greystyle</em><br>        img_numpy = np.array(PIL_img,&#39;uint8&#39;)<br>        <em>#print(PIL_img)</em><br>        <em>#.show()</em><br>        <em>#print(len(img_numpy)</em><br>        id = int(os.path.split(imagePath)[-1].split(&quot;.&quot;)[0])<br>        faces = detector.detectMultiScale(img_numpy)<br>        <em>#print(id)</em><br>        <em>#print(faces)</em><br>        <strong>if</strong> len(faces) &gt; 1:<br>            print(&quot;The following image detect more than 1 face&quot;, imagePath)<br>        <strong>for</strong> (x,y,w,h) <strong>in</strong> faces:<br>            faceSamples.append(img_numpy[y:y+h,x:x+w])<br>            ids.append(id)<br>            <em>#print(ids)</em><br>            <br>    <strong>return</strong> faceSamples,ids<br>faces,ids = getImagesAndLabels(path)<br><br><br>print(&quot;<strong>{0}</strong> faces, <strong>{0}</strong> id in total are detected&quot;.format(len(faces), len(ids)))</pre><h3><strong>Training data</strong></h3><p>Alright. Everything is ready for training the data. I have saved the model to a permanent destination for future use. In this case the model saving is not necessary as the training sample is very small; However, it is worth doing if you have many training data.</p><pre>face_recognizer=cv2.face.LBPHFaceRecognizer_create() face_recognizer.train(faces, np.array(ids))</pre><pre><strong>def</strong> train_classifier(faces, faceID):<br>    face_recognizer=cv2.face.LBPHFaceRecognizer_create()<br>    face_recognizer.train(faces, np.array(faceID))<br>    <strong>return</strong> face_recognizer</pre><pre><em># Save the model as bdktrainer.yml<br></em>facerecognizer = train_classifier(faces, ids) facerecognizer.save(&#39;C:<strong>\\</strong>Users<strong>\\</strong>Jonathan<strong>\\</strong>data analytics<strong>\\</strong>computer vision<strong>\\</strong>facial_recognition xml<strong>\\</strong>prediction<strong>\\</strong>bdktrainer.yml&#39;)</pre><h3><strong>Prediction</strong></h3><p>We will then feed in new data for prediction purpose. Before doing it, I have created a name dictionary to convert the id to the person name for better illustration and a new function “<em>puttext</em>” to create a text box on the detected face. It is up to you to change the font size, color and style for the text. Check out more at the <strong>OpenCV </strong>documentation.</p><p>Not bad. The <strong>OpenCV </strong>is able to recognize the person in the picture is David Beckham.</p><pre>name = {0:&quot;Beckham&quot;, 1:&quot;Trump&quot;, 2:&quot;Kim&quot;}<br>imgloc = &#39;C:<strong>\\</strong>Users<strong>\\</strong>Jonathan<strong>\\</strong>data analytics<strong>\\</strong>computer vision<strong>\\</strong>facial_recognition xml<strong>\\</strong>prediction<strong>\\</strong>beckham5.jpg&#39;<br>gray = cv2.imread(imgloc)<br>gray2 = cv2.cvtColor(gray,cv2.COLOR_BGR2RGB)<br><em>#plt.imshow(gray2)</em><br><em>#plt.show()</em><br><br>grayimage2 = cv2.cvtColor(gray,cv2.COLOR_BGR2GRAY)<br>faces = detector.detectMultiScale(grayimage2,scaleFactor=1.2, minNeighbors = 2)<br><br>print(&#39;number of faces = <strong>{0}</strong> &#39;.format(len(faces)))<br><em>#plt.imshow(gray)</em><br><em>#plt.show()</em><br><br><br><strong>def</strong> put_text(test_img,text,x,y): <br>    cv2.putText(test_img,text,(x,y),cv2.FONT_ITALIC,1.1,(255,255,255),2) <em>#text, font size, font color( purple yellow), thickness</em><br><br>print(faces)<br><br><strong>for</strong> face <strong>in</strong> faces:<br>    (x,y,w,h) = face<br>    print(x,y,w,h)<br>    roi_gray = grayimage2[y:y+h, x:x+h]<br>    plt.imshow(roi_gray, cmap=&#39;gray&#39;)<br>    plt.show()<br>    label, confidence = facerecognizer.predict(roi_gray)<br>    <br>    print(&quot;confidence:&quot;, confidence)<br>    print(&quot;label:&quot;, label)<br>    <br>    cv2.rectangle(gray, (x, y), (x+w, y+h), (255, 255, 255), 2)<br>    predicted_name = name[label]<br>    print(predicted_name)<br>    put_text(gray, predicted_name,x,y-5) <em>#put text 5 pixel higher than face</em><br>    <br>    gray = cv2.cvtColor(gray,cv2.COLOR_BGR2RGB)<br>    <br>plt.imshow(gray)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*Pj3ZImiQ_HEP2FCr0AU_LQ.png" /></figure><p>Last, I try to feed the image of myself to let the <strong>OpenCV </strong>tell me who i looked like most out of the 3 men. Ooh surprisingly, you may see the result below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*EK16Sy-VIre0kzsGhNIYfw.png" /></figure><h3>Conclusion</h3><p><strong>LBPH </strong>is one of most straightforward and handy facial recognition algorithm in Python and it produces a great result in a monotonic grey scale image. However, as you may see in the earlier image, you may need to adjust the <em>scaleFactor </em>and the <em>minNeighbors </em>to minimize the error in the image</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4717d86b7ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>