scieee AI-readable full text Open interactive document viewer

Implementation of Deep Learning models for Information Extraction on Identification Documents

Renda, Henrique Eduardo Espadinha

Abstract

The development of object detection models has revolutionized the analysis of personal information on identification cards, leading to a decrease in external human labor. Although previous strategies have been employed to address this issue without using machine learning models, they all present certain limitations, which artificial intelligence aims to overcome. This report delves into the development of a deep learning-based object detection capable of recognizing relevant information from Portuguese identification cards. All the decisions made during the project will be accompanied by a detailed background theory. Additionally, we provide an in-depth analysis of Optical Character Recognition (OCR) technology, which was utilized throughout the project to generate text from images. As the newest member of the Machine learning Team of Biometrid, I had the privilege of being involved in this project that led to the improvement of the current approach that does not leverage machine learning in the detection of relevant sections from ID cards. The findings of this project provide a foundation for further research into the use of AI in identification card analysis.

Full text

i Implementation of Deep Learning models for Information Extraction on Identification Documents Henrique Eduardo Espadinha Renda Internship at Biometrid Internship report presented as partial requirement for obtaining the Master’s degree Program in Data Science and Advanced Analytics i Title: Implementation of Deep Learning models for Information Extraction on Identification Documents Internship at Altice Portugal Henrique Eduardo Espadinha Renda MAA 2023 i ii NOVA Information Management School Instituto Superior de Estatística e Gestão de Informação Universidade Nova de Lisboa IMPLEMENTATION OF DEEP LEARNING MODELS FOR INFORMATION EXTRACTION ON IDENTIFICATION DOCUMENTS by Henrique Renda Internship report presented as partial requirement for obtaining the Master’s degree in Data Science and Advanced Analytics Advisor: Prof Doutor Roberto Henriques Co Advisor: Lucas Soares iii STATEMENT OF INTEGRITY As a member of the Biometrid team and master´s student at NOVA Information Management School, I pledge to uphold the highest standards of integrity and ethical conduct in the completion of my internship report. This includes ensuring the accuracy and truthfulness of all information presented, properly citing any sources used, and refraining from plagiarism or any other form of academic dishonesty. I will also maintain confidentiality and respect any privacy or sensitive information that may be shared during the course of my internship. I understand that any violation of these principles may result in disciplinary action, and I am fully committed to conducting myself in an honest and trustworthy manner throughout my internship. Lisbon, February 2023 iv February 2023 DEDICATION I dedicate this report to my family and friends, who have been a constant source of inspiration and motivation. In particular, I would like to express my deepest appreciation to my parents and girlfriend for their unwavering support, encouragement, and motivation that have been instrumental in helping me persevere through the challenges and celebrate the triumphs. Additionally, I extend my gratitude to my mentors for providing invaluable guidance and support throughout the research process. This report represents the culmination of years of hard work, and I am honored to share it with those who have played a significant role in shaping my academic and personal growth. v vi ABSTRACT The development of object detection models has revolutionized the analysis of personal information on identification cards, leading to a decrease in external human labor. Although previous strategies have been employed to address this issue without using machine learning models, they all present certain limitations, which artificial intelligence aims to overcome. This report delves into the development of a deep learning-based object detection capable of recognizing relevant information from Portuguese identification cards. All the decisions made during the project will be accompanied by a detailed background theory. Additionally, we provide an in-depth analysis of Optical Character Recognition (OCR) technology, which was utilized throughout the project to generate text from images. As the newest member of the Machine learning Team of Biometrid, I had the privilege of being involved in this project that led to the improvement of the current approach that does not leverage machine learning in the detection of relevant sections from ID cards. The findings of this project provide a foundation for further research into the use of AI in identification card analysis. KEYWORDS Artificial Intelligence; Machine Learning; Artificial Neural Networks; Computer Vision; Object Detection Models; Optical Character Recognition (OCR) vii INDEX 1. Introduction ................................................................................................................ 1 1.1. Company Overview .............................................................................................. 2 1.2. Problem Definition ............................................................................................... 3 1.2.1. Case Study ..................................................................................................... 4 1.2.2. Constraints and Limitations .......................................................................... 4 1.2.3. Proposed Solution ......................................................................................... 5 2. Theoretical Framework ............................................................................................... 6 2.1. Machine Learning ................................................................................................. 6 2.1.1. Supervised Learning ...................................................................................... 9 2.2. Artificial Neural Networks & CNNs ....................................................................... 9 2.2.1. Convolution Layers ...................................................................................... 10 2.2.2. Pooling Layers ............................................................................................. 11 2.2.3. Fully Connected Layers ............................................................................... 12 2.3. Deep learning ..................................................................................................... 13 2.4. Object Detection ................................................................................................ 14 2.4.1. Region-based Convolution Neural Networks (R-CNN) ................................ 15 2.4.2. Faster-RCNN ................................................................................................ 16 2.4.3. Single Shot MultiBox Detector (SSD) ........................................................... 17 2.4.4. CenterNet .................................................................................................... 18 2.5. Evaluation Metrics ............................................................................................. 19 2.5.1. Confusion Matrix ......................................................................................... 20 2.5.2. Intersection over Union (IoU) ..................................................................... 21 2.5.3. Precision and Recall .................................................................................... 22 2.5.4. F1-Score: ..................................................................................................... 22 2.5.5. Average Precision ........................................................................................ 22 2.5.6. Mean Average Precision (mAP) ................................................................... 23 2.6. Optical Character Recognition (OCR) ................................................................. 23 3. Methodology ............................................................................................................. 26 3.1. Tools and Technologies ...................................................................................... 26 3.1.1. TensorFlow .................................................................................................. 26 3.1.2. Label Studio ................................................................................................. 27 3.1.3. OpenCV ....................................................................................................... 28 1 1. INTRODUCTION With the technological advances registered in recent years, it can be acknowledged that we are currently in an era where data is being produced at an unprecedented rate, compelling businesses to rely on automated methods for data analysis. Retrieving useful insights from this amount of data is crucial, so involuntarily companies in this situation notice that it is mandatory to develop advanced algorithms that can summarize, classify, extract important information, and convert them into an understandable form (V. Y., Mariano et al., 2002). To address this issue, there has been a huge increase in the usage of Artificial Intelligence (AI) algorithms to guide business decisions. Machine learning (ML) models and Artificial Neural Networks (ANN), in particular, have demonstrated outstanding performance in resolving complex challenges across a wide range of industries, effectively revolutionizing the way companies approach problemsolving (A. Zulkhaizar, 2023). For example, in computer vision tasks like object detection and semantic segmentation, deep learning models have been successfully used in applications such as autonomous driving. This technology is rapidly advancing, bringing systems closer to possessing a level of intelligence comparable to humans in certain situations. According to the current Nvidia CEO, Jensen Huang, “Deep Learning can train a car to drive, and ultimately perform far better, and more safely, than any human driver could do behind the wheel.”. This was the goal of Huang’s company when developing hardware for the upcoming autonomous cars (J. Huang, 2017). Figure 1 - Usage of Deep Learning models in autonomous cars 1 In the example above, object detection models offer a solution for identifying relevant items in the road that allow the vehicle to drive safely. This ability renders them highly efficient for activities such as perception, decision-making, and vehicle control. Nevertheless, their usefulness extends beyond this use case scenario, as they have the capability to analyze and retrieve information from a given frame. As another example, throughout this report, we’ll highlight the experience of a Junior Machine Learning Engineer responsible for a project that led to the improvement of Biometrid’s machine learning infrastructure behind its OCR solution for information retrieval for Portuguese identification 1 Source: https://www.cbinsights.com/research/startups-drive-auto-industry-disruption/ 2 cards. The responsibilities regarding the collection, processing, and analysis of information will be described in detail. We’ll start by introducing the problem addressed and clarify the challenges faced, regarding the development of an object detection model capable of recognizing relevant sections from the Portuguese identification cards. Next, we’ll do a concise explanation of how the company is composed alongside its objective, before delving into more specific and technical aspects regarding the theory behind the project. Finally, this report will end up by clearly exposing all the practical implementations of the project alongside the final results. 1.1. COMPANY OVERVIEW Figure 2 - Biometrid's Logo 2 Created in 2015 under the name Polygon, the current Biometrid emerged as an IT company with headquarters established in Porto that promised to revolutionize the way we communicate with digital systems. At a time when with one click it is possible to open a bank account, register on a social network or even subscribe to a service it is no surprise that the digital footprint of all internet users has been growing exponentially. With that in mind, Biometrid is committed to delivering a range of tools that facilitate the onboarding, authentication, and validation of personnel in companies of all sizes. Figure 3 - Biometrid's Milestones Biometrid offers a range of solutions to simplify the Know Your Customer (KYC) processes. The company's flagship product, which shares the same name, streamlines these time-consuming activities, which are essential to safeguard financial institutions against fraud, corruption, money laundering, and terrorism financing. 2 Source: https://biometrid.com/ 3 Compared to its main competitors, Biometrid's product takes a unique approach. It uses a Drag&Drop methodology, which provides customers with autonomy and flexibility to build personalized verification processes. The product enables users to open bank accounts remotely, verify Proof-of-Life using personal documents, and generate digital signatures for public services. The company has established partnerships with banking institutions, insurance companies, and Portuguese Government departments. It has also expanded its operations to international markets, including Poland, Hungary, Colombia, Angola, and Mozambique. Biometrid's goal is to continue expanding its services and reach into new sectors and regions worldwide. For the ML team the main responsibility is to create and maintain all the ML models that support its solutions, especially the Optical Character Recognition (OCR) production pipeline for retrieving information from identification cards. The focus is divided into two: on one side improving the OCR pipeline, which would receive images of ID cards or passports, and from there extract information that could identify users in the future. On the other side, researching and developing new ML tools for the OCR infrastructure. 1.2. PROBLEM DEFINITION As mentioned before, systems equipped with artificial intelligence algorithms are now more present than ever in our daily lives. This paradigm shift means that processes that required a lot of manual work are now being replaced by models that simulate human behavior. One of the several examples where this change is noticeable is in the registration process. In the past, regardless of the industry, to perform the onboarding of a new client this one needed to fill out a form with his personal information manually and wait for the responsible staff to transfer the information into a dedicated database. This implied a rather lengthy process with several dedicated parts and a complex infrastructure. Luckily, to streamline the process, a new method has emerged for extracting this information without requiring manual entry from either the customer or staff (M. Ryan, & N. Hanafiah., 2015). A new system using optical character recognition (OCR) has been proposed to extract customer information from identification cards instead of manual data entry. This system, in the first instance, is powered by an object detection model responsible for processing an ID card image and retrieving the coordinates of the sections related to personal data as the result. These image coordinates are then used to crop the original image and feed those outputs into an OCR application that recognizes the text in the picture and converts it into machine-readable and editable text. 4 1.2.1. Case Study This chapter will examine the application of the selected approach in the Biometrid OCR pipeline to automate the process of retrieving personal information from Portuguese ID cards. By leveraging cutting-edge optical character recognition technology, the pipeline aims to streamline the data input process and provide accurate and efficient results. This subsection will delve into the details of this strategy and its impact on the process of retrieving personal information from ID cards. The growth of members of the ML team led to a new project which has the objective of improving the way the OCR data pipeline analyses images. Currently, the extraction process contains several layers of pre-processing: 1. The documents are exposed to a rotation model that orients them horizontally in an automatic way. 2. Next, this resulting image will serve as input for a segmentation model, which aims to remove all surrounding elements from the photo and generate cropped images. 3. These images are then converted from an RGB Format to Grayscale to improve the performance of the binarization that will be applied to the image lately. 4. After multiple morphological image transformations, the coordinates from the regions of interest were detected by multiple traditional image processing techniques that use relative coordinates to capture informational sections. 5. The process ends just when all of the proposed areas are analyzed by an OCR engine. This strategy presents itself as a very good alternative compared to a full-manual process, however, it’s in many ways limited as its results are only viable in favorable conditions where the document has a capture angle and favorable light conditions. As a company that consistently embraces new technologies, Biometrid extends this philosophy to every aspect of its product. So, the main goal of this project is to improve the OCR Pipeline by creating an artificial neural network capable of detecting all sections of the front of the Portuguese identification card. This way we hope to enhance the general performance of the OCR processes and establish a strategy that delivers favorable outcomes in all image scenarios. 1.2.2. Constraints and Limitations In the realm of camera-based analysis of text and documents, there exist several challenges associated with capturing images, including low resolution, uneven lighting, distorted perspectives, non-planar surfaces, wide-angle lens distortion, cluttered backgrounds, difficulties with zooming and focusing (M. Ryan, & N. Hanafiah., 2015). Throughout the report, we will explain all the strategies and techniques that we will apply to solve some of those problems. Besides that, we also find some constraints related to the dataset containing images of Portuguese Identification Cards. This is not publicly available due to GDPR restrictions, but fortunately, Biometrid had already obtained this type of data through a partnership with the “Agência para a Modernização Administrativa” (AMA) and regularly utilized it for other projects. So, even with limited data we still 5 manage to organize and curate approximately 3000 of these images to construct a consistent dataset capable of successfully training the model. Important to mention that these images contain personal information, and their public share is expressly forbidden. 1.2.3. Proposed Solution To address the case study, always with the limitations and constraints in consideration, it was decided by the team that the best strategy to improve the detection of the sections of the front face of the Portuguese identification card would go through the training of a deep neural network capable of improving the previous results and address situations where the image quality is not favorable. Previous studies suggest that various methods have been employed to tackle this issue. One commonly employed approach involves identifying saliencies in the image to locate documents inside a photo or video frame, without any prior knowledge about the document (F. Attivissimo et al., 2019). However, this strategy still presents some limitations mainly when the image contains noise, or the angle of capture is not favorable. The improved solution for the Biometrid OCR that will be presented throughout this report presents itself as a more advanced approach to this problem. It starts by using a detection model to locate the document, then crops the image to isolate the document from the background. After proper segmentation, the document is classified using a deep learning model. Throughout this document, we aim to enhance the average success rate of detecting relevant elements in identification cards, compared to the results that were achieved in the past. The models tested in the development of this solution will be thoroughly evaluated and compared to the current production models. Through this comparison, we can gain a better understanding of the progress made in our development and its potential for future advancements. Also, in the evaluation phase, we will focus on evaluating the inference latency since we believe that this will be of utmost importance. The duration between capturing an image and producing a result has a significant impact on delivering a smooth and seamless experience for our consumers and is therefore a top priority for the company. Figure 4 - Expected result 6 2. THEORETICAL FRAMEWORK This chapter will provide a comprehensive overview of the technical knowledge that underpins the project recently completed by the Machine Learning team at Biometrid. In Section 2.1, a comprehensive overview of Machine Learning will be presented. In Section 2.2, we will clarify the theoretical topics surrounding artificial neural networks, with a particular focus on convolutional neural networks (CNNs). In Section 2.3, we'll delve further into artificial neural networks by explaining the concept of Deep Learning. In Section 2.4, we will provide an overview of the various object detection model architectures that were tested over the past few months. In Section 2.5, we will discuss the evaluation stage of the project by presenting various metrics used to evaluate the performance of object detection models. Finally, in Section 2.6 of this report, we will provide an in-depth explanation of Optical Character Recognition (OCR) technology. This section will be crucial to understand the final phase of the project as it will cover the theory and technical aspects behind OCR. 2.1. MACHINE LEARNING Machine Learning (ML) is one of the subject fields of artificial intelligence that makes use of statistical models so that, with the help of data, it generates reliable predictions. Systems that offer these capabilities offer solutions to previous common limitations, examples comprehend a huge space of possibilities from correctly identifying spam emails to image/video recognition (P. Ariwala, 2022). This makes it possible to find hidden insights and identify complex patterns without explicit programming, not just because of the ML development but also due to an increase in computational power registered in recent years (C. Janiesch et al., 2021). According to a report by McKinsey, machine learning can create a potential economic impact of $2 trillion to $10 trillion per year across industries (J. Bughin et al., 2017) and is expected to grow at a compound annual growth rate of 38.8% from 2022 through 2029 and reach a value of $210 billion by the end of 2029. One of the key factors fueling this expansion is the growing acceptance of machine learning by major technology companies such as Apple, Microsoft, and many others across a wide range of industries, including healthcare, manufacturing, automotive, retail, advertising, automation, defense, financial services, and others (O. Farooq, 2022). 7 Figure 5 - Machine Learning investments by category 3 Compared to conventional or classical programming, where systems were fed by input data, and a function with predefined rules, which generates results according to them. An intelligent mechanism, that is, a system equipped with an ML model, presents itself as an alternative to the conventional engineering approach which receives the same data, but unlike the previous one, it also receives the expected outputs and thus creates a mathematical model with parameters adjusted to the problem. (O. Simeone, 2018) Figure 6 - Traditional Programming against Machine Learning approach 4 The idea behind the development of any machine learning algorithm is the presence of a large number of data that present a considerable level of quality. An organized collection of data is denominated by dataset and usually present a group of features in a tabular format. These datasets 3 Adapted from: https://www.statista.com/chart/17966/worldwide-artificial-intelligence-funding/ 4 Adapted from: Moroney, L. (2020). AI and Machine Learning for coders. O'Reilly Media. 8 can be used to train machine learning models for tasks such as classification, regression, clustering, and others. On the other hand, image datasets contain information in the form of images, which are twodimensional arrays of pixel values. These datasets are used to train machine learning models for tasks such as image classification, object detection, semantic segmentation, and others. Image datasets can be much larger in size compared to other types of datasets, as they often contain hundreds of thousands of images, each with multiple channels (e.g., red, green, and blue) and high resolution. To evaluate the performance of a machine learning model, the data are usually divided into three groups: training, testing, and validation. Only in this way, it is possible to have a perception of the behavior of the model with data never processed in the training phase. The first group has the biggest amount of data, typically between sixty to eighty percent, and is used to train the model. The validation set is used as an evaluation at the end of each epoch to evaluate the model during training and help optimize its parameters and settings. Finally, the test set is presented as a way to evaluate the model with different data from those presented in the previous sets and have a final evaluation of the results. Figure 7 - Train, Validation & Test Split 5 However, to conclude this chapter is worth mentioning that, despite the potential benefits in the industry, ML implementations have also challenges that need to be addressed. Being one of the most important examples to highlight the interpretation of accuracy. In most cases, a model that presents a high accuracy is considered a good one, and the opposite can lead to harm. For example where facial recognition systems are used in law enforcement. But highly accurate facial recognition systems can also pose risks to privacy and indicate the presence of mass surveillance (J. Fletcher, & A. Kostiainen., 2022). Another important topic related to accuracy and the ability of AI to perform correct predictions is its usage in areas that don’t have an objective ground truth and need external human judgment. The impact of an incorrect output depends on the context. For instance, predicting false occurrences of cancer can increase costs, but on the other hand, failing to predict a true result can have a much more impact on people’s life and delay the treatment. Another common example of this is using ML in a judicial context, false positives may send innocents to jail, while false negatives may make it harder to convict criminals. (J. Fletcher, & A. Kostiainen., 2022). 5 Adapted from: https://community.alteryx.com/t5/Data-Science/Holdouts-and-Cross-Validation-Why-the-Data-Used-to- Evaluate-your/ba-p/448982 9 Overall, is important to note that ML technologies are rapidly shaping a new future for the industry’s panorama. Companies embracing this type of AI have the potential to gain a competitive edge and improve their bottom line. However, it is important for companies to understand the challenges and limitations of machine learning, and to invest in the necessary expertise and resources to ensure the success of their machine learning initiatives. 2.1.1. Supervised Learning Based on a given problem and the available data, different types of Machine Learning algorithms can be used, each with its advantages and disadvantages. The first step is to understand which strategy to use to analyze the data. This data has great relevance in the results and can be classified as labeled data, that is, data that have one or more classes and allow their grouping or unlabeled data. In this project, we will focus on the first type of data which is characterized as data that contains input and output features. For a full understanding of this project is crucial to understand the theoretical aspects of supervised learning. This type of machine learning model receives input data (x) and output data (y). The goal is to discover the parameters of a function that will generate the best predictions when faced with information that has never been processed before. This is an algorithm that needs to receive labeled data, acquire a deep knowledge of them based on its parameters, and create a cause-effect relationship. We can divide the application of this type of machine learning into two categories, classification, and regression. In the case of classification, the objective is to predict a categorical result for each of the data, based on its independent variables. In regression problems, the expected output value is of the continuous type. 2.2. ARTIFICIAL NEURAL NETWORKS & CNNS Artificial Neural Networks (ANN) are statistical models that are directly inspired by the structure and function of the neurons in the brain. The fundamental units of neural networks are also referred to as neurons, nodes, or artificial neurons. A group of connected neurons creates networks that are trained to perform a variety of tasks, such as recognizing patterns in data, making predictions, or making decisions. This can be achieved by adjusting the weights of the connections between the nodes based on example inputs and their corresponding outputs (K. O'Shea, & R. Nash., 2015). An ANN is modeled by overlaying several layers of artificial neurons, or computational units, to receive inputs and then transfer them onto the next layer. The basic architecture consists of a network that has three types of neuron layers: input, hidden, and output layers (A. Abraham, 2005). However, there are some configuration variants, depending on the outputs and the data processing approach. Some common types of neural networks are Feedforward Neural Networks (FNN), Convolution Neural Networks (CNN), and Recurrent Neural Networks (RNN). However, throughout this report, we’ll just focus on CNNs since this type will be the only one that will be used to address our problem. Convolutional Neural Networks (CNN), which are also called “ConvNets”, is a type of ANN that, like the others, consists in neurons that learn through self-optimization. The main difference between this architecture and traditional ANN architecture is that this one is designed to deal with visual data. 10 CNN process images or videos and extracts relevant features directly from each pixel value without requiring any hand-engineered features or previous knowledge about the world. Figure 8 - Convolution Neural Network Architecture 6 To understand CNNs is important to know how its architecture is composed and what the types of layers that take part of it are. This type of ANN includes several building blocks, such as convolution layers, pooling layers, and fully connected layers. A common structure consists of repetitions of several convolution layers and a pooling layer, followed by one or more fully connected layers. 2.2.1. Convolution Layers A Convolution Layer is a fundamental component of the CNN architecture that performs feature extraction, which typically consists of a combination of linear and nonlinear operations. The first type of linear operation is convolution. This operation involves sliding a small matrix of weights (called a kernel or filter) over the input data (or input tensor) and computing an elementwise product of the weights and the values in the input volume at each position. The result for each pixel is then summed to obtain an output array called a feature map. This procedure is repeated by applying multiple kernels to form an arbitrary number of feature maps that extract different features from the input tensors (R. Yamashita et al., 2018). Two key hyperparameters that define the convolution operation are size (I x J) and the number of kernels (K). The size is typically 3 × 3, but sometimes 5 × 5 or 7 × 7. The number of kernels that are stacked on top of each other will set the depth of the feature maps and the complexity of the detection. 6 Source: Horak, K., & Sablatnig, R. (2019, August). Deep learning concepts and datasets for image recognition: overview 2019. In Eleventh international conference on digital image processing (ICDIP 2019) (Vol. 11179, pp. 484-491). SPIE. 17 At each sliding-window location, several proposals are predicted, and knowing that the regressor has 4*k coordinate outputs and the classification layer generates 2*k binary results the authors introduce the definition of “anchors” to define the central point of each sliding window. For any image, scale, and aspect ratio play a decisive role as important parameters to calculate the number of anchors (k). The developers chose 3 scales and 3 aspect-ratio as default parameters meaning that the maximum number of proposals per pixel is equal to 9, concluding that for the whole image, k = W*H*9. According to the original paper, the loss function of the RPN is minimized by the binary class label (of being an object or not) of each anchor. To assign a positive label to an anchor this one has to have the highest Intersection-over-Union (IoU) overlap with a ground-truth box or has to have an IoU overlap higher than 0.7 (S. Ren et al., 2015). 2.4.3. Single Shot MultiBox Detector (SSD) To address the high computational problems caused by the Faster R-CNN, other object detection systems, proposed different techniques that reduce the inference time while maintaining the same level of accuracy. So, by the end of 2016, C. Szegedy presented a paper on the implementation of Single Shot MultiBox Detector (SSD) reaching immediate breakthrough records in terms of performance and precision for object detection tasks compared to the previous models. This model approach is based on a feed-forward convolutional network that produces a fixed number of bounding boxes and creates a scoring mechanism that evaluates the presence of objects in those boxes. The architecture of the SSD uses VGG-16 architecture as its base network inheriting in this way its strong performance in high-quality image classification tasks. From there, the main difference stands in the removal of the fully connected layers by a set of convolutional layers that decrease in size progressively and enable predictions at multiple scales. These layers are then followed by a non-maximum suppression step to produce the final detections. Figure 15 - SSD Architecture 12 The SSD Model works as follows, the base network processes an input image that is divided into grids of various sizes, and, for each grid, detection is performed for different classes and different aspect ratios. After that, each of these grids is evaluated by a score that says how well the detected object fits in that particular grid. The non-maximum suppression step is as stated before, responsible for choosing the best final detection from the set of overlapping detections (W. Liu et al., 2016). 12 Source: Liu, W., Anguelov, D., Erhan, D., Szegedy, C., Reed, S., Fu, C. Y., & Berg, A. C. (2016). Ssd: Single shot multibox detector. In Computer Vision–ECCV 2016: 14th European Conference, Amsterdam, The Netherlands, October 11–14, 2016, Proceedings, Part I 14 (pp. 21-37). Springer International Publishing. 18 Figure 16 - SSD Framework 13 In the year of its launch, the SSD model registered better results than the previous state-of-the-art detection algorithms, but in recent years, new variants of YOLO architecture and SSD keep competing for the award of best object detection model in the PASCAL VOC 2007 Challenge. 2.4.4. CenterNet To reduce the steps performed by two-stage object detection architectures, like R-CNN or Faster R- CNN models, and to deal with the limitations of anchor-based models, CenterNet architecture was proposed in 2019 as an anchorless object detection algorithm that proves to be an effective lightweight option (K. Duan et al., 2019). Taking as the baseline the CornerNet architecture, CenterNet is a one-stage detector that aims to improve to performance of its predecessor by using a triplet of keypoints, rather than a pair. This architecture reduces the analysis cost by only paying attention to the central information using a keypoint detection process. In the given figure, the model represents each object using a center keypoint and a pair of corners. To generate a heatmap, CenterNet uses CNNs as a model backbone to generate bounding boxes, then count the number of bounding boxes that contain the center keypoint and uses this information to predict the likelihood of a central region in the image containing the same class of center keypoints. Each pixel in the heatmap represents the probability of an object center being present at the corresponding spatial location in the image. A high probability score indicates a high likelihood of an object center being present at that location, while a low probability score indicates a low likelihood of an object center is present. This approach of predicting the likelihood of object centers using a heatmap can improve the accuracy of object detection, particularly for small or occluded objects. 13 Source: Liu, W., Anguelov, D., Erhan, D., Szegedy, C., Reed, S., Fu, C. Y., & Berg, A. C. (2016). Ssd: Single shot multibox detector. In Computer Vision–ECCV 2016: 14th European Conference, Amsterdam, The Netherlands, October 11–14, 2016, Proceedings, Part I 14 (pp. 21-37). Springer International Publishing. 19 Figure 17 - CenterNet Architecture 14 The authors presented an architecture that employs two key strategies to predict the geometric centers and corners of objects. The first strategy is called Center Pooling and starts by predicting the center keypoint by finding the maximum value in both horizontal and vertical directions and adding these two values together. This helps to obtain more recognizable visual patterns within objects, making it easier to perceive the central part of the proposal. The second strategy is denominated Cascade Corner Pooling, which aims to find the corner points similarly to the previous one, but now by obtaining the maximum summed response in both the boundary and internal directions of objects on a feature map for corner prediction. Empirically, the authors claim that the results are more stable and robust to feature-level noises, leading to improved precision and recall. In summary, the CenterNet model is a state-of-the-art object detection architecture that achieves high accuracy with low computational costs. The model predicts object centers directly using a heatmap, which reduces the complexity of the model and improves detection accuracy for small and occluded objects. The model has achieved state-of-the-art results on several benchmark datasets and is widely used in both research and industry for various computer vision applications. 2.5. EVALUATION METRICS Evaluation metrics play a crucial role in the development and deployment of machine learning models. Building a machine learning model can be seen as a recursive pipeline where the responsible team trains a model, then evaluate it using evaluation metrics, finetune specific model hyperparameters, and repeat this procedure until the desired performance is achieved. So, it is extremely important to carefully choose and track the right evaluation metrics to ensure that the model is performing well, to perform a model comparison, and to meet the desired objectives. In this chapter, we will discuss the theoretical background of the evaluation metrics used throughout the project and explore how to choose and interpret these metrics in a production environment. We will also discuss the importance of considering the specific characteristics and goals of the task when selecting an evaluation metric, and the role of evaluation metrics in model selection, optimization, and monitoring. 14 Source: Duan, K., Bai, S., Xie, L., Qi, H., Huang, Q., & Tian, Q. (2019). Centernet: Keypoint triplets for object detection. In Proceedings of the IEEE/CVF international conference on computer vision (pp. 6569-6578). 20 Since we are dealing with an object detection algorithm, is expected to evaluate the model by comparing its output with ground-truth bounding boxes generated by a human operator responsible for manually labeling the objects and defining their boundaries (V. Y. Mariano et al., 2002). From this analysis, it’s common to use evaluation metrics like accuracy, precision, recall, and many others to understand how well the model can distinguish between different class labels and the trade-offs between false positive and false negative predictions. Since 2010 challenges like VOC PASCAL Challenge, COCO, ImageNet Object Detection Challenge, and Google Open Images Challenge have emerged as competitions that aim to evaluate new implementations and are now seen as valuable benchmarks to test object detection models in specific scenarios by using real-world annotated datasets (M. Everingham et al., 2009). These competitions contribute to the definition of standard evaluation procedures within the scientific community by using popular metrics like Average Precision (AP), Intersection over Union (IoU), or creating their variants to rank the models. In the next sections, we’ll try to clarify the metrics previously mentioned in a simplified and organized strategy where the reader is guided by a sequential process illustrated in the figure below. It should be noted that each step can be considered as a standalone method of evaluation, but they are interdependent and build upon one another. Figure 18 - Object Detection Evaluation Process 2.5.1. Confusion Matrix This table comes up as a useful tool for an initial understanding of the types of errors made by a model and for comparing the performance of different models. It’s constructed by comparing the predicted class labels with the true class labels of the data. 21 True Class Predicted Class Positive Negative Positive TP FP Negative FN TN Table 1 - Confusion Matrix 15 Looking at the table above, a confusion matrix will be composed by four main areas that help to understand the strengths and weaknesses of a model and for identifying areas for improvement. More precisely, each prediction can be classified as: • True positive (TP) if the prediction contains a correct detection of a ground-truth bounding box. • False positive (FP) if the algorithm performs an incorrect detection of a nonexistent object or a misplaced detection of an existing object. • False negative (FN) if the ground-truth object is not detected. Bear in mind that, within the realm of object detection, there is no such thing as a False Positive (FP) as there are an infinite number of bounding boxes that should not be identified within a given image. 2.5.2. Intersection over Union (IoU) Based on the Jaccard Index, this metric individually evaluates the overlap between a pre-annotated ground truth bounding box (gt) and the one predicted by the model (pd) having in consideration a specific threshold value. IoU score ranges between 0 and 1 where the closer the two boxes the higher the score, meaning that detection output with maximum IoU value is considered to have a perfect overlap with the ground truth bounding box. Figure 19 - Formula and Representation of the IoU calculation 16 15 Adapted from: Jeppesen, J. H., Jacobsen, R. H., Inceoglu, F., & Toftegaard, T. S. (2019). A cloud detection algorithm for satelliteimagery based on deep learning. Remote sensing of environment, 229, 247-259. 16 Adapted from: Padilla, R., Netto, S. L., & Da Silva, E. A. (2020, July). A survey on performance metrics for object-detection algorithms. In 2020 international conference on systems, signals and image processing (IWSSIP) (pp. 237-242). IEEE. 22 By computing the IoU score for each detection, it’s important to define a threshold (a) to convert real-valued scores into classifications. 2.5.3. Precision and Recall This performance benchmark act as a measure of how closely a predicted value agrees with the true value of a quantity. It is defined as the ratio of the number of correctly predicted positive cases (positive predictions containing an IoU greater than the threshold) to the total number of predicted positive cases (correctly identified objects + false positive predictions). In other words, it is a measure of the proportion of positive cases that are actually positive. Figure 20 - Precision Formula Precision is often used in conjunction with another metric called Recall (or Sensivity) to evaluate the performance of a model. Precision is typically more relevant when the goal is to limit the number of false positive predictions, whereas recall is more relevant when the goal is to identify as many positive cases as possible. This way we can define Recall as the metric that measures the ratio of the number of correctly predicted positive cases to the total number of actual positive cases. In other words, it is a measure of the proportion of actual positive cases that are correctly identified by the model. Figure 21 - Recall Formula Important to mention that, in the presence of imbalanced datasets, where one class is rare, it’s important to focus on the recall of the model. 2.5.4. F1-Score: This is the harmonic mean of precision and recall, with a higher score indicating a better balance between the two. The F1 score is defined as: Figure 22 - F1-Score Formula The F1 score is often used in imbalanced classification tasks, where it is important to achieve a balance between precision and recall. It is also useful when the cost of false positive and false negative predictions is not the same, as it allows for the weighting of these costs to be incorporated into the evaluation metric. 2.5.5. Average Precision In object detection algorithms, it is essential to strike a balance between precision and recall. The traditional evaluation metric, which is the F1 score, can only provide a single score for a given 23 threshold, making it less informative in situations where the threshold varies. To address this issue, the Average Precision (AP) metric was introduced, which has become a widely used evaluation metric for object detection algorithms. AP considers the number of true positives, false positives, and false negatives, making it particularly useful when the data is imbalanced. By computing the area under the precision-recall curve (AUC), AP provides a comprehensive summary of the trade-off between precision and recall across different thresholds, thus providing a more informative evaluation metric for object detection algorithms. To calculate the AP, the precision-recall curve is first computed by varying the threshold values and plotting the precision on the y-axis and recall on the x-axis. The AUC is then computed, which ranges from 0 to 1, with higher values indicating better performance. AP provides a more precise evaluation metric compared to traditional metrics, making it a valuable tool for object detection algorithms. As such, it has become a standard metric used in many object detection benchmarks and competitions. 2.5.6. Mean Average Precision (mAP) Multiclass Object Detection models face the challenge of detecting multiple object classes in an image. As a result, a metric called Mean Average Precision (mAP) was developed as an extension of the AP metric to calculate the average precision for each class. mAP calculates the AP for each class in the dataset and then averages the AP values for all the classes to obtain the final mAP score. The resulting value ranges from 0 to 1, with 1 indicating the best possible performance. mAP is a useful metric as it provides an overall view of the model's performance and helps to identify which classes the model is performing well on and which classes it is struggling with, providing insight into where the model needs improvement. The simplicity of mAP has made it an essential benchmark for evaluating the performance of object detection models in competitions and challenges. The mAP allows for easy comparison of different models and provides a fair evaluation metric for all models, regardless of the number of classes in the dataset. This makes it an effective tool for researchers and developers to assess the performance of their models and identify areas for improvement. 2.6. OPTICAL CHARACTER RECOGNITION (OCR) Optical Character Recognition (OCR) is a technology that provides the capacity of converting handwritten, typewritten, or printed text into machine-readable images. This offers numerous applications that can be used to improve workflow efficiency. Common examples are industries like legal, banking, and healthcare that are currently leveraging OCR technology to simplify their operations and streamline their processes (A. Singh, K. Bacchuwar, & A. Bhasin., 2012). Unlike humans, machines do not have the capability to recognize text or characters easily from an image, which is why significant research efforts have been put into developing OCR techniques. OCR is a complex problem due to the numerous languages, fonts, and styles in which text can be written, as well as the complex rules of languages. As a result, OCR requires the integration of various computer science disciplines, such as image processing, pattern classification, and natural language processing, to overcome these challenges (N. Islam, Z. Islam, & N. Noor., 2017). The process of OCR involves a series of distinct phases. The first one, denominated by image acquisition, entails obtaining an image from an external source such as a camera or scanner, and 24 transforming it into a format that is compatible with computer processing. This is a crucial step in the OCR process as it sets the foundation for accurate and efficient optical character recognition. Once the image has been acquired, the subsequent step in the OCR process is known as preprocessing. During this phase, a variety of techniques can be utilized to enhance the quality of the image. These techniques may involve removing noise, setting thresholds, and extracting the baseline of the image. By improving the image quality, the OCR algorithm can achieve a higher level of accuracy when it comes to recognizing the text or characters contained within the image. This phase is critical to ensuring the overall effectiveness of the OCR process. Moving to the next phase, the next step in the OCR process will focus on character segmentation. The goal of this phase is to isolate individual characters within the image so that they can be properly identified by the recognition engine. While simple techniques such as connected component analysis and projection profiles may be sufficient in certain cases, more advanced segmentation techniques are necessary for complex situations where characters may be overlapping, broken, or obscured by noise within the image. By effectively separating the characters, the OCR system can accurately recognize the text and produce an output that is faithful to the original document. The segmented characters are then processed to extract different features. Based on these features, the characters are recognized. Different types of features that can be used extracted from images are moments etc. The extracted features should be efficiently computable, minimize intra-class variations, and maximizes inter-class variations. The segmented characters are then processed in order to extract different features that will be used for character recognition. Based on these features, the characters are recognized. The features extracted from the characters should be efficiently computable and should minimize intra-class variations (variations within the same class of characters) while maximizing inter-class variations (variations between different classes of characters). Various types of features can be extracted from the characters, such as moments and other image-based features. After that, the features of segmented images are assigned to different categories or classes using different types of character classification techniques. Finally, post-processing techniques can be performed to improve the accuracy of OCR systems. These techniques utilize natural language processing, and geometric and linguistic context to correct errors in OCR results. 25 Figure 23 – General OCR Workflow 17 Over the years, OCR technology has undergone tremendous improvements, and modern systems can now recognize various fonts, sizes, and styles of text. Despite this, the accuracy of OCR systems still depends on factors such as image quality, text complexity, and language. Fortunately, advancements in artificial intelligence and machine learning have resulted in substantial improvements in OCR accuracy, leading to more reliable and precise results (A. Ranjan, V.N.J. Behera, & M. Reza., 2021). Nowadays, there are numerous OCR tools available that have made their usage more common in different environments. Some of the most popular OCR tools include Tesseract, developed by Google, Microsoft Cognitive Services by Microsoft, and Amazon Textract. For our project, we have decided to utilize the Pytesseract Python library, which provides an easy-to-use interface to leverage all the features and capabilities of Tesseract. The Pytesseract library offers a straightforward and efficient way of integrating OCR functionality into Python-based applications, making it a great choice for our project needs. 17 Adapted from: Mudiarta, I. M. D. R., Atmaja, I. M. D. S., Suharsana, I. K., Antara, I. W. G. S., Bharaditya, I. W. P., Suandirat, G. A., & Indrawan, G. (2020, April). Balinese character recognition on mobile application based on tesseract open-source OCR engine. In Journal of Physics: Conference Series (Vol. 1516, No. 1, p. 012017). IOP Publishing. 26 3. METHODOLOGY 3.1. TOOLS AND TECHNOLOGIES In this chapter, all the tools and technologies used throughout this project will be presented. We will explore the reasons for their selection, enumerate alternatives available in the market, and understand the importance of these tools and technologies for the success of the project. The chapter will cover the various libraries, frameworks, and platforms that have been employed to facilitate the process of building an object detection model, from data preparation to model training and deployment. By the end of this chapter, readers will have a comprehensive understanding of the tools and technologies used in the project, and how they contribute to the overall objective of the project. 3.1.1. TensorFlow TensorFlow (TF) is a powerful open-source software library for machine learning and deep learning, developed by researchers and engineers working on the Google Brain Team. At its core, TF uses data flow graphs to represent any computation. A data flow graph is a directed acyclic graph (DAG) where the edges represent the flow of data, and the nodes represent operations. This makes it easy to implement machine learning algorithms, such as neural networks (M. Abadi et al., 2016). TensorFlow also provides a wide range of tools for building, training, and deploying machine learning models using a variety of platforms including CPUs, GPUs, and TPUs. However, the development team maintains a collection of pre-made models on a platform called TensorFlow Hub, which can be used for tasks like object detection, image classification, and text generation. For visualization purposes, TensorFlow has a visualization tool called TensorBoard, which allows developers to easily visualize and understand the behavior of their models during training, evaluation, and inference. Figure 24 - TensorBoard Interface 18 The main alternative to TensorFlow is PyTorch. This python library was developed by Facebook and defines itself as an easier-to-use tool easy for tasks such as image classification, natural language 18 Source: https://www.tensorflow.org/tensorboard 33 of data for a new task is limited, as transfer learning reduces the need for extensive data collection and labeling. Luckily, TensorFlow offers a repository that contains several model architectures previously trained and accompanied by their evaluations when used in the COCO dataset. This way we started to research which ones met our needs seeking a model with consistent performance but at the same time not presenting a high inference time as this would negatively affect the processing time of the OCR pipeline. To organize the project and observe improvements over time, we opt to divide it into versions. Each version would present a different group of models alongside data modifications that we believed that made sense according to the outputs retained. In this way, it was possible to evolve our work while delivering reports to the Biometrid team at the end of each month. Below is displayed a table illustrating all the models tested per version. Models Observations Version 1 EfficientDet D1 SSD ResNet50 SSD ResNet101 SSD ResNet152 Version 2 SSD ResNet152 1024x1024 SSD ResNet50 v2 Improved version with different hyperparameters SSD ResNet101 v2 Improved version with different hyperparameters Version 3 Faster R-CNN Inception EfficientDet D2 CenterNet HourGlass104 Version 4 Faster R-CNN Inception v2 Improved version with different hyperparameters CenterNet Resnet50 CenterNet Resnet101 Table 2 - Model's architecture used per version. It's crucial to emphasize that the model’s key aspects have to be altered to adapt to the appropriate data format for our project. This involved modifying each model's configuration file to enhance the detection of objects based on the quantity and shape of the bounding boxes. 34 To measure the performance of our models, we focused on evaluating them using metrics explained previously such as mAP, Recall, and IoU. For this purpose, the evaluation metrics group was set to “coco_detection_metrics” in the eval_config parameter. Although the library provides other evaluation metrics, we found this to be the most appropriate for our project. The model training procedure was thoroughly documented, making it possible to initiate the first training iteration after inserting the data and label maps. This gave us a preliminary understanding of the model's capabilities. The training process was monitored by not only the console logs but also through the use of TensorBoard. This allowed for comprehensive tracking of the training evolution. 3.2.3. Model Fine-Tuning In the initial iteration of the models, we solely relied on the training and test data converted to TFRecords format without making any modifications to the model architecture. Nonetheless, we conducted research to identify the optimal parameters suited for our scenario. This led to the next phase of the solution's development known as finetuning the model, where during each training session, small modifications are made to the model's architecture to enhance its efficacy. In this section, the main objective is to discuss the various modifications that the team made to the model's configuration file to obtain the optimal architecture for our particular problem. The focus will be on the dataset composition, and a detailed overview will be provided for each of the themes contained within the configuration file. Throughout this process, we will explain the reasoning behind all the choices and provide insight into the various options that are available through this library. 3.2.3.1. Image Preprocessing In the context of any computer vision project, it is absolutely crucial to have a full understanding of the input data that is being fed into the model. Without this understanding, it is impossible to design and train a model that is truly effective at the task at hand. Deep learning algorithms that power this kind of project are heavily dependent on the input data, and even small variations or inconsistencies in the data can greatly impact the performance of the model. It is therefore essential to carefully preprocess the data, ensuring that it is in a format that is compatible with the model's architecture. Fortunately, the TFOD API provides a range of preprocessing tools that can be accessed right out of the box. In the initial section of the configuration file, users have the ability to exercise control over the image resizing process, including the shape of the resulting resized image. The library offers a considerable amount of flexibility concerning the various parameters that can be modified to achieve the desired results. However, it is important to note that before any modifications are applied, TensorFlow automatically handles the normalization of the images. This is an important feature that ensures consistency in the data and helps to optimize the performance of the model. When configuring the strategy chosen to process the input image for our model, the API offers two distinct options: "keep_aspect_ratio_resizer" and "fixed_shape_resizer". The former option allows users to specify a minimum size while maintaining the aspect ratio of the original image. However, it is important to note that this option can sometimes result in extensively padded images, especially in cases where the original image is rectangular. In such cases, it may be more suitable to use the "fixed_shape_resizer" option, which resizes the image to a specified rectangle size defined by the 35 "height" and "width" parameters. For our specific use case, we have determined that the "fixed_shape_resizer" option is the optimal choice, as it allows us to maintain consistency in the size of the input images, which is critical for optimizing the performance of the model. 3.2.3.2. Image Augmentation Image augmentation is an essential technique that can greatly enhance the accuracy and robustness of the model. By applying various transformations and manipulations to the input images, augmentation procedures can help to address issues such as overfitting, insufficient training data, and class imbalance. For example, flipping, rotating, and cropping images can increase the variability and diversity of the training data while adjusting brightness, contrast, and color can help to account for variations in lighting conditions. Additionally, image augmentation can also help to mitigate the effects of occlusions, viewpoint changes, and other real-world factors that may impact the model's ability to accurately detect objects in new and unseen images. Throughout the course of this project, we explored various of these methods to augment our dataset with synthetic images generated through the application of image manipulation techniques. Knowing that our images were accurately segmented and correctly oriented from the segmentation and rotation models, we made a deliberate effort to avoid modifying their orientation. Instead, we focused on applying techniques that could alter the color system of the data as you can check in the image below. This decision proved to be highly effective, as adjustments to factors such as hue, contrast, saturation, and brightness allowed us to minimize the model's sensitivity to color. As a result, the model was able to detect objects more accurately across a wider range of colors, leading to improved overall performance. The use of these techniques demonstrates the importance of careful and strategic data augmentation in the context of object detection and underscores the critical role that it plays in optimizing model performance. Figure 27 - Image Augmentation techniques used for the CenterNet configuration file While the techniques described above can be highly effective for augmenting image data in our context, it's worth noting that the TensorFlow Object Detection API offers a much broader range of augmentation options. As you can see in the image below, there are a wide variety of different 36 techniques that can be used to manipulate and enhance image data, ranging from simple color adjustments to more complex transformations like rotation, flipping, and distortion. By carefully considering the unique characteristics and requirements of your specific use case, you can leverage these powerful tools to create highly customized and effective data augmentation strategies that can significantly improve the accuracy and performance of your object detection models. Figure 28 - Image Augmentation techniques provided by Tensorflow Object Detection API 20 3.2.3.3. Post-processing Post-processing is another indispensable step in any object detection project, as it enables the model to generate accurate and meaningful results from the raw output of the detection algorithm. In the context of object detection, post-processing typically involves analyzing the output of the model and applying various techniques to refine and filter the results. By carefully tailoring these postprocessing techniques to the specific requirements of the project, it's possible to significantly improve the accuracy and precision of the object detection model, while also reducing the risk of false positives or other errors. As we are facing an anchorless architecture, our primary concern at this stage was preventing overfitting and improving model performance. To achieve this, we focused on advanced approaches to learning rate control over time. Learning rate plays a critical role in determining the rate at which the model's internal parameters and weights are updated during training. A carefully chosen learning rate can significantly impact the model's convergence and its ability to find the optimal set of parameters for the given task. As such, we employed various strategies to tune the learning rate, 20 Source: Tensorflow Model Garden Repository 37 including learning rate schedules and optimization algorithms. Through these techniques, we aimed to strike a balance between model convergence and generalization, ultimately leading to improved performance. In our case, we employed the cosine learning rate decay schedule for controlling the learning rate over time. This approach enables the learning rate value to alternate between increasing and decreasing throughout the training process. Specifically, the learning rate is gradually decreased towards zero as the training progresses, which helps the model converge toward an optimal solution while reducing the risk of overfitting. To correctly configure the learning rate schedule, it is important to focus on the following parameters and understand their impact of them on the performance of the model: • learning_rate_base: parameter that defines the initial learning rate that will be used to train your model. • total_steps: parameter that defines the number of total steps your model is going to train. Important to note that in the last steps of your training job, the learning rate scheduler will drive the learning rate value to be close to zero. • warmup_learning_rate: the maximum value that the learning rate will reach before starting to decrease. • warmup_steps: defines the number of steps that will be taken to increase the learning rate from learning_rate_base to warmup_learning_rate 3.2.4. Image Pipeline Once we had properly trained the model on our custom dataset and fine-tuned its parameters to enhance its performance, the subsequent phase involved comprehending the outcomes produced by the model. For every examined image, the model delivers numerous results, with the first ones being the labels assigned to each section. This is crucial for linking the section's name with the coordinates of the bounding boxes that will eventually be showcased. The bounding box coordinates generated by the model during image inference play a vital role in determining the location of the regions of interest. Utilizing these coordinates makes it feasible to isolate specific subsections of the images that only contain the desired information. In our scenario, we aim to extract sections of the image that exclusively contain personal data presented on the front face of the Portuguese identification card. To achieve this objective, we designed a data pipeline that involves conducting an image inference and subsequently utilizing the model's outcomes to crop the original image, leading to several subimages, each corresponding to a particular section. Our workflow deliberately involves minimal image manipulation techniques since the model is adept at processing horizontal segmented images and can accommodate color variations owing to the pre-applied image augmentation techniques. This represents one of the key benefits of our implementation over the current approach, as we can simply resize the image and feed it into the model, reducing the reliance on extensive image 38 processing that can lead to latency issues. As a result, our ML-powered solution operates independently of any time-consuming image processing, enhancing its overall efficiency. In the following paragraphs, we will discuss each function that constitutes our pipeline. Our pipeline was entirely coded in Python and created entirely by the Machine Learning team, which modified the existing functions to accommodate the changes introduced by the object detection algorithm. The initial function in our pipeline is called "detect_sectionsML" and only needs a parameter that refers to the image that will be analyzed. For the function to operate correctly, it must receive an image of a Portuguese identification card, which will be fed into our model to generate a prediction. Although the model generates several pieces of information, the function is designed to solely return the values corresponding to the bounding box coordinates and their respective classes/labels. Figure 29 – Python function used to make model inferences With a clear understanding of the preceding function's outcomes, we will now proceed to crop the original image utilizing the "crop_sections_ML" function, resulting in a list of images, with each element corresponding to a particular section. Figure 30 – Python function used to crop card sections by given coordinates Concluding our pipeline is the "extract_sections_data_ML" function, which plays a fundamental role in processing the images of each section. This function employs the Pytesseract library to convert images into text. However, as each section can display data in various formats, such as numbers and punctuation marks (as in the case of height) or solely letters (as in fields like first or last name), each 39 section requires a distinct Tesseract configuration. As a result, this function merges the multiple configurations with their respective sections and creates a Python dictionary to save the results. Figure 31 – Python function used to apply OCR in given sections 40 4. EXPERIMENTAL STUDY In this chapter, we will present the outcomes of our experimentation with various model architectures and determine the optimal one for deployment in a production setting. We will start by outlining the evaluation metrics used, and their relationship to the concepts introduced in chapter 2.5. Following that, we will end by providing a detailed analysis of the comparative performance of our best model against the existing production strategy. 4.1. EVALUATION PROTOCOL Throughout our object detection model training, TensorFlow generates real-time training process checkpoint log files which allow us to assess the performance of our models. These logs contain COCO evaluation metrics, which include essential metrics like mean average precision, recall, and Intersection over Union. These metrics aid us in quantifying the accuracy and precision of our models and enable us to identify areas that require improvement. By using COCO evaluation metrics, we can ensure that our models are optimized to detect and classify objects with high accuracy and efficiency, allowing us to achieve our research goals. As we have previously mentioned, we split our dataset into two parts - a training set and a test set. The test set plays a crucial role in evaluating the performance of our model, as it contains data that the model has never seen before. Important to understand that the evaluation process utilizes the checkpoint files generated during the training process to assess the model's ability to detect objects in the test dataset. The evaluation generates a set of metrics that provide a summary of the model's performance, enabling us to track its accuracy and precision over time. These metrics offer valuable insights into the strengths and weaknesses of our model, allowing us to fine-tune it for optimal performance. By regularly monitoring the evaluation metrics, we can ensure that our models are continuously improving and delivering reliable results (L. Vladimirov, 2020). All these results can also be visualized with the help of TensorBoard. This visualization tool converts the evaluation results obtained from the checkpoint files into intuitive and informative dashboards. These dashboards provide a comprehensive overview of the model's performance, enabling us to identify areas that require improvement. In addition to the evaluation metrics, TensorBoard also allows us to visualize the detection results in the test images, providing a clear understanding of how well the bounding boxes are detecting the areas of interest. This feature is particularly useful in identifying false positives or false negatives, which can be further investigated and corrected to improve the model's accuracy. By utilizing TensorBoard to analyze the evaluation results and visualize the detection outputs, we can gain a deeper understanding of our model's performance and make informed decisions on how to optimize it further. Once we establish that a model produces favorable outcomes, it becomes crucial to assess the latency it introduces while making an inference. This aspect holds immense significance since it can adversely impact the pipeline's performance if the response time increases significantly. Therefore, it is essential to carefully scrutinize the model's inference time to ensure that it meets the requirements of the intended application. Finally, upon analyzing the model's performance metrics over the test set, checking the bounding boxes display and the latency, the final evaluation phase now shifts focus to assessing the outputs 41 generated by the OCR engine. In light of this, the project team decided to build a web application using Streamlit to compare the results of our approach against the current production environment's output. The application provides an interface that you can check below, that allows us to browse through a folder of images depicting identification cards and manually check which sections Tesseract accurately converted to text using tick boxes. This evaluation phase is undoubtedly the most time-consuming since there is no record of all the ground truth values of the documents, and the performance of the OCR engine must be assessed by manually inspecting each section to determine if the output matches the expected values. Figure 32 - Streamlit Output Comparison App Upon evaluating both methods' results on our 3000-image dataset, the application generates a CSV file, which we use to produce a line plot that will be used to compare visually the two implementations. We will present this plot below when analyzing the results. The evaluation process for this project is comprehensively outlined, highlighting each distinct phase. The next chapter will provide a detailed overview of the outcomes obtained in each of these phases and explicate the rationale behind selecting the final model. 4.2. EXPERIMENTAL RESULTS AND DISCUSSION This chapter focuses on presenting the outcomes achieved with our artificial intelligence algorithm's implementation for detecting Portuguese ID card sections. We have divided the results into three phases, as discussed in the previous chapter, to assess our approach's effectiveness in different ways. 42 4.2.1. TensorBoard Results Throughout each phase presented in Table 2, we started checking the performance of each model via TensorBoard by analyzing its evaluation metrics on the train and test set. This approach allowed us to monitor the training progress of a specific model in real time and compare it to previously trained models. Our initial emphasis is on the evaluation metric known as loss, which is a value assigned during the training of a model that aims to reflect the disparity between the model's predicted output and the real output. The fundamental objective of the training process is to decrease the loss metric, indicating that the predicted output should closely resemble the actual output. Presented in the following table are the loss values of the most optimized versions for each of the trained models. It is evident that all the loss values are quite low, but the CenterNet Resnet101 model outperformed the rest, indicating that its predictions are the most accurate. This initial evaluation positions it as a strong contender for the final model, although we still need to analyze numerous other metrics to determine if it is the optimal choice. Model Loss value CenterNet HourGlass104 0.01957 EfficientDet1 0.02583 EfficientDet2 0.02957 Faster R-CNN Inception 0.01372 SSD ResNet101 0.04287 SSD ResNet50 0.0577 CenterNet Resnet50 0.01219 CenterNet Resnet101 0.0106 Table 3 - Loss Comparison Regarding the metrics of mean average precision and recall values, the results were found to be dissimilar. Among the evaluated model architectures, only three achieved values higher than 80% for mean average precision, namely CenterNet HourGlass104, Faster R-CNN Inception, and CenterNet Resnet50. These models also performed exceptionally well in terms of recall values. Thus, these same three models were considered the most effective ones for the given task. A comparative view of the recorded values for both these evaluation metrics is presented in the following table. 49 6. BIBLIOGRAPHY [1] Abadi, M., Barham, P., Chen, J., Chen, Z., Davis, A., Dean, J., ... & Zheng, X. (2016, November). Tensorflow: a system for large-scale machine learning. In Osdi (Vol. 16, No. 2016, pp. 265-283). [2] Abraham, A. (2005). Artificial neural networks. Handbook of measuring system design. [3] Alexandari, A. M., Shrikumar, A., & Kundaje, A. (2017). Separable fully connected layers improve deep learning models for genomics. BioRxiv, 146431. [4] Ariwala. (2022, October). 9 Real-World Problems that can be Solved by Machine Learning. Maruti Techlabs. https://marutitech.com/problems-solved-machine-learning/ [5] Attivissimo, F., Giaquinto, N., Scarpetta, M., & Spadavecchia, M. (2019, October). An automatic reader of identity documents. In 2019 IEEE International Conference on Systems, Man and Cybernetics (SMC) (pp. 3525-3530). IEEE. [6] Bhatt, D., Patel, C., Talsania, H., Patel, J., Vaghela, R., Pandya, S., ... & Ghayvat, H. (2021). CNN variants for computer vision: history, architecture, application, challenges and future scope. Electronics, 10(20), 2470. [7] Bughin, J., Hazan, E., Ramaswamy, S., Chui, M., Allas, T., Dahlstrom, P., ... & Trench, M. (2017). Artificial intelligence: The next digital frontier? [8] Duan, K., Bai, S., Xie, L., Qi, H., Huang, Q., & Tian, Q. (2019). Centernet: Keypoint triplets for object detection. In Proceedings of the IEEE/CVF international conference on computer vision (pp. 6569-6578). [9] Everingham, M., Van Gool, L., Williams, C. K., Winn, J., & Zisserman, A. (2009). The pascal visual object classes (voc) challenge. International journal of computer vision, 88, 303-308. [10] Farooq, O. (2022, October 3). [10 Best Machine Learning Stocks to Invest In]. Yahoo Finance. https://finance.yahoo.com/news/10-best-machine-learning-stocks-165306920.html [11] Fletcher, J., & Kostiainen, A. (2022, November). Ethical Principles for Web Machine Learning. W3C. https://www.w3.org/TR/webmachinelearning-ethics [12] Fritz Labs. (2018). Object Detection Guide. Fritz AI. https://www.fritz.ai/object-detection/ [13] Girshick, R., Donahue, J., Darrell, T., & Malik, J. (2014). Rich feature hierarchies for accurate object detection and semantic segmentation. In Proceedings of the IEEE conference on computer vision and pattern recognition (pp. 580-587). [14] Goodfellow, I., Bengio, Y., & Courville, A. (2016). Deep learning. MIT press. [15] H. Zhu, X. Yan, H. Tang, Y. Chang, B. Li and X. Yuan, "Moving Object Detection with Deep CNNs," in IEEE Access, vol. 8, pp. 29729-29741, 2020, doi: 10.1109/ACCESS.2020.2972562. [16] Hakim, H., & Fadhil, A. (2021, February). Survey: Convolution neural networks in object detection. In Journal of Physics: Conference Series (Vol. 1804, No. 1, p. 012095). IOP Publishing. 50 [17] Horak, K., & Sablatnig, R. (2019, August). Deep learning concepts and datasets for image recognition: overview 2019. In Eleventh international conference on digital image processing (ICDIP 2019) (Vol. 11179, pp. 484-491). SPIE. [18] Huang, J. (2017, August 14). “Our goal: Every single car will be autonomous.” Bosch Global. https://www.bosch.com/stories/thought-leader-jensen-huang/ [19] Islam, N., Islam, Z., & Noor, N. (2017). A survey on optical character recognition system. arXiv preprint arXiv:1710.05703. [20] Janiesch, C., Zschech, P., & Heinrich, K. (2021). Machine learning and deep learning. Electronic Markets, 31(3), 685-695. [21] Janke, J., Castelli, M., & Popovič, A. (2019). Analysis of the proficiency of fully connected neural networks in the process of classifying digital images. Benchmark of different classification algorithms on high-level image features from convolutional layers. Expert Systems with Applications, 135, 12-38. [22] Krizhevsky A., Sutskever I. & Hinton G.E., 2012. Imagenet Classification with Deep Convolutional Neural Networks. Advances in Neural Information Processing Systems (NIPS). :1097– 1105. [23] Liu, W., Anguelov, D., Erhan, D., Szegedy, C., Reed, S., Fu, C. Y., & Berg, A. C. (2016, October). SSD: Single shot multibox detector. In European conference on computer vision (pp. 21-37). Springer, Cham. [24] Mariano, V. Y., Min, J., Park, J. H., Kasturi, R., Mihalcik, D., Li, H., ... & Drayer, T. (2002, August). Performance evaluation of object detection algorithms. In 2002 International Conference on Pattern Recognition (Vol. 3, pp. 965-969). IEEE. [25] Mavrikis, S. T., Antonopoulos, C. P., Voros, N. S., & Keramidas, G. (2021, September). Comparative evaluation of computer vision technologies, targeting object identification and localization scenarios. In 2021 6th South-East Europe Design Automation, Computer Engineering, Computer Networks and Social Media Conference (SEEDA-CECNSM) (pp. 1-8). IEEE. [26] Moroney, L. (2020). AI and Machine Learning for coders. O'Reilly Media. [27] Mudiarta, I. M. D. R., Atmaja, I. M. D. S., Suharsana, I. K., Antara, I. W. G. S., Bharaditya, I. W. P., Suandirat, G. A., & Indrawan, G. (2020, April). Balinese character recognition on mobile application based on tesseract open-source OCR engine. In Journal of Physics: Conference Series (Vol. 1516, No. 1, p. 012017). IOP Publishing. [28] Padilla, R., Netto, S. L., & Da Silva, E. A. (2020, July). A survey on performance metrics for object-detection algorithms. In 2020 international conference on systems, signals and image processing (IWSSIP) (pp. 237-242). IEEE. [29] Ranjan, A., Behera, V. N. J., & Reza, M. (2021). Ocr using computer vision and machine learning. Machine Learning Algorithms for Industrial Applications, 83-105. 51 [30] Ren, S., He, K., Girshick, R., & Sun, J. (2015). Faster r-cnn: Towards real-time object detection with region proposal networks. Advances in neural information processing systems, 28. [31] Ryan, M., & Hanafiah, N. (2015). An examination of character recognition on ID card using template matching approach. Procedia Computer Science, 59, 520-529. [32] Simeone, O. (2018). A very brief introduction to machine learning with applications to communication systems. IEEE Transactions on Cognitive Communications and Networking, 4(4), 648- 664. [33] Singh, A., Bacchuwar, K., & Bhasin, A. (2012). A survey of OCR applications. International Journal of Machine Learning and Computing, 2(3), 314. [34] Vladimirov, L. (2020). TensorFlow 2 Object Detection API Tutorial. TensorFlow 2 Object Detection API Documentation. https://tensorflow-object-detection-api- tutorial.readthedocs.io/en/latest/index.html [35] Yamashita, R., Nishio, M., Do, R. K. G., & Togashi, K. (2018). Convolutional neural networks: an overview and application in radiology. Insights into imaging, 9(4), 611–629. https://doi.org/10.1007/s13244-018-0639-9 [36] Zulkhaizar, A. (2023, January 4). The Future of AI: How Artificial Intelligence is Revolutionizing the Way We Work - Digital First Magazine. Digital First Magazine. https://www.digitalfirstmagazine.com/the-future-of-ai-how-artificial-intelligence-is-revolutionizing- the-way-we-work/