<?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 Arthur Fortes on Medium]]></title>
        <description><![CDATA[Stories by Arthur Fortes on Medium]]></description>
        <link>https://medium.com/@fortes-arthur?source=rss-4742b1c76a29------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*oIFbEUp1BYRIJ6J6Mbh1Lg.jpeg</url>
            <title>Stories by Arthur Fortes on Medium</title>
            <link>https://medium.com/@fortes-arthur?source=rss-4742b1c76a29------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 16:38:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fortes-arthur/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[What is technology adoption lifecycle and how does it work?]]></title>
            <link>https://experiencestack.co/what-is-technology-adoption-lifecycle-and-how-does-it-work-4234a0e9a2b?source=rss-4742b1c76a29------2</link>
            <guid isPermaLink="false">https://medium.com/p/4234a0e9a2b</guid>
            <category><![CDATA[innovation]]></category>
            <category><![CDATA[technology-adoption]]></category>
            <category><![CDATA[business]]></category>
            <category><![CDATA[innovation-management]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Arthur Fortes]]></dc:creator>
            <pubDate>Mon, 31 Jan 2022 11:51:00 GMT</pubDate>
            <atom:updated>2022-02-02T05:49:34.969Z</atom:updated>
            <content:encoded><![CDATA[<p>How to understand and leveraging the technology adoption lifecycle</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NdxIFtI2AeW3WkTaFePRjA.jpeg" /><figcaption>Understanding technology adoption life cycle. (Photo by <a href="https://www.pexels.com/pt-br/@startup-stock-photos">Startup Stock Photos</a>)</figcaption></figure><p>Many people struggle with change and to adopt innovation. For instance, televisions have been in the world for decades and by now most people in the world are familiar with the concept of watching TV. Most households in the world now own a TV, so one can say that TVs are widely adopted. However, that is not true to other product categories. For example, do you own a <a href="https://www.lifewire.com/an-introduction-to-smart-watches-3441381">smartwatch</a>? You may own one, but there is a reasonable chance that you don’t. Money may play a role here. You may find smartwatches too expensive, but still quite a few of you could probably afford a smartwatch. Then, why don’t you own one? Another example is a <a href="https://3dprinting.com/what-is-3d-printing/">3D printer</a> that can be used to print physical objects. There are experts that claim that every household will one day own a 3D printer. You may even know someone who does own a 3D printer. However, there’s a small chance that you have one in your house. Now, why is that? Do you think that they are too expensive for what they currently offer? Or do you perhaps think that they are difficult to use? How can it be that some people adopt a certain innovation, while others do not?</p><p>In this article, I will discuss and present concepts about the technology adoption lifecycle. Understanding how users adopt new products is vital to build the right product roadmap.</p><h3>Context and Concepts</h3><p>Now, to get a better understanding, I will present the technology adoption lifecycle. This concept was based on innovation adoption lifecycle, introduced by the prominent American scholar, <a href="https://www.toolshero.com/toolsheroes/everett-rogers/#:~:text=Everett%20Rogers%20(1931%2D2004),&#39;early%20adopter&#39;%20or%20pioneer.">Everett Rogers</a>, in his great book called <em>Diffusion of Innovations [1]</em>. The adoption lifecycle represents the number of people that adopt a certain innovation over time, starting at the moment when an innovation becomes available. The first televisions, for example, became available in the 1930s [2]. At the time television was introduced, only a few people acquired one. However, the number of people that adopted a TV at a certain moment increased until 50% of potential adopters had acquired a TV. After that, the number of people that acquired a TV for the first time at a certain moment decreased. Once most people own a TV, the adoption rate becomes really low again.</p><p>Everett Rogers divided the graph into five sections representing different adopting categories. The five groups and their percentage distribution, based on his research, are:</p><ul><li><strong><em>Group 1: The Innovators</em></strong><em> </em>(2.5%) are people that do not have any issues with the complexity of new technologies or innovations. Think about 3D printers, for example. When they were first introduced, they were difficult to use. This also applies to personal computers that were introduced in the 70s. However, innovators do not care about this complexity. They can easily deal with it so they adopt the innovation, and then focus on the technology.</li><li><strong><em>Group 2: The Early Adopters</em></strong><em> </em>(13.5%) are not focused on the technology itself, but they are more enthusiastic about potential applications of an innovation. So, if early adopters see an early primitive 3D printer, their imagination starts running wild, and they can see all kinds of applications. This is what excites them, and that is why they are relatively fast when adopting innovations.</li><li><strong><em>Group 3: The Early Majority</em></strong> (34%) are people with more practical orientation. They want to see practical proof of how the innovation can be useful to them.</li><li><strong><em>Group 4: The Late Majority</em></strong> (34%) want to see even more proof. When purchasing a product, this group wants to be sure that it has the strongest support system.</li><li><strong><em>Group 5: </em>T<em>he Laggards</em></strong> (16%) are people who generally assess innovation by themselves. They check whether a certain innovation is interesting to them, or not. However, they are generally skeptical and they accept only a few innovations, and quite often they do not adopt them at all.</li></ul><h4><strong>For better understanding</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*n6qL3ekSGTiU-22T4TR_ow.jpeg" /><figcaption>New product adoption. (Photo by <a href="https://marketoonist.com/">Marketoonist</a>)</figcaption></figure><p>The image above contains three important elements of the techonolofy adoption lifecycle. First, it shows the five adoptive categories. The stages that an innovation goes through during the adoption lifecycle are the second element . The innovation is represented by the square figures above the curve. Finally, the last one shows the chasm between the Early Adopters and Early Majority. You can see that the innovator points at the innovation and says “wow”. Innovators focus on the product and they like it even when it is still in its infancy and not even functioning properly. The Early Adopters find the innovation brilliant and see the opportunities that it offers.</p><h4>What is innovation chasm?</h4><p>The idea of the chasm was introduced by the authors <a href="http://www.geoffreyamoore.com/">Moore</a> and <a href="http://www.markethink.guru/en/markethinkers/738-regis-mckenna#:~:text=Regis%20McKenna%20is%20a%20marketer,(Apple%20Computer)%2C%20the%20first">McKenna</a>, who wrote the book <em>Crossing the Chasm [3]</em>. The chasm indicates that there is a big difference between two adopters categories. Early Adopters are visionaries, they see the potential of innovation even when it has not fully matured and still has some kinks. The Early Majority, however, needs clarification on how an innovation can be useful to them. Once the innovation itself becomes more reliable, has fewer faults and breaks down less often, only then the Early Majority will consider accepting this innovation. As you can see in the image, the Early Majority says: “I heard Ashton Kutcher has one”. <a href="https://www.imdb.com/name/nm0005110/">Ashton Kutcher</a> is an American actor and might serve as a role model to some people amongst the Early Majority. For them, people’s opinions are important. On the other hand, the Early Adopters do not care what other people think about it. If they think something is interesting, they adopt it. Moving to the Late Majority, they only accept an innovation if it is quite popular and established in the market. This suggests that they only tend to adopt something when it is widely accepted and can be considered the standard. Finally, the Laggards are not really aware of what is going on. They’re also not very open to innovations in general, even if the innovation is well developed.</p><p>Here are some other characteristics of the groups that are on either side of the chasm. The Early Adopters are intuitive. They support revolution, and they follow their own rules. A typical example of an Early Adopter was <a href="https://www.britannica.com/biography/Steve-Jobs">Steve Jobs</a>, co-founder of <a href="https://www.apple.com/">Apple</a>. They are more analytical and more in favor of evolution in contrast to the Early Majority, who prefer slower progress. They are likely to consult others. Also, the Early Adopters tend to take risks and they are motivated by possible opportunities. They explore what is possible. The Early Majority tends not to take risks, but rather manages risks. They are motivated by solving current problems and instead of exploring what might be possible, they pursue what is probable. They choose for certainty. More generally said, the Early Adopters look with their eyes shut. They are visionaries while the Early Majority looks with their eyes open.</p><h3>Innovation and Business</h3><p>If a company wants to introduce an innovation, initially it needs to get some of the first groups’ market share by building an innovation that is sufficiently attractive for the Innovators and Early Adopters. Consequently, the company needs to develop an innovation that is both elegant and functional, making it unique and the best in its category. If an innovation matches these criteria, it is likely to be adopted by the Innovators and Early Adopters. Getting these adopter categories on board is essential for getting that first foot in the other market. If the company wants to move to the mainstream market, it has to make this market its focal point. The innovation has to be redesigned and offered in such a way that it can be easily used by the mainstream market. As you may remember, the mainstream market consists of the Early Majority and Late Majority categories. To reach this mainstream market, the company needs to ensure that it has the largest group of customers in its category.</p><p>Also the innovation should be perceived as current standard and the quality of customer support around the product needs to be high. The different interests and criteria of the early markets and the mainstream markets require companies to adapt to innovation, if they want to cross the chasm, and move to the larger and often more financially attractive mainstream market.</p><p>Steve Jobs in Apple was very successful in redesigning product categories that only served in early markets into products that also served the mainstream markets [4]. In 1977, Steve Jobs saw that many computers were not user friendly. So, he realized that the interface of the personal computers should be changed. He introduced the graphical interface and only then the mainstream market adopted these personal computers The Apple Two was the first successful personal computer. Decades later, they were also very successful in bringing the productivity of tablets to the mainstream market. They introduced the iPads.</p><h3>Which One Are You?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hKdg9cPbfAWH5y_0NlPMpQ.jpeg" /><figcaption>(Photo by <a href="https://www.pexels.com/pt-br/@jonathanborba">Jonathan Borba</a>)</figcaption></figure><p>It is important to note that individuals do not always line up as <em>Innovators </em>in all areas of their decision making processes. For instance, a person may adopt cutting-edge green technologies for their home with solar heating and yet not belong to an online social network or own a smartphone. We bounce back and forth across the curve in large part based on the pain points we are trying to solve and our interest in the underpinnings of the change presented.</p><h3><strong>Final Remark</strong></h3><p>In this article, I introduced the concept of the technology adoption lifecycle and how people tend to adopt an innovation. Potential adopters can be divided into five categories: Innovators, Early Adopters, Early Majority, Late Majority, and Laggards. People fall in different categories and have their own preferences concerning what they look for in innovations. Therefore, some innovations can be more easily accepted than others. It was also mentioned that between the Early Adopters and Early Majority, there is the chasm. In this way, the early market of Innovators and Early Adopters is thrilled by the innovation itself or by the opportunities it brings, while the mainstream markets can just be convinced to adopt if the innovation is clearly useful to them. It is also important to notice that some people may not be interested in innovations at all. By these means, we can conclude that if companies want their products to be successfully adopted by their target audience, the technology adoption lifecycle must be taken into account.</p><h3>References</h3><p>[1] Rogers, Everett M. Diffusion of Innovations. New York: Free Press, 1995. Print. <em>(Link to buy </em><a href="https://www.amazon.com.br/Diffusion-Innovations-5th-Everett-Rogers/dp/0743222091">https://www.amazon.com.br/Diffusion-Innovations-5th-Everett-Rogers/dp/0743222091</a><em>)</em></p><p>[2] History of the Television. Link: <a href="https://bebusinessed.com/history/history-of-the-television/#:~:text=The%20world&#39;s%20first%20television%20stations,broadcast%20on%20July%202%2C%201928">https://bebusinessed.com/history/history-of-the-television/#:~:text=The%20world&#39;s%20first%20television%20stations,broadcast%20on%20July%202%2C%201928</a>.</p><p>[3] Moore, G. A. (1991). Crossing the chasm: Marketing and selling technology products to mainstream customers. New York, N.Y.: HarperBusiness. <em>(link to buy </em><a href="https://www.amazon.com.br/Crossing-Chasm-3rd-Disruptive-Mainstream/dp/0062292986">https://www.amazon.com.br/Crossing-Chasm-3rd-Disruptive-Mainstream/dp/0062292986</a><em>)</em></p><p>[4] The Founding of Apple Computers, Inc. Link: <a href="https://guides.loc.gov/this-month-in-business-history/april/apple-computers-founded#:~:text=and%20Photographs%20Division.-,Apple%20Computers%2C%20Inc.,the%20way%20people%20viewed%20computers.&amp;text=1%20Sales%20jumped%20from%20%247.8,the%20year%20Apple%20went%20public">https://guides.loc.gov/this-month-in-business-history/april/apple-computers-founded#:~:text=and%20Photographs%20Division.-,Apple%20Computers%2C%20Inc.,the%20way%20people%20viewed%20computers.&amp;text=1%20Sales%20jumped%20from%20%247.8,the%20year%20Apple%20went%20public</a>.</p><blockquote>The material was prepared based on the Innovation Management course at the Erasmus University of Rotterdam. Link: <a href="https://www.coursera.org/learn/innovation-management">https://www.coursera.org/learn/innovation-management</a></blockquote><p>English text reviwed by <a href="https://medium.com/u/d85fd01905f6">Flavio Cardoso</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4234a0e9a2b" width="1" height="1" alt=""><hr><p><a href="https://experiencestack.co/what-is-technology-adoption-lifecycle-and-how-does-it-work-4234a0e9a2b">What is technology adoption lifecycle and how does it work?</a> was originally published in <a href="https://experiencestack.co/">Experience Stack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning based Human Pose Estimation using OpenCV and MediaPipe]]></title>
            <link>https://fortes-arthur.medium.com/deep-learning-based-human-pose-estimation-using-opencv-and-mediapipe-d0be7a834076?source=rss-4742b1c76a29------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0be7a834076</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[mediapipe]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[pose-estimation]]></category>
            <dc:creator><![CDATA[Arthur Fortes]]></dc:creator>
            <pubDate>Thu, 20 May 2021 15:29:39 GMT</pubDate>
            <atom:updated>2021-06-04T00:52:43.694Z</atom:updated>
            <content:encoded><![CDATA[<p>A guide to MediaPipe library for Human Pose Estimation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g6jzfBrE7cFPGHsLmtSdyw.png" /><figcaption>Result of Pose Estimation without background.</figcaption></figure><p>One of the hardest tasks in computer vision is determining the high degree-of-freedom configuration of a human body with all its limbs, complex self-occlusion, self-similar parts, and large variations due to clothing, body-type, lighting, and many other factors. The problem of human pose estimation can be defined as the computer vision techniques that predict the location of various human keypoints(joints and landmarks) such as elbows, knees, neck, shoulder, hips, chest etc. In today’s article, we will learn about deep learning based human pose estimation using MediaPipe and OpenCV libraries.</p><h3>Table of Contents</h3><ul><li>What is MediaPipe?</li><li>Pose Estimation Problem</li><li>Implementing the Solution</li><li>Useful Links</li></ul><h3>What is MediaPipe?</h3><p>Mediapipe is a framework mainly used for building multimodal audio, video, or any time series data. With the help of the MediaPipe framework, an impressive ML pipeline can be built for instance of inference models like TensorFlow, TFLite, and also for media processing functions.</p><blockquote><strong>Note:</strong> You don’t even need a GPU for running the experiments with MediaPipe, as today’s integrated graphics and CPUs working well for this solution. Logically, the FPS will be much lower than the use of a GPU.</blockquote><p>MediaPipe offers customizable Python solutions as a prebuilt Python package on <a href="https://pypi.org/project/mediapipe/">PyPI</a>, which can be installed simply with pip install mediapipe. It also provides tools for users to build their own solutions. Please see <a href="https://google.github.io/mediapipe/getting_started/python">MediaPipe in Python</a> for more info.</p><p>MediaPipe solutions for ML:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*--g79ylAWbnOPrWFcB2G5w.png" /><figcaption>ML solutions covered by MediaPipe. (Source: <a href="https://google.github.io/mediapipe/solutions/pose.html">https://google.github.io/mediapipe/solutions/pose.html</a>)</figcaption></figure><h3>Pose Estimation Problem</h3><p>Human pose estimation from video plays a critical role in various applications such as <a href="https://google.github.io/mediapipe/solutions/pose_classification.html">quantifying physical exercises</a>, sign language recognition, and full-body gesture control. For example, it can form the basis for yoga, dance, and fitness applications. It can also enable the overlay of digital content and information on top of the physical world in augmented reality. MediaPipe Pose is a ML solution for high-fidelity body pose tracking, inferring 33 3D landmarks on the whole body from RGB video frames utilizing our <a href="https://ai.googleblog.com/2020/08/on-device-real-time-body-pose-tracking.html">BlazePose</a> research that also powers the <a href="https://developers.google.com/ml-kit/vision/pose-detection">ML Kit Pose Detection API</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*JJCbfzhTySIqKr1L5pDkpQ.png" /><figcaption>Landmarks recognized by MediaPipe. (Source: <a href="https://google.github.io/mediapipe/solutions/pose.html">https://google.github.io/mediapipe/solutions/pose.html</a>)</figcaption></figure><h3><strong>Implementing the Solution</strong></h3><h4>Requirements</h4><p>For this project, I used Python with <a href="https://www.anaconda.com/">Anaconda Env</a> and used the followed libs:</p><pre># Using conda<br>conda install -c conda-forge opencv</pre><pre># Using pip<br>pip install mediapipe</pre><h4>Creating the Pose Estimator Class</h4><p>Let us create a python class to estimate the pose and also that the class can be used for any further project related to posing estimation. Also, you can use it in real-time with the help of your webcam.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b21e633062bfa749c2c25f65c8fb328e/href">https://medium.com/media/b21e633062bfa749c2c25f65c8fb328e/href</a></iframe><h4>Making prediction</h4><p>Since we created a class in the above file, we will make use of it in another file to make predictions in videos.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac608b614f85d754c15aca0186170060/href">https://medium.com/media/ac608b614f85d754c15aca0186170060/href</a></iframe><p>Now just run the follow command:</p><pre>python detector.py -i videos/input_video.mp4 -o videos/output_video.mp4 -b False</pre><blockquote><strong>Note:</strong> The complete code and requirements are available on my GitHub, which is available on the useful links.</blockquote><h4>Result</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FPBGm0VlCQF4&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPBGm0VlCQF4&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FPBGm0VlCQF4%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/39c7ff8dcb5e790b859b1c4a8ab5fe06/href">https://medium.com/media/39c7ff8dcb5e790b859b1c4a8ab5fe06/href</a></iframe><h3>Useful links</h3><ul><li><a href="https://github.com/arthurfortes/pose_estimation">arthurfortes/pose_estimation</a></li><li><a href="https://mediapipe.dev/"></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0be7a834076" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Personalized Face Mask Detection Using OpenCV and Deep Learning]]></title>
            <link>https://fortes-arthur.medium.com/building-a-personalized-face-mask-detection-using-opencv-and-deep-learning-4aae008c95a0?source=rss-4742b1c76a29------2</link>
            <guid isPermaLink="false">https://medium.com/p/4aae008c95a0</guid>
            <category><![CDATA[face-mask]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[covid19]]></category>
            <dc:creator><![CDATA[Arthur Fortes]]></dc:creator>
            <pubDate>Wed, 03 Feb 2021 23:36:04 GMT</pubDate>
            <atom:updated>2021-02-04T00:32:03.125Z</atom:updated>
            <content:encoded><![CDATA[<p>A hands-on guide to understand how to build a mask detection with personalized outputs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*VmQLQis63-AdHi-GkgJcug.png" /></figure><p>Face masks have become a vital element of our daily lives during the current global pandemic (COVID-19). So, wearing them is important for safety and to control the spread. These Masks are capable of stopping the spread of this deadly virus, which will help to control the spread. As we have started moving forward in this ‘new normal’ world, the necessity of the face mask has increased. By these means, it is necessary that in addition to using the masks, people use them correctly, always covering the mouth and nose.</p><p>In this article, unlike other works, our main focus is to detect whether a person is wearing correctly a mask or not.</p><p>There are some steps to achieve our goal: First we need to build a dataset, then we need to perform our classifier model based on deep learning and detect human faces using OpenCV and finally we create a real time solution do predict if a person is using correctly a mask or not.</p><h3>Step 1 : Dataset</h3><p>The dataset used in this experiment was composed by images that we found online in published datasets:</p><ul><li><a href="https://github.com/sandeco/CanalSandeco/tree/master/Deep%20Learning%20s%C3%A9rie/%2316%20-%20Detectando%20Faces%20em%20v%C3%ADdeo%20com%20Deep%20Learning">CanalSandeco</a></li><li><a href="https://github.com/cabani/MaskedFace-Net">MaskedFace-Net</a></li><li><a href="https://github.com/X-zhangyang/Real-World-Masked-Face-Dataset">Real-World-Masked-Face-Dataset</a></li></ul><p>The use of several datasets was necessary to collect different scenarios:</p><ul><li>People of different racial and ethnicities</li><li>Masks of different types</li><li>Masks in different positions</li><li>Different Angles</li></ul><h4>Examples</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*MthYaQRvLAFJQqk65NcIsw.jpeg" /><figcaption>Dataset images representing all labels.</figcaption></figure><pre>{0: ‘maskchin’, 1: ‘maskmouth’, 2: ‘maskoff’, 3: ‘maskon’}</pre><h4>Final Dataset Link</h4><p>The complete dataset are available in <a href="https://drive.google.com/file/d/1QP5Xwgg4WK9OGkzYUr63uGXaGy89nDaA/view?usp=sharing">Google Drive</a> (25.6GB).</p><h3>Step 2 : Perform Deep Learning Architecture</h3><p>In this task, I used <a href="https://keras.io/api/applications/mobilenet/">MobileNet</a>, a class of light weight deep convolutional neural networks that are vastly smaller in size and faster in performance than many other popular models, in order to classify if a person are using a mask or not. I worked with MobileNet implemented in TensorFlow’s Keras API.</p><pre>from keras.applications.mobilenet import MobileNet<br>...</pre><pre><strong># Params<br></strong>IMAGE_WIDTH = 300<br>IMAGE_HEIGHT = 300<br>IMAGE_SIZE = (IMAGE_WIDTH, IMAGE_HEIGHT)<br>IMAGE_CHANNELS = 1<br>IMG_DIR = &#39;images/&#39;<br>BATCH_SIZE = 32<br>NUM_CLASSES = 4</pre><pre><br><strong># Model</strong><br>base_model = MobileNet(<br>    weights= None,<br>    include_top=False,<br>    input_shape= (IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_CHANNELS)<br>)</pre><pre>x = base_model.output<br>x = GlobalAveragePooling2D()(x)<br>x = Dense(256,activation=&#39;relu&#39;)(x)<br>x = Dropout(0.2)(x)</pre><pre>predictions = Dense(NUM_CLASSES, activation=&#39;softmax&#39;)(x)<br>model = Model(inputs=base_model.input, outputs=predictions)</pre><pre>opt = Adam(lr=0.000125)</pre><pre>model.compile(loss=&#39;categorical_crossentropy&#39;, optimizer&#39;adam&#39;, metrics=[&#39;accuracy&#39;])</pre><h4>Callbacks</h4><pre>callbacks_list = [<br>    ModelCheckpoint(<br>        &#39;../weights/service_weights.h5&#39;, monitor=&#39;val_accuracy&#39;,            verbose=1, save_best_only=True, mode=&#39;max&#39;),<br>    EarlyStopping(monitor=&#39;val_accuracy&#39;, patience=5),<br>    ReduceLROnPlateau(monitor=&#39;val_accuracy&#39;, patience=3, verbose=1, factor=0.5, min_lr=0.00001)<br>]</pre><h4>Generators</h4><pre>def add_noise(img):<br>    &#39;&#39;&#39;Add random noise to an image&#39;&#39;&#39;<br>    VARIABILITY = 8<br>    deviation = VARIABILITY*random.random()<br>    noise = np.random.normal(0, deviation, img.shape)<br>    img += noise<br>    np.clip(img, 0., 255.)</pre><pre>    return img</pre><pre>train_datagen = ImageDataGenerator(<br>    brightness_range=[0.2, 1.6],<br>    rescale=1. / 255,<br>    rotation_range=0,<br>    width_shift_range=0.1,<br>    height_shift_range=0.1,<br>    shear_range=0.2,<br>    zoom_range=0.2,<br>    horizontal_flip=True,<br>    fill_mode=&quot;nearest&quot;,<br>    preprocessing_function=add_noise,<br>)</pre><pre>train_generator = train_datagen.flow_from_dataframe(<br>    train_df,<br>    IMG_DIR,<br>    x_col=&#39;filename&#39;,<br>    y_col=&#39;category&#39;,<br>    target_size=IMAGE_SIZE,<br>    color_mode = &#39;grayscale&#39;,<br>    class_mode=&#39;categorical&#39;,<br>    batch_size=BATCH_SIZE<br>)</pre><pre><br>validation_datagen = ImageDataGenerator(rescale=1./255)</pre><pre>validation_generator = validation_datagen.flow_from_dataframe(<br>    validate_df,<br>    IMG_DIR,<br>    x_col=&#39;filename&#39;,<br>    y_col=&#39;category&#39;,<br>    target_size=IMAGE_SIZE,<br>    color_mode = &#39;grayscale&#39;,<br>    class_mode=&#39;categorical&#39;,<br>    shuffle=False,<br>    batch_size=BATCH_SIZE<br>)</pre><h4><strong>Fit Model</strong></h4><pre>epochs=50 if FAST_RUN else 50</pre><pre>history = model.fit_generator(<br>    train_generator,<br>    epochs=epochs,<br>    validation_data=validation_generator,<br>    validation_steps=total_validate//BATCH_SIZE,<br>    steps_per_epoch=total_train//BATCH_SIZE,<br>    callbacks=callbacks_list<br>)</pre><h4><strong>Classification Report Results</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*NoqaaqONkTetkxlVxBaP_g.png" /><figcaption>Evaluation of validation set</figcaption></figure><h3>Step 3 : OpenCV Face Detection Strategy</h3><p>In order to find faces in a frame/image and then identify if the person is wearing a mask or not, I used <a href="https://docs.opencv.org/3.4/db/d28/tutorial_cascade_classifier.html">CascadeClassifier</a>, already included in the OpenCV library. In general, this training method uses an .xml file, which is also already included in the package, to train a model that recognizes faces in a generic way, using the Viola-Jones and AdaBoost method to improve performance.</p><pre>import cv2</pre><pre>filename = &quot;haarcascade_frontalface_alt2.xml&quot;</pre><pre># Load face recognition template<br>classifier = cv2.CascadeClassifier(f&#39;{cv2.haarcascades}/{filename}&#39;)</pre><pre># Detecting faces in the image<br>faces = classifier.detectMultiScale(image)</pre><p><em>The only problem with this method is that it only recognizes front faces in the 3x4 photo style.</em></p><h3>Step 4 : Predicting in Real Time</h3><pre>import silence_tensorflow.auto<br>from tensorflow.python.keras.models import load_model<br>from tensorflow.compat.v1 import InteractiveSession<br>from tensorflow.compat.v1 import ConfigProto<br>import numpy as np<br>import cv2</pre><pre>config = ConfigProto()<br>config.gpu_options.allow_growth = True<br>session = InteractiveSession(config=config)</pre><pre>keras_model = load_model(&#39;model.h5&#39;)<br>cam = cv2.VideoCapture(0) <br>file_name = &quot;haarcascade_frontalface_alt2.xml&quot;<br>classifier = cv2.CascadeClassifier(f&quot;{cv2.haarcascades}/{file_name}&quot;)</pre><pre>label = {<br>    0: {&quot;name&quot;: &quot;Mask only in the chin&quot;, &quot;color&quot;: (51, 153, 255), &quot;id&quot;: 0},<br>    1: {&quot;name&quot;: &quot;Mask below the nose&quot;, &quot;color&quot;: (255, 255, 0), &quot;id&quot;: 1},<br>    2: {&quot;name&quot;: &quot;Without mask&quot;, &quot;color&quot;: (0,0,255), &quot;id&quot;: 2},<br>    3: {&quot;name&quot;: &quot;With mask ok&quot;, &quot;color&quot;: (0, 102, 51), &quot;id&quot;: 3},<br>}</pre><pre>while True:<br>    status, frame = cam.read()</pre><pre>    if not status:<br>        break</pre><pre>    if cv2.waitKey(1) &amp; 0xff == ord(&#39;q&#39;):<br>        break<br>    <br>    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)<br>    faces = classifier.detectMultiScale(gray)</pre><pre>    for x,y,w,h in faces:<br>        color = (0,0,0)<br>        gray_face = gray[y:y+h+50, x:x+w+50]</pre><pre>        if gray_face.shape[0] &gt;= 200 and gray_face.shape[1] &gt;= 200:</pre><pre>            gray_face = cv2.resize(gray_face, (300, 300))<br>            gray_face = gray_face / 255<br>            gray_face = np.expand_dims(gray_face, axis=0)<br>            gray_face = gray_face.reshape((1, 300, 300, 1))<br>            pred = np.argmax(keras_model.predict(gray_face))<br>            classification = label[pred][&quot;name&quot;]<br>            color = label[pred][&quot;color&quot;]</pre><pre>            cv2.rectangle(frame, (x,y), (x+w, y+h), color, label[pred][&quot;id&quot;])</pre><pre>            cv2.putText(frame, classification, (x, y + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2, cv2.LINE_AA)<br>            cv2.putText(frame, f&quot;{len(faces)} detected face&quot;,(20,20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,0,0), 2, cv2.LINE_AA)</pre><pre>    cv2.imshow(&quot;Cam&quot;, frame)</pre><h4>Result</h4><p>In this step, we will unify everything that was previously done in a script so that we can view the results in real time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*ulFAYPct4zCWVSRoGWbKSg.gif" /><figcaption>Real time detection.</figcaption></figure><p>🏷️ Labels<br>- Mask only in the chin [RGB Color: Neon Carrot]<br>- Mask below the nose [RGB Color: Aqua]<br>- Without mask [RGB Color: Red]<br>- With mask ok [RGB Color: Green]</p><h3>Final Remark</h3><p>We have developed a model that can identify whether a person has worn a mask or not. In addition, our model is able to identify whether a person is wearing the mask in the wrong way, either by not covering the nose or leaving the mask only on the chin. These types of models can be implemented in public places that would help the authorities to monitor the situation easily.</p><p>I hope this experiment help you in your studies or work. See you soon!</p><h3>Useful links</h3><ul><li>Repository that motivated this experiment:</li></ul><p><a href="https://github.com/MariaEduardaDeAzevedo/detector-de-mascaras">MariaEduardaDeAzevedo/detector-de-mascaras</a></p><ul><li>The code are available in my Github:</li></ul><p><a href="https://github.com/arthurfortes/face_mask_detection">arthurfortes/face_mask_detection</a></p><ul><li>Dataset</li></ul><p><a href="https://drive.google.com/file/d/1QP5Xwgg4WK9OGkzYUr63uGXaGy89nDaA/view?usp=sharing">mask_dataset_images.zip</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4aae008c95a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Recommender Systems Engines with a Python Framework]]></title>
            <link>https://medium.com/data-science/building-recommender-systems-engines-with-a-python-framework-5b4d29925c28?source=rss-4742b1c76a29------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b4d29925c28</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[collaborative-filtering]]></category>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[recommender-systems]]></category>
            <dc:creator><![CDATA[Arthur Fortes]]></dc:creator>
            <pubDate>Thu, 27 Feb 2020 17:53:47 GMT</pubDate>
            <atom:updated>2020-07-29T15:58:11.067Z</atom:updated>
            <content:encoded><![CDATA[<h4>A hand on guide to understand how to use and develop in Case Recommender</h4><figure><img alt="&lt;span&gt;Photo by &lt;a href=”https://unsplash.com/@mvdheuvel?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCop" src="https://cdn-images-1.medium.com/max/1024/1*0X-pNeFVsj_4w0nC1qKC8Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@mvdheuvel?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Maarten van den Heuvel</a> on <a href="https://unsplash.com/s/photos/documents?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>A number of frameworks for Recommender Systems (RS) have been proposed by the scientific community, involving different programming languages, such as Java, C\#, Python, among others. However, most of them lack an integrated environment containing clustering and ensemble approaches which are capable to improve recommendation accuracy. On the one hand, clustering may support developers to pre-process their data to optimize or extend recommender algorithms. On the other hand, ensemble approaches are efficient tools to combine different types of data in a personalized way.</p><p>In this article, I describe a python framework called Case Recommender, which contains a variety of content-based and collaborative recommender algorithms, as well as ensemble approaches for combining multiple algorithms and data sources. In addition, it provides a set of popular evaluation methods and metrics for rating prediction and item recommendation.</p><h3>Contextualization</h3><p>Traditionally, recommender systems employ filtering techniques and machine learning information to generate appropriate recommendations to the user’s interests from the representation of his profile. However, other techniques, such as Neural Networks, Bayesian Networks and Association Rules, are also used in the filtering process . The most used types of filtering are currently: Content-Based (CBF), responsible for selecting information based on content filtering of elements, e.g., e-mail messages filtered out as trash for containing unwanted words; Collaborative Filtering (CF), based on the relationship between people and their subjective regarding the information to be filtered. The selection of e-mails based on the relationship between sender and recipient is an example of that. Besides, there is a hybrid approach that combines the content-based and the collaborative filtering methods.</p><h3>Case Recommender</h3><p>Case Recommender is currently being rewritten to support optimized calculations using known Python scientific libraries. I also developed and improved classes that allow developers to manipulate files, predict and evaluate models, compute (dis)similarities between users or items, beside use metadata and external information. The framework is now implemented in Python 3 and it addresses two common scenarios in recommender systems: rating prediction and item recommendation, using explicit, implicit or both types of feedback in several recommender strategies. To install Case Recommender on Mac OS X / Linux/ Windows, chances are that one of the following two commands will work for developers and users:</p><pre>easy_install CaseRecommender</pre><p>or alternatively:</p><pre>pip install CaseRecommender</pre><p>The important features while designing our framework were to enable the computation of recommendations in large-scale, easy creation and extension of algorithms for different types of filtering and scenarios. Another feature is to support sparse and large datasets in a way that there is as little as possible overhead for storing data and intermediate results. Developers can choose between using one of the available recommender algorithms, combining multiple recommendations using one of the available ensemble techniques, or develop their own algorithm using the <em>BaseRatingPrediction </em>or <em>BaseItemRecommendation </em>classes. Up to the current version, the algorithms available in the framework are shown at table bellow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*DdfAtcwlhK8xQLd3AurzxQ.png" /></figure><h3>Input Data</h3><p>The framework allows developers to deal with different datasets and not having to develop their own programs to execute recommender functions. The input ofalgorithms expects the data to be in a simple text format:</p><blockquote>user_id item_id feedback</blockquote><p>where user_id and item_id are integers referring to users and items IDs, respectively, and feedback is a number expressing how much the user likes an item or binary interaction. The separator between the values can be either spaces, tabs, or commas. If there are more than three columns, all additional columns are ignored. For example, below is a sample of data from the <a href="https://grouplens.org/datasets/movielens/100k/">ML100k dataset</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/81/1*dx4N6pqltXMKIp1OBrBqnA.png" /></figure><h3>Datasets for Recommender Systems</h3><p>During my studies, I also build a repository of a topic-centric public data sources in high quality for RS. They are collected and tidied from Stack Overflow, articles, recommender sites and academic experiments. Most of the datasets presented in the repository are free, having open sorce linceses, however, some are not and you need to ask permission to use or cite the authors’ work. Access this link to obtain theses data.</p><p><a href="https://github.com/caserec/Datasets-for-Recommender-Systems">GitHub - caserec/Datasets-for-Recommender-Systems: This is a repository of a topic-centric public data sources in high quality for Recommender Systems (RS)</a></p><h3>Usage</h3><p>For divide our dataset using Fold Cross Validation:</p><pre>from caserec.utils.split_database import SplitDatabase</pre><pre>SplitDatabase(input_file=dataset, dir_folds=dir_path, n_splits=10).k_fold_cross_validation()</pre><p>Run Item Recommendation Algorithm (E.g: ItemKNN)</p><pre>from caserec.recommenders.item_recommendation.itemknn import ItemKNN</pre><pre>ItemKNN(train_file, test_file).compute()</pre><p>Run Rating Prediction Algorithm (E.g: ItemKNN)</p><pre>from caserec.recommenders.rating_prediction.itemknn import ItemKNN</pre><pre>ItemKNN(train_file, test_file).compute()</pre><p>Evaluate Ranking (Prec@N, Recall@N, NDCG@, Map@N and Map Total)</p><pre>from caserec.evaluation.item_recommendation import ItemRecommendationEvaluation<br> ItemRecommendationEvaluation().evaluate_with_files(predictions_file, test_file)</pre><p>Evaluate Ranking (MAE and RMSE)</p><pre>from caserec.evaluation.rating_prediction import RatingPredictionEvaluation</pre><pre>RatingPredictionEvaluation().evaluate_with_files(predictions_file, test_file)</pre><p>Run ItemKNN in Fold Cross Validation Approach</p><pre>from caserec.recommenders.item_recommendation.itemknn import ItemKNN<br>from caserec.utils.cross_validation import CrossValidation</pre><pre>## Cross Validation<br>recommender = ItemKNN(as_binary=True)<br>CrossValidation(input_file=db, recommender=recommender, dir_folds=folds_path, header=1, k_folds=5).compute()</pre><p>More examples can be found in this <a href="https://github.com/caserec/CaseRecommender/tree/master/examples">link</a>.</p><h3>Conclusions</h3><p>The goal of Case Recommender is to integrate and facilitate the experiments and development of new recommender techniques for different domains. Our framework contains a recommender engine, that contains content-based, collaborative and hybrid filtering approaches for rating prediction and item recommendation scenarios. In addition, the framework contains ensemble and clustering algorithms, validation and evaluation metrics to improve and measure the quality of the recommendation.</p><p>Future releases are planned which will include more features (parallel processing techniques and new algorithms) and an evaluation tool with several plots and graphs to help developers to better understand the behavior of their recommender algorithms.</p><h3>Useful Links</h3><ul><li><a href="https://github.com/caserec/CaseRecommender">caserec/CaseRecommender</a></li><li><a href="http://www.mymedialite.net/">MyMediaLite Recommender System Library</a></li><li><a href="https://dl.acm.org/doi/10.1145/3240323.3241611">Case recommender | Proceedings of the 12th ACM Conference on Recommender Systems</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b4d29925c28" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/building-recommender-systems-engines-with-a-python-framework-5b4d29925c28">Building Recommender Systems Engines with a Python Framework</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hands-On Speech Recognition Engine with Keras and Python]]></title>
            <link>https://fortes-arthur.medium.com/hands-on-speech-recognition-engine-with-keras-and-python-c60488ac53cd?source=rss-4742b1c76a29------2</link>
            <guid isPermaLink="false">https://medium.com/p/c60488ac53cd</guid>
            <category><![CDATA[speech-recognition]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Arthur Fortes]]></dc:creator>
            <pubDate>Thu, 20 Feb 2020 12:24:40 GMT</pubDate>
            <atom:updated>2020-02-20T16:18:14.201Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-15-lw5l6bSycWDnurzD5w.png" /></figure><p>Have you ever wondered how speech recognition algorithms work? These algorithms are increasingly popular, especially in personal assistants, such as Amazon, Siri and Google Assistent.</p><p>Speech recognition is the ability of a machine or program to identify words and phrases in spoken language and convert them to a machine-readable format. Usually, simple implementations of these algorithms has a limited vocabulary, and it may only identify words/phrases if they are spoken very clearly. However, more sophisticated algorithms such as <a href="https://cloud.google.com/speech-to-text">Cloud Speech-to-Text</a> from Google and <a href="https://aws.amazon.com/pt/transcribe/">Amazon Transcribe</a>, have a wide vocabulary and embrace of regionalism, noise and slang.</p><p>In this context, today I will report how to build a speech recognition model to recognize short commands. Best of all, developing and including speech recognition in a Python project using Keras is really simple. In this article, I will demonstrate:</p><ul><li>How speech to text works</li><li>How to process audio to be transcribed</li><li>A deep learning model using Keras to solve this challenge</li><li>One way to evaluate this model</li><li>A script to integrate the predictive model in your project</li></ul><h3>Overview</h3><p>Speech is simply a series of sound waves created by our vocal chords when they cause air to vibrate around them. These soundwaves are recorded by a microphone, and then converted into an electrical signal. The signal is then processed using advanced signal processing technologies, isolating syllables and words. Over time, the computer can learn to understand speech from experience, thanks to incredible recent advances in deep learning.</p><p>Speech recognition works using algorithms through acoustic and language modeling. Acoustic modeling represents the relationship between linguistic units of speech and audio signals; language modeling matches sounds with word sequences to help distinguish between words that sound similar. Often, deep learning models based on recurrent layers are used to recognize temporal patterns in speech to improve accuracy within the system. However, other approaches such as Hidden Markov model (the first speech recognition algorithms were made using this approach) can also be used. In this article, I will talk only about acoustic model.</p><h3>Signal Processing</h3><p>There are many ways to transform an audio waves into elements that an algorithm can process, one of these ways, and the one that we will use in this tutorial, is to record the height of the audio waves in equally spaced points:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vd_5HdXrCO8Asppw" /></figure><p>We are reading thousands of times per second and recording a number that represents the height of the sound wave at that moment. Basically, it is an uncompressed .wav audio file. The “CD Quality” audio is sampled at 44.1 kHz (44,100 readings per second). But for speech recognition, a sampling rate of 16khz (16,000 samples per second) is sufficient to cover the frequency range of human speech.</p><p>In this way an audio is represented through a number vector, in which each number represents the amplitude of the sound wave in intervals of 1/16000 of a second. This process is similar to what happens with image pre-processing, as can be seen in the example below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/0*aCGgzEeTReLKQxK-" /></figure><p>Thanks to Nyquist’s theorem (1933 — <a href="https://pt.wikipedia.org/wiki/Vladimir_Kotelnikov">Vladimir Kotelnikov</a>), we know that we can use mathematics to perfectly reconstruct the original sound wave from spaced samples — as long as we sample at least twice as fast as the highest frequency we want to record.</p><h3>Hands-On</h3><p>In order to perform this task, I used an <a href="https://www.anaconda.com/distribution/"><strong>Anaconda </strong></a>environment (Python 3.7) with the following Python libraries:</p><ul><li><a href="https://ipython.org/"><strong><em>ipython</em></strong></a> (v 7.10.2)</li><li><a href="https://keras.io/"><strong><em>keras</em></strong></a> (v 2.2.4)</li><li><a href="https://srclog.com/librosalibrosa"><strong><em>librosa</em></strong></a> (v 0.7.2)</li><li><a href="https://www.scipy.org/"><strong><em>scipy</em></strong></a> (v 1.1.0)</li><li><a href="https://scikit-learn.org/stable/"><strong><em>sklearn</em></strong></a><strong><em> </em></strong>(v 0.20.1)</li><li><a href="https://python-sounddevice.readthedocs.io/en/0.3.14/"><strong><em>sounddevice</em></strong></a> (v 0.3.14)</li><li><a href="https://www.tensorflow.org/"><strong><em>tensorflow</em></strong></a> (v 1.13.1)</li><li><a href="https://www.tensorflow.org/"><strong><em>tensorflow-gpu</em></strong></a><strong><em> </em></strong><em>(v 1.13.1)</em></li><li><a href="https://numpy.org/"><strong><em>numpy</em></strong></a><strong><em> </em></strong><em>(v </em>1.17.2<em>)</em></li></ul><p>The experiments were performed on a machine with the following hardware: Ryzen 5 3400g (4 CPU), 16 GB memory, NVIDIA GeForce GTX 1060, Ubuntu 18.04)</p><h4>1. Dataset</h4><p>We used in our experiments the Speech Commands Datasets provided by TensorFlow. It includes 65,000 one-second long utterances of 30 short words, by thousands of different people. We’ll build a speech recognition system that understands simple spoken commands. You can download the dataset from <a href="https://www.kaggle.com/c/tensorflow-speech-recognition-challenge">here</a>.</p><h4>2. Preprocessing the audio waves</h4><p>In the used dataset, the duration of a few recordings is less than 1 second and the sampling rate is too high. So, let us read the audio waves and use the below-preprocessing steps to deal with this. Here are the two steps we’ll follow:</p><ul><li>Resampling</li><li>Removing shorter commands of less than 1 second</li></ul><p>Let us define these pre-processing steps in the below code snippet:</p><pre>for label in labels:<br>    waves = [f for f in os.listdir(train_audio_path + &#39;/&#39;+ label) if f.endswith(&#39;.wav&#39;)]<br>    for wav in waves:<br>        samples, sample_rate = librosa.load(train_audio_path + &#39;/&#39; + label + &#39;/&#39; + wav, sr = 16000)<br>        samples = librosa.resample(samples, sample_rate, 8000)<br>        if(len(samples)== 8000) : <br>            all_wave.append(samples)<br>            all_label.append(label)</pre><p>From the above, we can understand that the sampling rate of the signal is 16000 hz. Let us resample it to 8000 hz since most of the speech related frequencies are present in 8000 hz.</p><p>The second step is treat our labels, here we convert the output labels to integer encoded and convert the integer encoded labels to a one-hot vector since it is a multi-target problem:</p><pre>label_enconder = LabelEncoder()<br>y = label_enconder.fit_transform(all_label)<br>classes = list(label_enconder.classes_)<br>y = np_utils.to_categorical(y, num_classes=len(labels))</pre><p>The last step of pre-processing step is reshape the 2D array to 3D since the input to the conv1d must be a 3D array:</p><pre>all_wave = np.array(all_wave).reshape(-1,8000,1)</pre><h4>3. Create train and validation set</h4><p>In order to perform our deep learning model, we will need generate two sets (train and validate). For this experiment, I train the model with 80% of the data and validate on the remaining 20%:</p><pre>x_train, x_valid, y_train, y_valid = train_test_split(np.array(all_wave),np.array(y),stratify=y,test_size=0.2,random_state=777,shuffle=True)</pre><h4>4. Model Architecture</h4><p>I used Conv1d and GRU layers to model the network that is used for speech recognition. Conv1d is a convolutional neural network which performs the convolution along only one dimension and GRU (Gated Recurrent Unit) aims to solve the vanishing gradient problem which comes with a standard recurrent neural network. GRU can also be considered as a variation on the LSTM because both are designed similarly and, in some cases, produce equally excellent results.</p><p>This proposed model was based on <a href="https://arxiv.org/abs/1512.02595">DeepSpeech2</a> and <a href="https://github.com/facebookresearch/wav2letter">Wav2letter++</a> algoritms, two well known speech recognition approaches. The code below illustrate the proposed model using Keras:</p><pre>inputs = Input(shape=(8000,1))<br>x = BatchNormalization(axis=-1, momentum=0.99, epsilon=1e-3, center=True, scale=True)(inputs)</pre><pre>#First Conv1D layer<br>x = Conv1D(8,13, padding=&#39;valid&#39;, activation=&#39;relu&#39;, strides=1)(x)<br>x = MaxPooling1D(3)(x)<br>x = Dropout(0.3)(x)</pre><pre>#Second Conv1D layer<br>x = Conv1D(16, 11, padding=&#39;valid&#39;, activation=&#39;relu&#39;, strides=1)(x)<br>x = MaxPooling1D(3)(x)<br>x = Dropout(0.3)(x)</pre><pre>#Third Conv1D layer<br>x = Conv1D(32, 9, padding=&#39;valid&#39;, activation=&#39;relu&#39;, strides=1)(x)<br>x = MaxPooling1D(3)(x)<br>x = Dropout(0.3)(x)</pre><pre>x = BatchNormalization(axis=-1, momentum=0.99, epsilon=1e-3, center=True, scale=True)(x)</pre><pre>x = Bidirectional(CuDNNGRU(128, return_sequences=True), merge_mode=&#39;sum&#39;)(x)<br>x = Bidirectional(CuDNNGRU(128, return_sequences=True), merge_mode=&#39;sum&#39;)(x)<br>x = Bidirectional(CuDNNGRU(128, return_sequences=False), merge_mode=&#39;sum&#39;)(x)</pre><pre>x = BatchNormalization(axis=-1, momentum=0.99, epsilon=1e-3, center=True, scale=True)(x)</pre><pre>#Flatten layer<br># x = Flatten()(x)</pre><pre>#Dense Layer 1<br>x = Dense(256, activation=&#39;relu&#39;)(x)<br>outputs = Dense(len(labels), activation=&quot;softmax&quot;)(x)</pre><pre>model = Model(inputs, outputs)<br>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*FZKSbKq1MTbcJM-pVcYq5Q.png" /></figure><p><strong><em>Note</em></strong><em>: If you will use only CPU to train this model, please replace the CuDNNGRU layer with GRU.</em></p><p>The next step is to define the loss function to be categorical cross-entropy since it is a multi-classification problem:</p><pre>model.compile(loss=&#39;categorical_crossentropy&#39;, optimizer=&#39;nadam&#39;, metrics=[&#39;accuracy&#39;])</pre><p>Early stopping and model checkpoints are the callbacks to stop training the neural network at the right time and to save the best model after every epoch:</p><pre>early_stop = EarlyStopping(monitor=&#39;val_loss&#39;, mode=&#39;min&#39;, verbose=1, patience=15, min_delta=0.0001) <br>checkpoint = ModelCheckpoint(&#39;speech2text_model.hdf5&#39;, monitor=&#39;val_acc&#39;, verbose=1, save_best_only=True, mode=&#39;max&#39;)</pre><p>Let us train the model on a batch size of 32 and evaluate the performance on the holdout set:</p><pre>hist = model.fit(<br>    x=x_train, <br>    y=y_train,<br>    epochs=100, <br>    callbacks=[early_stop, checkpoint], <br>    batch_size=32, <br>    validation_data=(x_valid,y_valid)<br>)</pre><p>And the output of this command is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*YIF9BqwB646vaCstMr0JJA.png" /></figure><h4>5. Diagnostic plot</h4><p>I’m going to lean on visualization again to understand the performance of the model over a period of time:</p><pre>pyplot.plot(hist.history[&#39;loss&#39;], label=&#39;train&#39;)<br>pyplot.plot(hist.history[&#39;val_loss&#39;], label=&#39;test&#39;)<br>pyplot.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*DBU47phU2qsKgwGGVvoR3g.png" /></figure><h4>6. It’s time to predict</h4><p>In this step, we will load the best weights and define the function that recognizes the audio and converts it to text:</p><pre>model = load_model(&quot;speech2text_model.hdf5&quot;)</pre><pre>def s2t_predict(audio, shape_num=8000):<br>    prob = model.predict(audio.reshape(1,shape_num,1))<br>    index = np.argmax(prob[0])<br>    return classes[index]</pre><p>Prediction time! Make predictions on the validation data:</p><pre>index = random.randint(0,len(x_valid) - 1)<br>samples = x_valid[index].ravel()</pre><pre>print(&quot;Audio:&quot;, classes[np.argmax(y_valid[index])])<br>print(&quot;Predicted Text:&quot;, s2t_predict(samples))</pre><pre>ipd.Audio(samples, rate=8000)</pre><p>Here is a script that prompts a user to record voice commands. Record your own voice commands and test it on the model:</p><pre>samplerate = 16000</pre><pre># the value below must be in seconds  <br>duration = 1</pre><pre>filename = &#39;recorded_audio.wav&#39;<br>print(&quot;start&quot;)</pre><pre>mydata = sd.rec(int(samplerate * duration), samplerate=samplerate,<br>    channels=1, blocking=True)</pre><pre>print(&quot;end&quot;)</pre><pre>sd.wait()<br>sf.write(filename, mydata, samplerate)</pre><p>Finally, we create a script to read the saved voice command and convert it to text:</p><pre>audio, audio_rate = librosa.load(&#39;recorded_audio.wav&#39;, sr=16000)<br>audio_sample = librosa.resample(audio, audio_rate, 4351)</pre><pre>ipd.Audio(audio_sample,rate=8000)</pre><pre>print(&quot;Predicted Text:&quot;, s2t_predict(audio_sample))</pre><h3>Final Remark</h3><p>Speech recognition technology is already a part of our everyday lives, but for now is still limited to relatively simple commands. As the technology advances, researchers will be able to create more intelligent systems that understand conversational speech. In this article, I reported a speech-to-text algorithm based on two well-known approaches to recognize short commands using Python and Keras.</p><p>The talk presentation and the code is available in<strong> </strong><a href="https://github.com/arthurfortes/speech2text_keras"><strong><em>GitHub</em></strong></a><strong>.</strong></p><p>Processing, interpreting and understanding an audio wave is the key to many powerful new technologies and methods of communication. Given current trends, speech recognition technology will be a fast-growing (and world-changing) subset of signal processing for years to come.</p><p>In the next steps, I will work with the language model to correct the output of this approach. I hope this article has been useful for you and until next time.</p><h3>References</h3><p>[1] <a href="https://www.analyticsvidhya.com/blog/2019/07/learn-build-first-speech-to-text-model-python/">Learn how to Build your own Speech-to-Text Model (using Python). Aravind Pai. 2019</a></p><p>[2] <a href="https://arxiv.org/abs/1512.02595">Deep Speech 2: End-to-End Speech Recognition in English and Mandarin. Dario Amodei et al. 2015</a></p><p>[3] <a href="https://github.com/facebookresearch/wav2letter">Wav2Letter: an End-to-End ConvNet-based Speech Recognition System. Ronan Collobert, Christian Puhrsch, Gabriel Synnaeve. 2016.</a></p><h3>Useful links</h3><p><a href="https://github.com/arthurfortes/speech2text_keras">arthurfortes/speech2text_keras</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c60488ac53cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Label Where’s Wally/Waldo images using OpenCV and Deep Learning (YOLO v2)]]></title>
            <link>https://fortes-arthur.medium.com/how-to-label-wheres-wally-waldo-images-using-opencv-and-deep-learning-yolo-v2-abba7150999f?source=rss-4742b1c76a29------2</link>
            <guid isPermaLink="false">https://medium.com/p/abba7150999f</guid>
            <category><![CDATA[computacional-vision]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[wally]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Arthur Fortes]]></dc:creator>
            <pubDate>Fri, 14 Feb 2020 14:14:07 GMT</pubDate>
            <atom:updated>2021-02-03T14:47:13.430Z</atom:updated>
            <content:encoded><![CDATA[<h4>A hand on guide to learn how to use a object detection network</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*AiJcbJRqbmyE84INkcK7cA.jpeg" /><figcaption>Where’s Wally puzzle example.</figcaption></figure><p>In this article, our goal is to recognize the famous character Wally or Waldo (yes, he has a few names around the world) in an image. Although there are already some consistent solutions, I decided to implement this challenge using an architecture called YOLO (You Only Look Once), a real-time object detection system that I am currently studying.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*YFNaWxqFQo33ubIS6ZUUdA.gif" /></figure><p>In this purpose, I used an <a href="https://www.anaconda.com/distribution/"><strong>Anaconda </strong></a>environment (Python 3.7) with the following Python libraries:</p><ul><li><strong><em>o</em></strong><a href="https://docs.opencv.org/master/d9/df8/tutorial_root.html"><strong><em>pen</em></strong></a><strong><em>cv-python </em></strong><em>(v </em>4.1.1.26<em>)</em></li><li><strong><em>t</em></strong><a href="https://www.tensorflow.org/"><strong><em>ensorflow-</em></strong></a><strong><em>gpu </em></strong><em>(v 1.14.0)</em></li><li><a href="https://github.com/arthurfortes/darkflow"><strong><em>darkflow </em></strong></a><em>(v 1.0.0)</em></li><li><a href="https://numpy.org/"><strong><em>numpy</em></strong></a><strong><em> </em></strong><em>(v </em>1.17.2<em>)</em></li></ul><p>The experiments were performed on a machine with the following hardware: Ryzen 5 3400g (4 CPU), 16 GB memory, NVIDIA GeForce GTX 1060, Ubuntu 18.04)</p><p>There are 3 steps to achieve our goal: First we need to build a dataset, then we need to perform YOLO model and finally we create an output image highlighting Wally.</p><h3>Step1 : Wally Dataset</h3><p>Our dataset was composed by images that we found online, <a href="https://www.kaggle.com/residentmario/wheres-waldo">Keagle</a> and data augmentation (Vertical Flip, Brightness modification) using Keras (<a href="https://keras.io/preprocessing/image/"><strong>ImageDataGenerator</strong></a>). As a second task, we label the images obtained, highlighting the location of Wally in each one. <a href="https://github.com/tzutalin/labelImg"><strong>LabelImg </strong></a>was using for this propose, since it is a great tool witch allow annotate images in Pascal VOC format (generate xml files).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O28xbe4vNrIiEpaYXjfm2A.png" /><figcaption>Images from our dataset with annotation in LabelImg</figcaption></figure><p>As result of this task, we built a dataset with 350 images.</p><h3><strong><em>Step2 : Perform Deep Learning </em></strong>Architecture</h3><p>In order to detect Wally we used Yolo algorithm, an deep learning object detection architecture based on convolution neural networks.</p><p>Yolo is a single network trained end to end to perform a regression task predicting both object bounding box and object class proposed by Joseph Redmon , Ali Farhadi, Ross Girshick and Santosh Divvala in 2015.</p><blockquote>The paper is available in this <a href="https://arxiv.org/pdf/1612.08242.pdf">link</a>.</blockquote><p>I have used open source implementation, “<a href="https://github.com/thtrieu/darkflow">Darkflow</a>”, so you don’t need to worry about the detail.</p><p><strong><em>Installing Darkflow</em></strong></p><p>I am currently updating the original version of Darkflow, updating dependencies and creating new features. In this way. I strongly recommend, that you use <a href="https://github.com/arthurfortes/darkflow"><strong>my github repository</strong></a> to follow this tutorial. In the repository, you will find the complete installation guide and other important instructions. I am just going to leave the instruction as simple as possible here (using conda and pip).</p><pre>conda install Cython<br>git clone <a href="https://github.com/arthurfortes/darkflow.git">https://github.com/arthurfortes/darkflow.git</a><br>cd darkflow<br>python setup.py build_ext - inplace<br>pip install .</pre><p><strong><em>Downloading Weights</em></strong></p><p>To train Yolo model it is recommended that you use the weights and the configurations already trained from the deep learning network. There are two ways of downloading these files. First of all, you can download it from the <a href="https://pjreddie.com/darknet/yolo/"><strong><em>official YOLO project webpage</em></strong></a>. Second, you can download it from <a href="https://drive.google.com/drive/folders/1Ocqn6jrwPUdaartTH8ZTewFlJVOgCwss?usp=sharing"><strong>my wheigts repository</strong></a>.</p><p><strong><em>Building and Training the Model</em></strong></p><p>In order to organize our project, we need to follow this repository tree:</p><pre>Wally_Project<br>|- built_graph<br>|- cfg<br>|---- yolov2-wally.cfg<br>|---- yolov2-wally.cfg<br>|- ckpt<br>|- labels.txt</pre><p>The files downloaded in the last section must be pasted in the <em>cfg </em>path and the other repositories may be empty. The labels.txt file must contain in each line the labels that our model will provide. In our case, our file contains only one line: “<em>wally”</em>.</p><p>As you can see in the darkflow repository, it is quiet simple to build the model. First, you need to create a <em>train_model.py</em> file and then define options object. Finally, you need to instantiate TFNet class object with the options.</p><p>As you can see below, it is quiet simple to build the model. First, you need to define options object. Then, you need to instantiate TFNet class object with the options.</p><pre>from darkflow.net.build import TFNet<br>import cv2</pre><pre>options = {<br>           &quot;model&quot;: &quot;cfg/yolov2-wally.cfg&quot;,<br>           &quot;load&quot;: &quot;cfg/yolov2-wally.weights&quot;,<br>           &quot;batch&quot;: 8,<br>           &quot;epoch&quot;: 1000,<br>           # comment the line bellow if you don&#39;t have GPU<br>           &quot;gpu&quot;: 0.8,<br>           &quot;train&quot;: True,<br>           &quot;annotation&quot;: &quot;data/total/annotations/&quot;,<br>           &quot;dataset&quot;: &quot;data/total/images/&quot;,<br>           &quot;load&quot;: -1<br>           }</pre><p>The options is a specification of the model and its environment. These and other specifications are described below.</p><pre>&#39;<strong>imgdir</strong>&#39;: path to testing directory with images        <br>&#39;<strong>binary</strong>&#39;: path to .weights directory     <br>&#39;<strong>config</strong>&#39;: path to .cfg directory     <br>&#39;<strong>dataset</strong>&#39;: path to dataset directory     <br>&#39;<strong>labels</strong>&#39;: path to labels file       <br>&#39;<strong>backup</strong>&#39;: path to backup folder   <br>&#39;<strong>summary</strong>&#39;: path to TensorBoard summaries directory       <br>&#39;<strong>annotation</strong>&#39;: path to annotation directory       <br>&#39;<strong>threshold</strong>&#39;: detection threshold       <br>&#39;<strong>model</strong>&#39;: configuration of choice       <br>&#39;<strong>trainer</strong>&#39;: training algorithm        <br>&#39;<strong>momentum</strong>&#39;: applicable for rmsprop and momentum optimizers        &#39;<strong>verbalise</strong>&#39;: say out loud while building graph        <br>&#39;<strong>train</strong>&#39;: train the whole net        <br>&#39;<strong>load</strong>&#39;: how to initialize the net? Either from .weights or a checkpoint, or even from scratc     <br>&#39;<strong>savepb</strong>&#39;: save net and weight to a .pb file       <br>&#39;<strong>gpu</strong>&#39;: how much gpu (from 0.0 to 1.0)    <br>&#39;<strong>gpuName</strong>&#39;: GPU device name    <br>&#39;<strong>lr</strong>&#39;: learning rate   <br>&#39;<strong>keep</strong>&#39;: Number of most recent training results to save     <br>&#39;<strong>batch</strong>&#39;: batch size<br>&#39;<strong>epoch</strong>&#39;: number of epoch <br>&#39;<strong>save</strong>&#39;: save checkpoint every ? training examples<br>&#39;<strong>demo</strong>&#39;: demo on webcam<br>&#39;<strong>queue</strong>&#39;: process demo in batch       <br>&#39;<strong>json</strong>&#39;: Outputs bounding box information in json format       &#39;<strong>saveVideo</strong>&#39;: Records video from input video or camera<br>&#39;<strong>pbLoad</strong>&#39;: path to .pb protobuf file (metaLoad must also be specified<br>&#39;<strong>metaLoad</strong>&#39;: path to .meta file generated during --savepb that corresponds to .pb file</pre><p>As I suggested to download yolo.weights from <a href="https://drive.google.com/drive/folders/1Ocqn6jrwPUdaartTH8ZTewFlJVOgCwss?usp=sharing"><strong><em>here</em></strong></a>, I specified it. If you have your own pre-trained weight files, this is where you let the model knows (like after you trained custom objects, your system will produce the specific weight file).</p><p>That done, just run the script with this command:</p><pre>python train_model.py</pre><p>and wait a few minutes … hours … days …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*OSmgPBwMc8ErKp1IFYBQ8A.gif" /><figcaption>Good time to have a coffee and see how the day is outside.</figcaption></figure><blockquote><strong>Important Trick: </strong>I had a lot of difficulty when I started using Yolo. First because the models never performed as desired, second because generally the predictions were meaningless (sometimes they didn’t even appear). After a while, I discovered that there is a trick for this model to work: training the first time with few examples (3 or 5 images) for many times (I usually use 1000). That done, we trained yolo algorithm with all dataset at once.</blockquote><h3>Step3 : It’s time to find Wally!</h3><p>In this step, we need to create a script to find Wally, using our trained weights.</p><pre>options = {&quot;pbLoad&quot;: &quot;yolov2-wally.pb&quot;,<br>           &quot;metaLoad&quot;: &quot;yolov2-wally.meta&quot;}<br>yolo_sensor = TFNet(options)</pre><p>To highlight Wally in the image, I developed a function using OpenCV to draw a rectangle around the object, as seen below.</p><pre>def highlight_wally(img, predictions, padding=20):<br>    predictions.sort(key=lambda x: x.get(&#39;confidence&#39;))<br>    <br>    for pred in predictions:<br>        xtop = pred.get(&#39;topleft&#39;).get(&#39;x&#39;)<br>        ytop = pred.get(&#39;topleft&#39;).get(&#39;y&#39;)<br>        xbottom = pred.get(&#39;bottomright&#39;).get(&#39;x&#39;)<br>        ybottom = pred.get(&#39;bottomright&#39;).get(&#39;y&#39;)<br>        cv2.rectangle(img, (xtop-padding, ytop-padding), (xbottom+padding, ybottom+padding), (0, 0, 0), 3)  <br>        font_scale = 2<br>        font = cv2.FONT_HERSHEY_PLAIN<br>        rectangle_bgr = (0, 0, 0)<br>        text = &quot;Wally {}%&quot;.format(round(float(pred.get(&#39;confidence&#39;)), 2)*100)<br>        # get the width and height of the text box<br>        (text_width, text_height) = cv2.getTextSize(text, font, fontScale=font_scale, thickness=1)[0]<br>        # set the text start position<br>        text_offset_x = xtop<br>        text_offset_y = ytop - 30<br>        # make the coords of the box with a small padding of two pixels<br>        box_coords = ((text_offset_x, text_offset_y), (text_offset_x + text_width + 2, text_offset_y - text_height - 2))<br>        cv2.rectangle(img, box_coords[0], box_coords[1], rectangle_bgr, cv2.FILLED)<br>        cv2.putText(img, text, (text_offset_x, text_offset_y), font, fontScale=font_scale, color=(255, 255, 255), thickness=2)     <br>    <br>    return img</pre><p>Finally, I built a prediction function using Yolo v2 model and the OpenCV function:</p><pre>def yolo_predict(img, output_path):<br>    imgcv = cv2.imread(img)<br>    result = yolo_sensor.return_predict(imgcv)<br>    labeled_img = highlight_wally(imgcv, result)<br>    cv2.imwrite(&#39;{}_labaled.png&#39;.format(img[:img.rfind(&#39;.&#39;)]), labeled_img)</pre><p>And the result was:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XRV9dQUuRVw1dJUJNWUE8g.png" /><figcaption>Wally was found with 72% certainty.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*0SEfRQrCs3glKgy6DmOnKQ.png" /><figcaption>For this experiment we built a dataset with 350 images.</figcaption></figure><blockquote><em>The trained weights are in </em>my <a href="https://drive.google.com/drive/folders/1Ocqn6jrwPUdaartTH8ZTewFlJVOgCwss?usp=sharing">Google Drive</a>.</blockquote><blockquote><em>You can find the whole code in my </em><a href="https://github.com/arthurfortes/yolo-find-wally">GitHub</a>.</blockquote><h3>Final Remark</h3><p>In this article, we created a model to find Wally in images using YOLO architecture. YOLO is a relatively simple way to generate object detectors with a good accuracy rate and quickly (if you are using GPU).</p><p>It is difficult to create a robust solution that works in all Wally’s puzzle scenarios. We could have improve our YOLO model in charge of that but it would need a lot more data and it’s very painful to annotated these images.</p><p>In the next steps, I will try realize this experiment using YOLO v3 model. I hope this article has been useful for you and until next time.</p><h3>Useful links</h3><ul><li><a href="https://github.com/arthurfortes/yolo-find-wally">arthurfortes/yolo-find-wally</a></li><li><a href="https://github.com/arthurfortes/darkflow">arthurfortes/darkflow</a></li><li><a href="https://pjreddie.com/darknet/yolo/">YOLO: Real-Time Object Detection</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abba7150999f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Consultar endereços e CEPs brasileiros utilizando Python]]></title>
            <link>https://fortes-arthur.medium.com/consultar-endere%C3%A7os-e-ceps-brasileiros-utilizando-python-9c8f14f4592?source=rss-4742b1c76a29------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c8f14f4592</guid>
            <dc:creator><![CDATA[Arthur Fortes]]></dc:creator>
            <pubDate>Thu, 06 Feb 2020 22:18:27 GMT</pubDate>
            <atom:updated>2020-02-06T22:18:27.261Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*MGanPoVMOFzPRZ0lUE4aGQ.png" /></figure><p>Atualmente, não existe nenhuma base oficial gratuita de consulta de endereços e CEPs no Brasil. Hoje, somente o site dos Correios pode ser usado para este fim, e foi através dele que desenvolvi uma API em Python chamada <em>consulta_correios.</em></p><p>Essa biblioteca é responsável por localizar o CEP através de informações dos endereços e/ou endereços pelo número do CEP, retornando o conteúdo da requisição. Para o segundo caso, já existem diversas bibliotecas e scripts, tais como <a href="https://viacep.com.br/">ViaCep</a> e <a href="https://github.com/mstuttgart/pycep-correios">PyCEP Correios</a>.</p><h3><strong>Como funciona?</strong></h3><p>A API faz uma requisição POST para o site dos correios com o CEP ou endereço desejado (o CEP/endereço deve ser passado como parâmetro). Como resposta, a API recebe todo o conteúdo da página com os resultados da busca.</p><blockquote><strong>Nota</strong>: Para testar a busca no site dos Correios, basta entrar <a href="http://www.buscacep.correios.com.br/sistemas/buscacep/resultadoBuscaCepEndereco.cfm">aqui</a>.</blockquote><p>Com o conteúdo retornado, utiliza-se a biblioteca <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/"><em>Beautiful Soup</em></a><em> </em>para manipular o HTML da página e recuperar somente os dados relevantes. Por fim, a API trata esses campos e os retornam através de um dicionário.</p><h3>Requisitos</h3><p>Python 3.5+</p><p>Bibliotecas Python:</p><ul><li>beautifulsoup4</li><li>requests</li><li>unidecode</li></ul><h3><strong>Instalação</strong></h3><p>Para instalar a versão do repositório do Python, basta utilizar o comando:</p><pre>pip install Consulta-Correios</pre><p>Para instalar a versão mais atual, basta utilizar o comando:</p><pre>pip install -U git+git://github.com/arthurfortes/consulta_correios.git</pre><h3>Utilização</h3><p>Para localizar o CEP pelo endereço, incluindo outros atributos (como tipo de logradouro ou bairro), basta utilizar o seguinte código:</p><pre>&gt;&gt;&gt; import consulta_correios<br><br>&gt;&gt;&gt; address = consulta_correios.busca_cep(&#39;Av. Júlio Prestes&#39;)<br>&gt;&gt;&gt; print(address)<br>{&#39;address&#39;: &#39;Avenida Julio Prestes&#39;, &#39;neighborhood&#39;: &#39;Taquaral&#39;, &#39;city/state&#39;: &#39;Campinas/SP&#39;, &#39;zipcode&#39;: &#39;13076-001&#39;}</pre><p>Para localizar o endereço pelo CEP, utiliza-se o mesmo código, mudando apenas o parâmetro:</p><pre>&gt;&gt;&gt; import consulta_correios<br><br>&gt;&gt;&gt; address = consulta_correios.busca_cep(&#39;13073-003&#39;)<br>&gt;&gt;&gt; print(address)<br>{&#39;address&#39;: &#39;Avenida Julio Prestes&#39;, &#39;neighborhood&#39;: &#39;Taquaral&#39;, &#39;city/state&#39;: &#39;Campinas/SP&#39;, &#39;zipcode&#39;: &#39;13076-001&#39;}</pre><blockquote>Quer contribuir? Basta acessar o <a href="https://github.com/arthurfortes/consulta_correios">Github </a>da API e seguir as instruções.</blockquote><h3><strong>Conclusões</strong></h3><p>Neste artigo, apresentei a Consulta Correios, uma API em Python para auxiliar os desenvolvedores, de maneira prática e simples, a obter informações de endereço (logradouro, cidade, estado, CEP, etc). A biblioteca é open-source e está aberta para uso comercial e contribuições. :)</p><h3>Referências</h3><p><a href="https://github.com/arthurfortes/consulta_correios">arthurfortes/consulta_correios</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c8f14f4592" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling with .doc extension with Python]]></title>
            <link>https://fortes-arthur.medium.com/handling-with-doc-extension-with-python-b6491792311e?source=rss-4742b1c76a29------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6491792311e</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[file-handling]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Arthur Fortes]]></dc:creator>
            <pubDate>Thu, 30 Jan 2020 19:32:44 GMT</pubDate>
            <atom:updated>2020-01-30T19:32:44.117Z</atom:updated>
            <content:encoded><![CDATA[<h3>Handling with .doc extension with Python</h3><h4>A guide to performing operations on .doc files using Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*RG9pdBfvutcz3UGO0wD2-Q.png" /></figure><p>In this week I started one project, in which I need read a Word doc (.doc) and extract relevant information from it. However, I never work with .doc files and then I started to research it. I found lots of information on reading .docx (e.g. <a href="https://textract.readthedocs.io/en/stable/">textract</a>)but much less on .doc.</p><p>In this context, I’m writing this article to share a native solution for anyone working with <a href="https://www.anaconda.com/">Anaconda</a>, without needing extra installations (if you use pure Python, just install a library). The magic library is called <a href="https://github.com/mhammond/pywin32"><strong><em>win32com</em></strong></a><strong><em>, </em></strong>which provides access to many of the Windows APIs from Python., such as .ppt.</p><h3>1. Installing via PIP</h3><ul><li>If you are using Anaconda, please skip this step.</li></ul><pre>pip install pywin32</pre><p>For more information about installation, you could access <a href="https://github.com/mhammond/pywin32">win32com Github</a>.</p><h3>2. Import and read file</h3><p>Here’s a script to save Word documents in and below a given directory to text.</p><pre>import fnmatch, os, pythoncom, sys, win32com.client<br><br>wordapp = win32com.client.gencache.EnsureDispatch(&quot;Word.Application&quot;)</pre><pre><br>try:<br>    for path, dirs, files in os.walk(sys.argv[1]):<br>        for doc in [os.path.abspath(os.path.join(path, filename)) for filename in files if fnmatch.fnmatch(filename, &#39;*.doc&#39;)]:<br>            print &quot;processing %s&quot; % doc<br>            wordapp.Documents.Open(doc)<br>            docastxt = doc.rstrip(&#39;doc&#39;) + &#39;txt&#39;<br>            wordapp.ActiveDocument.SaveAs(docastxt, FileFormat=win32com.client.constants.wdFormatTextLineBreaks)<br>            wordapp.ActiveWindow.Close()</pre><pre>finally:<br>    wordapp.Quit()</pre><p>To get other elements of the document, you ca use the follow command:</p><pre>element = doc.Content. =&gt; text</pre><h3>3. Create and write text to a Word Document</h3><p>When using win32com, bear in mind that you are talking to the Word object model. You don’t need to know a lot of VBA or other languages to apply the samples to using Python; you just need to figure out which parts of the object model are being used. Here, we have a simple example of how create a Word Document with content.</p><pre>import win32com.client</pre><pre># Create new Word Object<br>wordapp = win32com.client.Dispatch(&quot;Word.Application&quot;) </pre><pre># Word Application should`t be visible<br>wordapp.Visible = 0</pre><pre># Create new Document Object<br>worddoc = wordapp.Documents.Add()</pre><pre># Make some Setup to the Document:<br>worddoc.PageSetup.Orientation = 1 <br>worddoc.PageSetup.LeftMargin = 20<br>worddoc.PageSetup.TopMargin = 20<br>worddoc.PageSetup.BottomMargin = 20<br>worddoc.PageSetup.RightMargin = 20<br>worddoc.Content.Font.Size = 11<br>worddoc.Content.Paragraphs.TabStops.Add (100)<br>worddoc.Content.Text = &quot;Hello, I am a text!&quot;<br>worddoc.Content.MoveEnd</pre><pre># Close the Word Document (a save-Dialog pops up)<br>worddoc.Close()</pre><pre># Close the Word Application<br>wordapp.Quit()</pre><h3>4. Extra</h3><p>Here you will find a simple example how to create a small Table in Word and to fill it with date.</p><pre>from win32com import client<br>import powerfactory as pf</pre><pre>app = pf.GetApplication()<br>lines = app.GetCalcRelevantObjects(&#39;*.ElmLne&#39;)<br>ldf = app.GetFromStudyCase(&#39;ComLdf&#39;)</pre><pre>ldf.Execute()<br>nr_lines = len(lines)</pre><pre>wordapp = client.Dispatch(&quot;Word.Application&quot;)<br>wordapp.Visible = True<br>worddoc = wordapp.Documents.Add()</pre><pre><br>rang = doc.Range(Start=0,End=0)<br>worddoc.Tables.Add(rang, NumRows=2, NumColumns=1)<br>index = 2 + nr_lines</pre><pre>worddoc.Tables(1).Rows(2).Cells(1).Split(1,3)<br>width = doc.Tables(1).Rows(1).Cells(1).Width<br>worddoc.Tables(1).Rows(1).Cells(1).Range.Bold=True<br>worddoc.Tables(1).Rows(1).Cells(1).Range.Font.Size=15<br>worddoc.Tables(1).Rows(1).Cells(1).Range.Text=&#39;Report of LoadFlow Calculations from PowerFactory&#39;<br>worddoc.Tables(1).Cell(2,1).Range.Text=&#39;Name of the line&#39;<br>worddoc.Tables(1).Cell(2,2).Range.Text=&#39;Loading&#39;<br>worddoc.Tables(1).Cell(2,3).Range.Text=&#39;Comment&#39;<br>app.PrintPlain(doc.Tables(1).Rows(2).Cells)</pre><pre>for i,line in enumerate(lines):<br>    worddoc.Tables(1).Rows.Add()<br>    worddoc.Tables(1).Cell(i+3,1).Range.Text=line.loc_name<br>    worddoc.Tables(1).Cell(i+3,2).Range.Text=str(<br>round(line.GetAttribute(&#39;c:loading&#39;),2))+ &#39; %&#39;</pre><pre>if(line.GetAttribute(&#39;c:loading&#39;)&gt;60):<br>        worddoc.Tables(1).Cell(i+3,3).Range.Font.Color=225<br>        worddoc.Tables(1).Cell(i+3,3).Range.Text=&#39;LoadingOver 60%&#39;</pre><p>To copy the contents of a Word document and paste it into an Outlook application, just follow the code below.</p><pre>import win32com.client<br><br>word = win32com.client.Dispatch(&quot;Word.Application&quot;)<br>doc = word.Documents.Open(word_path)<br>doc.Content.Copy()<br>doc.Close()<br><br>outlook = win32com.client.Dispatch(&quot;Outlook.Application&quot;)<br># Create a new MailItem object<br>msg = outlook.CreateItem(0)<br>msg.GetInspector.WordEditor.Range(Start=0, End=0).Paste()<br><br>msg.Display(False)</pre><h3>Final Remark</h3><p>File handling in Python is pretty easy because most of the basic operations just take a single line of code to do the job, as we have seen in this article. However, when you need to handling with a proprietary software some difficulties begin to appear. In this article, I introduced the <a href="https://github.com/mhammond/pywin32"><strong><em>win32com</em></strong></a> lib, which is capable of manipulating .doc extension, the mainly Microsoft Word format. I hope this content be useful for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6491792311e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>