Full text
Herramienta adaptativa para la creación de tests automáticos de interfaces de videojuegos Adaptative tool for automatic test creation of video game interfaces Trabajo de Fin de Grado Curso 2022–2023 Autor Cristian Rene Castillo de León Iago Quintas Diz Director Guillermo Jiménez Díaz Colaborador Alessandro Lentini Grado en Desarrollo de Videojuegos Facultad de Informática Universidad Complutense de Madrid
Herramienta adaptativa para la creación de tests automáticos de interfaces de videojuegos Adaptative tool for automatic test creation of video game interfaces Trabajo de Fin de Grado en Desarrollo de Videojuegos Departamento de Software e Inteligencia Artificial Autor Cristian Rene Castillo de León Iago Quintas Diz Director Guillermo Jiménez Díaz Colaborador Alessandro Lentini Convocatoria: Septiembre 2023 Calificación: Grado en Desarrollo de Videojuegos Facultad de Informática Universidad Complutense de Madrid 15 de Septiembre de 2023
Dedicatoria A mi familia, por apoyarme y ayudarme en todo lo posible, no lo habría conseguido sin vosotros. A mi madre, por darme todo lo que necesitaba para cumplir mis sueños. Y a Raquel, que has sido mi faro durante tantos años, por escucharme y conseguir sacarme una sonrisa todos los días. Cris A Aaron, por haber estado siempre ahí a lo largo de estos años y por ser un gran amigo. A mis padres, por haber confiado en mí y darlo todo para que hoy este aqui. A mi hermano, por haber sido siempre mi mejor amigo e inspirarme a ser mejor. Y a mi hermana, que siempre consigue sacarme una sonrisa. Iago v
Agradecimientos Gracias a todo el equipo por habernos dado todo lo que necesitábamos. Gracias a Alessandro y Angela por sus ideas y seguimiento. A Claudio por motivarnos a trabajar todos los días tratando siempre de aportarnos ideas y preocupándose por nosotros. A Blanca y a Ricardo por ser nuestros referentes y estar siempre disponibles cuando les hemos necesitado. A Fran, por ayudarnos a adaptarnos al entorno y estar ahí para apoyarnos. A la gente que aunque no trabajase con nosotros directamente, se interesó por el trabajo que haciamos. Y finalmente a Guille, por haberse preocupado tanto por el proyecto y habernos dado la oportunidad de acceder a estas prácticas. A todo el mundo que confió en el proyecto o dedicó parte de su tiempo en seguir nuestro progreso, gracias. vii
Resumen Herramienta adaptativa para la creación de tests automáticos de interfaces de videojuegos El testing es una parte fundamental durante el desarrollo de un programa o aplicación de software. Este proceso consiste en verificar y validar las distintas funcionalidades de un programa y de esta forma conseguir un producto de calidad. Sin dicha parte la mayoría de las aplicaciones serían inutilizables debido a la cantidad de errores que experimentaría un usuario. Sin embargo, el testing requiere de mucho tiempo y dinero para lograr unos resultados significativos, llevando a las empresas de videojuegos a contar con un gran número de testers que comprueban manualmente el funcionamiento de sus productos. En el caso de interfaces de videojuegos, las nuevas tecnologías y herramientas de automatización pueden ser útiles para reducir este trabajo manual y dedicarlo a pruebas únicamente realizables por humanos. Usando aprendizaje automático y preprocesado de imágenes, se ha hecho una herramienta capaz de etiquetar de forma general elementos de una interfaz de videojuegos aplicable a múltiples títulos para la realización de pruebas de navegación automáticas. Palabras clave automatización, preprocesado, clasificación, detección, interfaz, aprendizaje, videojuegos, testing, bordes, adaptable ix
List of figures 1.1. Technical debt increases over production time . . . . . . . . . . . . . . . . . 1 2.1. Example of figure-ground principle (Todorovic, 2008). . . . . . . . . . . . . 6 2.2. Example of proximity principle (Todorovic, 2008). . . . . . . . . . . . . . . . 6 2.3. Example of similarity principle (Todorovic, 2008). . . . . . . . . . . . . . . . 7 2.4. Example of closure principle (Todorovic, 2008). . . . . . . . . . . . . . . . . 7 2.5. Example of continuity principle (Todorovic, 2008). . . . . . . . . . . . . . . 7 2.6. Comparison between a standard HUD and a diegetic HUD . . . . . . . . . . 8 2.7. Example of test programmed on Selenium IDE . . . . . . . . . . . . . . . . 10 2.8. Example of test programmed on Sikuli IDE . . . . . . . . . . . . . . . . . . 12 2.9. Simplification done by OCRs from text to bit images (Smith, 1987). . . . . 13 3.1. Cogitopipeline .................................. 18 3.2. F1®22 multiplayer menu example . . . . . . . . . . . . . . . . . . . . . . . 19 3.3. Image Processing pipeline . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 3.4. F1®22 menu before and after binary threshold . . . . . . . . . . . . . . . . 20 3.5. F1®22 adapted contrast and brightness result . . . . . . . . . . . . . . . . 20 3.6. Sobel intensity graphic (Bradski and Kaehler, 2008) . . . . . . . . . . . . . 22 3.7. Second derivative of an edge (Bradski and Kaehler, 2008) . . . . . . . . . . 22 3.8. Gaussian filter application on contrasted image, the entire image is blurred in order to obtain the most prominent shapes in the image. . . . . . . . . . 23 3.9. Median filter application on contrasted image, a minimal blur to reduce the noise in the image is applied. This modification of the image results in smoothed parts, such as the face of the figure. . . . . . . . . . . . . . . . . 24 xvii
3.10. Bilateral filter application on contrasted image. This filter helps smoothing out the noise in specific parts while preserving edges such as the background and buttons in this figure. . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 3.11. One-dimensional edge profiles. (Jain et al., 1995) . . . . . . . . . . . . . . . 25 3.12. HSV Multi-Channel Canny result . . . . . . . . . . . . . . . . . . . . . . . . 26 3.13. Comparison of Canny applied to a Non-blurred and Gaussian filter F1®21 image. Contours and edges from inside each detected element are moderately reduced on the right after the filter is applied. . . . . . . . . . . . . . 27 3.14. Comparison of Canny applied to a Non-blurred and Median filter F1®20 image. The noise is slightly reduced for the tool to correctly detect the elementsonthescreen. ............................. 27 3.15. Comparison of Canny applied to a Non-blurred and Bilateral filter FIFA 23 image. Most of the noise from the background is removed. . . . . . . . . . 28 3.16. Filtered contours of a F1®2020image..................... 28 3.17. Bounding boxes of a F1®2020image ..................... 29 3.18. Text detected on a STAR WARS Jedi: Survivor™menu ........... 29 3.19. Icons detected by machine learning model on a FIFA 23 settings menu . . . 30 3.20. Text detection and icon detection performed on a FIFA 23 menu. Left being the original image and right being a visual representation of each kind of elementdetected. ................................ 30 3.21. Exit and Settings label dictionary examples . . . . . . . . . . . . . . . . . . 31 3.22. Classified texts on a STAR WARS Jedi: Survivor™menu. The green boxes outline the detected texts and display the label classified on top of them. . . 32 3.23. Classified icons on a FIFA 23 settings menu. The green boxes outline the detected icons and display the classified label and confidence on top of them. 32 3.24. Horizontal checker for menu bar detection on a F1®2021 menu . . . . . . . 34 3.25. Example result of all the final information gathered by the tool. . . . . . . . 35 4.1. Tesseract text detection prototype simple example . . . . . . . . . . . . . . 37 4.2. Tesseract text detection prototype FIFA 23 menu example . . . . . . . . . . 38 4.3. Sikulitestexample................................ 39 4.4. Example of Rekognition text detection. . . . . . . . . . . . . . . . . . . . . . 40 4.5. SageMaker first button detection model . . . . . . . . . . . . . . . . . . . . 41 4.6. Comparison between AWS text detection services on Madden. . . . . . . . . 42 4.7. Missing contours in a FIFA 23 settings menu . . . . . . . . . . . . . . . . . 43 4.8. Artificial contours for missing contours detected . . . . . . . . . . . . . . . . 43 4.9. Example of generic icon’s dataset and its use on FIFA 23 . . . . . . . . . . . 44
4.10. Example of screenshots of different menus from FIFA 23 . . . . . . . . . . . 46 4.11. Combined dictionary result example. This example shows the type of element, the text it contains with its position and dimensions as well as the position and dimensions of its contour, and finally its labels. . . . . . . . . . 47 4.12. Cogito UML architecture diagram . . . . . . . . . . . . . . . . . . . . . . . . 49 4.13. Labels.json example containing two labels. . . . . . . . . . . . . . . . . . . . 52 4.14. Appsettings.json example. It contains the game to be tested, whether lambda will be used for processing or locally and whether debug images willbegenerated. ................................ 53 5.1. Confusion matrix for different steps of the tool through F1®2022 screenshots 57 5.2. Table of times of each step of the tool applied to FIFA 2023 screenshots (in seconds)...................................... 61 5.3. Table of times of each step of the tool applied to F1®2022 screenshots (in seconds)...................................... 62 5.4. Graph of times of each step of the tool applied to FIFA 2023 screenshots (in seconds)...................................... 63 5.5. Graph of times of each step of the tool applied to F1®2022 screenshots (in seconds)...................................... 63 5.6. Boxplot of times of each step of the tool applied to FIFA 2023 screenshots (inseconds).................................... 63 5.7. Boxplot of times of each step of the tool applied to F1®2022 screenshots (inseconds).................................... 64
List of tables xxi
Chapter 1 Introduction “Cogito ergo sum” — René Descartes 1.1. Motivation Manual testing of video games can be a time-consuming and costly process, as it requires testers to play games repeatedly to identify and report any bugs or issues that may arise. The large scale of these projects make it a very complex task to detect all these issues. For that reason, the cost of the technical debt should be minimized (Keith, 2015) in order to avoid these increased solving costs that accumulate between all development stages. Figure 1.1: Technical debt increases over production time As Figure 1.1 shows, the more advanced the development stages are, the more cost it will be required to solve issues with the code. Fixing these issues on earlier stages can take very little time once they are found, However, if they are not fixed, the cost to solve these bugs grows exponentially. Advancements in technology have led to the development of even more sophisticated automated testing tools, such as AI-powered testing, which can help further reduce the costs and time associated with manual testing. Different AI approaches such as natural processing language or neural networks are interesting technologies that could be really useful if integrated with an actual testing workflow, making testing more efficient. 1
2Chapter 1. Introduction While automated testing can be a more cost-effective and efficient option, it is important to note that these tests still require human oversight. However, the goal is to trust humans to do the final assertions of tests so they can still be reliable, while the computer does the rest of the tedious work, the navigation and all the back end implementation on how to understand what is happening on a specific moment. Overall, the use of automation in video game testing is becoming increasingly popular, as it can help reduce costs and improve the efficiency of the testing process. However, it is important to have a balance between automated and manual testing, as both have their advantages and limitations. One specific area where testing is needed is interfaces. It can highly benefit of automatic testing due to the nature of the tests: doing an specific set of actions to arrive to certain menus, check button functionalities or even to check if a menu has not critical bugs that make the video game unplayable. Usually, graphic user interfaces, or GUIs, are designed with usability principles on mind. For this reason, if a relationship could be established between these principles and the testing of what is seen on the screen, it is possible that a better understanding of what is happening on the tests would be obtained. 1.2. Objectives The main goal of this investigation is contributing to the development of Cogito, a tool capable of performing automatic testing of interfaces on video games by introducing human like actions. An example could be the "Go to the Settings Menu" action, Cogito will be able to identify the different user interface elements of the video game and find the specific elements to reach that menu. The tool will identify the different elements using a combination of text, contours, edges and icon detection and then it will classify those elements in different labels using text and image classification. This main goal is divided into three sub-goals to be completed in order: 1. Research about already existing tools and possible approaches. Some investigation will be made about alternative testing software: What functionalities do they provide and how are those implemented. 2. Design and development of the tool. 3. Evaluating the effectiveness and performance of the tool. The work will be mainly focused on the part related to analyze the information on the screen. Given a screenshot of the current state of a video game, the tool should detect all important detected elements, being those: Classifying each button of the interface into a meaningful label about its role. Detect selected buttons, if any. Return the grouped elements like: grids, menu bars and lists.
1.3. Work plan 3 One of the most important points on the development of the tool will be its adaptability, to be able to work in different types of games and interfaces with the lowest possible maintenance. Since most of the existing tools require a lot of maintenance or are built inside the game itself, this solution will work outside of any engine or game. There are some limitations which define what the project will focus on: A fully focused machine learning solution is not necessary. Some steps for the project can be achieved through the use of image processing algorithms, due to the complexity of a fully generic machine learning element detector. The interfaces where the tool will be tested will be the subsequent ones to the main menu interface. Those interfaces that are a part of the game will not be tested, as well as diegetic interfaces that are a part of the game’s world. The project will be built as a tool to improve automatic interface testing for Electronic Arts and will allow testers to focus on performing less tedious and repetitive tests. 1.3. Work plan This project has been developed based on the SCRUM methodology. SCRUM is one of the most widely used methodologies in the software development industry, a project management method (Sutherland, 2015). Following this methodology, it has been established that the work plan will be divided into two-week periods called sprints, in each of the sprints the team will meet to assign each of the members a number of tasks, each task will have an estimated score that will indicate the complexity of the task and a priority to indicate which tasks should be done before others. At the end of each sprint, the resolved tasks will be closed and those still in progress or to be started will be assigned to the next sprint, and new ones will be created. Due to the complexity and continuous research of the project, there will not be many tasks in the beginning and more will be created over time. Before starting to work with the team for the creation of the tool, the project will focus on the research of the different existing tools for the creation of tests and will investigate Amazon’s machine learning tools. The development of the tool will start with a period of a few weeks of research on SageMaker and Rekognition services by creating different image recognition models and observing the advantages and disadvantages of these models. Once the models have been trained and tested with refined datasets, a prototype of how the tool will work will be developed, without yet focusing on navigation and focusing only on the recognition of interface elements. Based on the results of these image recognition models, the team will study the different alternatives or combinations to be implemented for the final tool. The team has already determined part of the technologies that will be used during the development of the tool, mainly Amazon Web Services (AWS) such as SageMaker or Rekognition for the machine learning parts of the project. Python will be used as the development language, Microsoft Visual Studio Code as the environment and the OpenCV library for image processing. The reason for using Python as a programming language is because it allows fast iteration between prototypes. In addition, when closed it will allow
10 Chapter 2. State of the art Waits, needed for the nature of the platform the tests are being run on. After doing an action, a delay should be expected until the website loads all the required elements. For this reason, there are two main ways to wait: •Active waits. Waiting for a specific time of seconds. Not very reliable due to short waits can both pass or fail a test, depending on the connection of the user. •Wait for an element. More efficient on successful tests, since once the element is found, the test can continue running. Asserts. In order to check if a test has passed successfully, there are multiple instructions to verify the test is correct. Some examples are if an element exists, if it is visible or if the title of the website contains specific words. Figure 2.7: Example of test programmed on Selenium IDE As Figure 2.7 shows, Selenium has an integrated development environment (IDE) that allows to easily create functional tests. There is a list of commands like the ones that have been described before, which are performed in order. 2.2.1.2. GameDriver API GameDriver (Gutierrez et al., 2018) is a functional testing automation video game API designed to automate repetitive tasks a player must do in a video game. It was developed specifically for the Unity engine and allowed effective communication with the elements of the scenes. The API enables the tester to control and interrogate the game, asking about its properties such as the score, positions of elements, current scene, and more. GameDriver API enables the tester to create a script that waits for a specific time or an object, required for the test, to appear. The script can take control of the keyboard and mouse with specific commands and allows the capture of images and video. This API
2.2. GUI testing 11 also provides methods for moving objects or characters to a specific location and detecting elements on the screen by name and colour. 2.2.1.3. Appium Appium (Cuellar, 2012) is an open-source tool that allows the development of automatic functional tests in both Mobile Web, iOS and Android applications. A single API that works on both platforms. Recently Appium has also been able to test Windows applications. Appium allows the development of tests on Web Applications, as well as Native Applications on mobile devices. The main difference between Appium is the ability to perform automatic tests on both Android and iOS. Appium uses an HTTP server written in Node.js that creates and manages multiple WebDriver sessions on Android and iOS devices, WebDriver is an automation framework that works with different APIs for sending commands to and interacting with an application or web. The typical operation of Appium would be, a client or tester sends a request to the Appium server, the server will receive the request and handle it by sending it to the device or emulator that will execute the request or test cases requested by the client and send the results to the Appium server that will send it to the client for observation. It works similarly to Selenium, an HTTP server that listens to and sends your requests. 2.2.2. Visual testing Visual testing, also known as visual regression testing, is a type of automatic testing that verifies the visual appearance of a software application by comparing screenshots of the application before and after changes are made. Visual testing ensures that the application’s user interface remains consistent and visually appealing after changes are made. The main advantage of visual testing over functional testing is that it can detect visual defects that may be missed by functional tests. For example, functional testing may not detect a change in font size or colour that could affect the overall user experience. Visual testing can also help ensure brand consistency and compliance with design standards. It has one great advantage compared to functional testing: it only relies on the visual output of an application, so it can be generic. One example of this is Sikuli, which uses computer vision techniques integrated with its tests. 2.2.2.1. Sikuli Sikuli (Chang and Yeh, 2009) is an open source tool used to perform automatic visual testing. It is an interpreter for multiple scripting languages as Python, used to define tests cases. It also supports an API to use specific visual testing actions, for instance, searching a template image inside another screenshot. To implement all these actions, the computer vision library OpenCV is used. As it is shown on Figure 2.8, tests are programmed on python, with the addition of an API that allows passing screenshots as parameters. There is an integration inside of the
12 Chapter 2. State of the art Figure 2.8: Example of test programmed on Sikuli IDE tool that allows to capture the region of interest of the screen to speed up programming the tests. Just like all the previously studied tools do in functional testing, it has wait instructions to give time to the program to change between states and load all the resources needed before next instruction. This kind of instructions are expanded with the image recognition API, allowing to also wait for an specific image to appear. 2.3. Computer vision techniques Computer vision techniques involve the use of computers to view elements of an image in a similar way of how an actual human would see them. That way, computers can understand images, allowing to automatize tasks that previously only humans could do. There are multiple examples of computer vision algorithms, such as edge detection, feature extraction, template matching or histogram comparison. Some of these will be explained along this chapter and the following ones (see subsection 3.2.3 for more details). 2.3.1. Optical character recognition Optical character recognition, or OCR, is the process of converting texts from any kind of image data to encoded text that can be recognized by machines. It is one of the most logical steps to take related to visual testing. It is used in a variety of situations, such as its integration with automation tools. One of its most common uses is being integrated in automatic workflow processes. AI- powered tools often rely on OCR either to obtain datasets by processing documents related
2.3. Computer vision techniques 13 to one subject, or for obtaining input cases for other AI models to use them. Written text detection, either by a machine or a human, depend on a lot of factors. Font size, color, contrast with the background, alignment or orientation can affect the whole detection. The existence of different fonts is a very troublesome factor, not to mention how text is read on different languages. Figure 2.9: Simplification done by OCRs from text to bit images (Smith, 1987). As Figure 2.9 shows, each letter is detected (a), then an skeleton of the image is obtained (b) and finally the skeleton is reduced to a minimum shape and stored as a bitmap. The story of OCRs has been in constant development. When this technology was first investigated, only computer vision techniques were used. The simplification seen on Figure 2.9 was used later in an algorithm called feature extraction. It consists obtaining the most interesting points of an image in this case, in order to reduce the amount of data with the models are trained on. This algorithm selects the points, labeling them according to the following characteristics per section. Center point, concave or convex, distance to the central point or length are some of these characteristics. In the past, OCR technology only depended on computer vision techniques, which had limitations. Even if feature extraction is a powerful tool, adaptability is not one of its strengths. In cases like handwritten text, where big enough variations can occur between different cases, it can lead to false negatives. Also, the more features detected per letter, the more challenging it will be computationally to analyze (Wang et al., 2021). Nowadays every state-of-the-art OCR is based on machine learning. It makes the whole process easier, as well as saves computational time and efforts. However, computer vision is not excluded from the process. In order to obtain meaningful data from each letter, feature extraction is still used, but now is also done by the model. This is what is known as deep learning. Next, a model is in charge of assigning encoded text letter instead of comparison as it was previously done. Related to computer vision, there are two open source libraries that are often used: Tesseract and OpenCV. Tesseract is an OCR library while OpenCV includes other computer vision techniques, standing out for its wide range of image processing functionalities.
14 Chapter 2. State of the art 2.3.2. Tesseract Tesseract (Smith and Hewlett-Packard, 1984) is an open source engine OCR which can be used on different libraries, depending on the language. It is currently trained with more than 100 languages and most of the common fonts, and allows the use of neural nets for line detection on its last version, Tesseract 4. It also gives support to the previous version, which recognizes character patterns. For the legacy engine, it requires .traineddata files, which include the result of the training for each language. In addition to the 100 languages it is trained on, Tesseract can be trained on other languages as well generating another .traineddata as has been done with the original supported languages. Tesseract text works in unicode (UTF-8). It supports PNG, JPEG and TIFF files as input and multiple outputs such as plain text or PDFs. 2.3.3. OpenCV Open Source Computer Vision Library, or OpenCV (Bradski and Kaehler, 2008), is a powerful open source computer vision and machine learning library that implements time efficient operations with images. It acts as a common infrastructure for machine learning and computer vision algorithms, including both classic algorithms and state-of-the-art ones. OpenCV has been programmed using C++ and has bindings with Java, Python and MATLAB, among other languages. This allows to use efficient in time algorithms while keeping the fast iteration workflow Python allows. OpenCV counts with its own deep neural network module (dnn) that allows to prepare data in order to use them for training machine learning models. Besides that, it also allows to perform image conversion to simplify data, operating with images in both RGB or HSV color schemes, as well as grayscales. This is particularly useful when it comes feed less information to models to obtain better performing solutions. However, this simplification can be also helpful with the classic computer vision algorithms in some cases, as it happens with edge detection algorithms. 2.4. Image classification In order to automate visual testing of video game interfaces, it is necessary for the tool to somehow understand the meaning of the elements it will detect on the screen. One of the solutions most widely used to classify data at present is deep learning. Deep learning is a field within machine learning. Often deep learning is referenced for images and feature extraction (defined on Figure 2.3.1). Additionally, in deep learning, the models automatically perform feature extraction of the characteristics with which better results would be obtained (MathWorks, 2017). Deep learning is used on neural networks as it will be explained in detail on the next subsection.
2.4. Image classification 15 2.4.1. Convolutional Neural Networks for image classification Neural networks (NN) are structures based on how an actual brain works like. They are composed of interconnected neurons, the most basic unit of data, and those are grouped in layers, which are communicated with weights that modify the information shared between neurons. Each neuron is connected to all the neurons from the previous and next layer. Most often, the application for them is using them as classifiers, where first layer contains the input, and last layer is the output. Between these 2 layers there are hidden layers, which function is to find the correlations and patters between the input and the output, modifying the weights of the layers throughout the process. The process of training a neural network consists on iterate throughout them using functions called forward propagation algorithms. These go from the input layers to the output ones, measuring the error obtained on the end and adjusting the weights of the neural network in order to get close to the desired result. In addition to that, there are some extensions to these process, such as back propagation, which allows to check the error in the output layer and send it back to the previous layers so the adjustment is more precise. Convolutional neural networks (CNN) differ on typical neural networks on the way neurons communicate with each other. Input neurons are not all assigned to every hidden layer’s neuron. Instead, each input neuron is assigned to a group of neurons from the hidden layer with weights that never change, since each hidden layer’s neuron is only used for a specific feature. This way mimics how an actual brain works, and this process has been improved on updated versions like RNCC, Fast RNCC and Faster RNCC. Their efficiency has been tested and work better with large volumes of data (Victor Ikechukwu et al., 2021). Specially deep convolutional neural networks, which are neural networks with multiple hidden layers. As it has been said on the previous section, using a pretrained neural network facilitates training, allowing training to be done with some initial weights and features, even if the labels for the images are different to the ones used originally to train the NN. This opens the possibility of training over neural networks that have already been trained on large datasets of generic images, and tune them into classiffiers with more specific labels. Currently, there are two popular ones widely used for this purpose: Residual neural network (ResNet-50) is a CNN already trained with more than one million images from the ImageNet dataset, and counts with 50 hidden layers. It appeared as a solution for the vanishing gradient problem, which made the optimization of neural networks harder as error increased. It uses a technique called skip connections, which allows to omit communications that would endanger the accuracy of the neural network. VGG-19 (Visual Geometry Group) is another CNN, trained with 19 hidden layers. It is based on a variation of the same dataset used by ResNet-50. Counts with 1000 labels and was trained over 150000 images. Its structure allows it to perform a better feature extraction, while using state-of-the-art technologies in the field of CNN.
16 Chapter 2. State of the art 2.5. Conclusion This chapter has discussed the different ways of testing based on what they aim for, functional and visual testing. Also, a research has been made about the different open source libraries and machine learning models that can be useful for the development of the project. Both these testing approaches have their own strengths, which will be discussed later in the design chapter. Although the software studied performs automatic tests following a guide script, they are not adaptative to changes in the application under test. Even when functional testing methodology is proven to be useful, they are not compatible with all testing workflows due to its previously mentioned limitations. However, it is important to look into detail about its capabilities given that they might be useful for future work. Since good video game GUIs follow Gestalt principles, they constitute the environment that will appear more commonly on the majority of existing games. With this information a standard point can be guaranteed in order to perform tests on interfaces, knowing which elements they have in common. Having studied the relevant technologies in this chapter, it is time to integrate them into the tool design.
Chapter 3 Design of a tool for creation of automatic tests of video game interfaces The standard way to perform menu navigation testing is based on testing a video game’s interface manually. Other methods include functional automation testing tools (subsection 2.2.1) or manually programmed scripts. All these solutions require a lot of work and maintenance, being tedious as they will have to be changed to test them in each new game. The use of automation in video game testing has become quite popular and menu navigation is no exception, the design of this tool takes a leap forward focusing also on adaptability, allowing automatic navigation in multiple titles using one unique solution without the need for tedious maintenance and extensive scripting. This chapter will discuss the design of our tool for creation of automatic tests of video game interfaces, Cogito. Particularly, it will be focused on automatic menu navigation. This tool processes images to detect the different elements in a user interface using a combination of image processing, optical character recognition and machine learning solutions. The detected elements are then classified into different labels and based on the results Cogito finds the specific elements to reach the desired destination. Cogito will use a scripting language to enable high-level testing and will work in different types of video games. The design of the tool was an ongoing process of research that changed significantly throughout the project. The final functionality and features of this tool will be explained during this chapter. 3.1. Cogito pipeline Cogito is an adaptative tool for the automatic navigation of menus of multiple different titles. This tool uses a combination of different image recognition algorithms and machine learning models to detect and classify the elements on a video game screenshot and, based on the results, moves or clicks on the item that is most likely to help it reach the desired destination. The Cogito pipeline works as follows: 17
18 Chapter 3. Design of a tool for creation of automatic tests of video game interfaces 1. Write a testing script indicating actions such as "Go to Settings". 2. Navigation, run the script on the game: a) Take a screenshot of the current state of the game. b) Identify and classify elements on the screen: 1) Image processing Adaptative contrast and brightness. Adaptative noise and blur filtering. Edge detection. Contour detection. Text detection. Icon detection. 2) Element classification: Text classification. Icon classification. Meaningful element groups. •Element grouping detection •Highlighted button detector •Finding navegable menus c) Choose the element to interact with based on the previous steps. d) Repeat until reaching destination. The main focus of this thesis has been the step (b): Identify and classify elements on the screen. Most of the work has been done on the identification and classification of data due to the large scope of the project. Outside of the main focus, step (c) has been briefly approached in a certain way which will be explained later on. Figure 3.1 represents the whole process. Figure 3.1: Cogito pipeline The following sections describe in detail the entire Cogito process and features. 3.2. Image processing The Image Processing section is one of the most important parts of the tool, as it helps to find the sizes and positions of the different interface elements. It was concluded that in order to achieve an adaptative tool, it was necessary to find a way to focus only on the important elements of a menu, leaving behind everything unnecessary such as dynamic elements or backgrounds. As seen in Figure 3.2, most of the
3.2. Image processing 19 interface elements have an unnecessary drawing or picture that does nothing to indicate the meaning of the element, but it is still required to get its whole size and position to achieve a proper navigation and menu structure, that is why image processing is used. Figure 3.2: F1®22 multiplayer menu example This process consists mainly in the detection of edges and contours in a menu image, but for the tool to be adaptable to multiple types of games, an adaptative process of different filters must be performed in order to achieve the best results. Figure 3.3 represents the whole Image Processing pipeline. Figure 3.3: Image Processing pipeline The following subsections describe in depth the Image Processing pipeline. 3.2.1. Adaptative contrast and brightness Tonal contrast is the difference between bright areas and dark areas in an image. To achieve a solution adaptable to any type of interface, the best possible contrast and brightness settings must be achieved. The implemented proposal is based on the value of the tonal contrast calculation of the image, and thus be able to adjust the overall brightness and contrast of the image depending on that value. This tonal contrast value is calculated and then used in a combination of operations: 1. The input image in RGBA is converted into gray-scale to apply a fixed-level threshold to get a binary image result. This fixed-level threshold converts any pixel that exceeds the threshold to white and those not exceeded to black. 2. Based on the binary result, the number of black and white pixels and thus the average tonal contrast of the image is obtained, as can be seen in Figure 3.4. 3. This average tonal contrast can then be used to obtain a brightness value to change the original image’s brightness; the resulting image can be obtained by calculating
26 Chapter 3. Design of a tool for creation of automatic tests of video game interfaces In order to obtain the adaptive threshold values, a combination of conversion of the image to gray-scale and the median of the image pixels using the formulas 3.6 and 3.7 was used. In these equations the sigma value is set to 0.33 while the other two depend on its gray-scale median values, this process will be applied to each channel of the HSV image due to the possible loss of information when converting to gray-scale, by doing this on each channel and merging the results the tool makes sure that no information is lost and obtains a more accurate result. Figure 3.12: HSV Multi-Channel Canny result As can be seen on Figure 3.12, the combination of each HSV channel Canny results on a binary matrix containing the edges of the image. The importance of the brightness, contrast and blur filters explained above in performing the Canny algorithm will be appreciated below. Gaussian Filter - Canny As explained above, the Gaussian filter is used for high contrast images in order to remove unnecessary noise or edges, as can be seen in Figure 3.13, the Canny algorithm is able to capture most of the edges in a non-blurred image but maintains a considerable amount of noise, so it is necessary to apply a Gaussian filter in order to reduce such noise. Median Filter - Canny The median filter is used for images with low contrast and low sharpness, due to the low sharpness value it is applied in a reduced way to maintain as much edges as possible and reduce the noise, as seen in Figure 3.14. Bilateral Filter - Canny The bilateral filter is used for images with low contrast and high sharpness. Images with a high sharpness value could indicate that unimportant backgrounds or elements stand out in the image. This filter is perfect to reduce this kind of noise and unnecessary edges. As seen in Figure 3.15 background noise is considerably reduced.
3.2. Image processing 27 (a) Non-blurred image Canny (b) Gaussian filter image Canny Figure 3.13: Comparison of Canny applied to a Non-blurred and Gaussian filter F1®21 image. Contours and edges from inside each detected element are moderately reduced on the right after the filter is applied. (a) Non-blurred image Canny (b) Median filter image Canny Figure 3.14: Comparison of Canny applied to a Non-blurred and Median filter F1®20 image. The noise is slightly reduced for the tool to correctly detect the elements on the screen. 3.2.4. Contour detection Contours are curves joined by all continuous points along a boundary that have the same color or intensity (Bradski and Kaehler, 2008). To correctly detect the contours of an image, some steps must be followed: 1. The image to be detected must be binary for greater accuracy. To do this the canny algorithm is used. 2. Based on the binary image, a contour detection algorithm is used. 3. Contours are simplified and filtered to keep only those that are closed or convex. (Figure 3.16). 4. The bounding boxes are obtained from the contours in order to have simplified shapes and thus obtain most of the buttons or interface elements (Figure 3.17). This step is relatively simple thanks to the work done in the previous phases, allowing a more accurate detection. Throughout this process the tool has applied different brightness, contrast and blur filters in order to be able to use the edge and contour detection algorithms in the image.
28 Chapter 3. Design of a tool for creation of automatic tests of video game interfaces (a) Non-blurred image Canny (b) Bilateral filter image Canny Figure 3.15: Comparison of Canny applied to a Non-blurred and Bilateral filter FIFA 23 image. Most of the noise from the background is removed. Figure 3.16: Filtered contours of a F1®2020 image At this point it is necessary to filter these contours by keeping only those that contain a meaningful element, these elements being text or icons. This is done because a meaningless contour is probably not part of a menu. By obtaining texts and icons the tool will then be able to classify them and then find structures of navigable menu elements. 3.2.5. Text detection To detect text, an OCR machine learning model is used. After extensive testing, it has proven to be very effective and is able to detect text from a large number of different sources. Although it is a very feasible solution, it still requires further refinement which will be described below: 1. The machine learning model recognizes text word-by-word due to possible errors when detecting paragraphs or lines of text. 2. Once all the words of an image have been obtained, those that are not in horizontal orientation will be discarded. Then those words that are sufficiently close and aligned horizontally will be merged together and those lines of words that are close and
3.2. Image processing 29 Figure 3.17: Bounding boxes of a F1®2020 image aligned vertically will be joined together (Figure 3.18). With this process the tool is able to detect paragraphs and lines of text. 3. Finally, the returned result will be a list of all the texts with their respective bounding boxes. Figure 3.18: Text detected on a STAR WARS Jedi: Survivor™menu 3.2.6. Icon detection In addition to text detection, a general icon detection is also performed. For this purpose, a trained machine learning model is used to recognize elements that resemble an icon in a screenshot. This model has been used because it is possible that some buttons only have an icon without text and it is necessary to select it to know what it is, so it must be detected first. This model is trained with a database of different images containing icons of any type,
30 Chapter 3. Design of a tool for creation of automatic tests of video game interfaces all labeled with the same label. The model will receive an image and will detect in it the elements that have any resemblance similar to an icon. Figure 3.19: Icons detected by machine learning model on a FIFA 23 settings menu As can be seen on Figure 3.19, the model is able to detect most of the icons in an image and also considers text as icons, since during the training process some of the icon images used contained text. But due to the previous text detection it is possible to discard those texts detected by the general icon model and keep those true icons. Now that the bounding boxes of the contours as well as the text and icons of the image have been obtained, it is time to combine all the previous steps. The tool will merge both results in order to filter out the important elements of the image. For this purpose, those contours that contain a text or an icon are considered as relevant and because the contour detection could fail, it has been decided to keep those texts and icons that are not contained in a bounding box, while the rest of the contours will be discarded. (a) FIFA 23 Settings menu (b) Text and icon detection combined with the detected buttons on the image. Figure 3.20: Text detection and icon detection performed on a FIFA 23 menu. Left being the original image and right being a visual representation of each kind of element detected. As can be seen in Figure 3.20, the red chromatic boxes are the contours of each element, the yellow boxes represent the text and the purple boxes represent the icons. This result is used for the next step of the tool, classification. This is in charge of classifying the texts and icons of the data obtained. Once the elements have been classified separately, the tool will seek to group these elements in order to find a navigable menu.
3.3. Element classification 31 3.3. Element classification Now that information like the position of elements or their contents has been obtained, this part of the pipeline will focus on classifying these elements. This will not only into texts and icons, but also meaningful elements 3.3.1. Text classification In the case of text classification, the tool mainly uses a dictionary of labels (Figure 3.21), where each label contains words or phrases associated with that label. The process to classify a text using this dictionary consists of going through each word of each label in the dictionary and making a comparison between the word and the text to be classified. This comparison will be based on word similarity and the confidence will be determined by that similarity. Figure 3.21: Exit and Settings label dictionary examples This process is applied to every text type entry of the previous phase (subsubsection 4.2.3.2). Text not classified correctly or with a confidence value below a defined threshold will be discarded. Figure 3.22 shows an example of text classification using this solution, using green boxes to surround classified elements, marking them with their corresponding label. Although it has been mentioned that this solution does not need tedious maintenance, Cogito will still need to be maintained to keep the different labels in check with the video games to be tested with. Even so, maintenance will be minimal and this will be the only critical aspect to be updated. In the case of text classification, the label dictionary part of the tool is the one that needs the most maintenance, but it can be done quickly as it only means including a word or phrase in the label dictionary. 3.3.2. Icon classification The process followed by icon classification is similar to that of icon detection (subsubsection 4.2.3.2), but in this case applied only to specific types of menu icons. The model
32 Chapter 3. Design of a tool for creation of automatic tests of video game interfaces Figure 3.22: Classified texts on a STAR WARS Jedi: Survivor™menu. The green boxes outline the detected texts and display the label classified on top of them. has been trained with multiple examples to be able to recognise typical icons that appear in multiple video games such as the Settings, Accessibility or Controller icons. Each type of icon is a label for the model to train. This solution, in combination with the icon detection result, can be very useful to specify which function a button has and thus be able to classify buttons that do not contain any text. Figure 3.23 shows an example of icon classification using the aforementioned model, using green boxes to surround classified elements on the same way that was done with texts, marking them with their corresponding label as well. Figure 3.23: Classified icons on a FIFA 23 settings menu. The green boxes outline the detected icons and display the classified label and confidence on top of them. 3.3.3. Meaningful element groups Now that most of the elements of the screen have been obtained and they have been classified, it is time to check various aspects of the elements in order to know in which
3.3. Element classification 33 parts of the screen can the tool navigate through. The steps to perform are the following: Element grouping detection (subsubsection 3.3.3.1) - Groupings of elements or buttons will be detected following Gestalt’s principles to differentiate between groups (section 2.1). Highlighted button detection (subsubsection 3.3.3.2) - Inside each of these groups, the selected button must be detected in order to properly know where it is located during navigation. Finding navigable menus (subsubsection 3.3.3.3) - It is necessary to know which groups of elements are truly part of the menu interface and can be navigated through. This case will help to establish the navigation’s entry point and to know if we have reached the desired destination. 3.3.3.1. Element grouping detection The objective of this stage is to obtain the groups of elements that form an aligned structure because they are more likely to belong to a video game menu. This approach has been decided due to the current state of video game interfaces, which are largely based on Gestalt principles and maintain adequate accessibility for players (section 2.1). The tool will search for elements that are aligned both horizontally, vertically and in the form of grid, in order to obtain the possible lists of horizontal, vertical or grid buttons that may be on the screen. Following the Gestalt principle of proximity, the tool assumes that the elements that are close and aligned will belong to the same group. Once the groups of horizontally or vertically aligned elements are found, the tool will search if there is a relationship between these groups, in order to find a grid of elements as well. When talking about elements, the tool will mainly seek to group texts and icons that are aligned. These elements may or may not be actually related and for this the tool must be able to keep only the correct groups of elements, that is why the tool is required to have a way to find navigable menus. 3.3.3.2. Highlighted button detection The detection of the selected button is a crucial part of the tool because knowing which element has the focus greatly aids navigation. If we look at video game interfaces, the selected button usually has a different contrast level than the rest or a different color, so this information is very useful when it comes to finding the different button. To do this, the tool uses an algorithm based on histogram intersection comparison. When getting the groups of buttons the tool acquires the histogram of each of the buttons and compares them with the rest using the intersection algorithm. If a histogram has a similar range of colors or contrast its intersection will be greater while if they are totally different the intersection will be minimal (subsection 3.2.2). By obtaining the intersections between every element in a group the tool is able to know which element is selected because it will have a much smaller intersection than the others.
34 Chapter 3. Design of a tool for creation of automatic tests of video game interfaces 3.3.3.3. Finding navigable menus In order for the tool to be able to know if there is a navigable menu on the screen, it is necessary to use the groups of aligned elements and keep only those groups that have a meaning. That is why the tool uses checkers to identify those groups, which are in charge of checking that the different groupings of aligned elements contain elements classified with labels belonging to a menu interface. Checkers help the tool find the correct groups of elements and the tool will use them to find navigable menus or menu components such as menu bars. These are the following types of checkers: Horizontal and Vertical Checker These checkers are mainly in charge of finding in the horizontal or vertical aligned groups obtained previously if they comply with the rule previously mentioned, that the elements of said group have specific labels. This rule is used so that these checkers only store groups of elements that can belong to an interactive menu. They can work well when looking for menu bars or profile bars, as such menu items usually have the same type of labels in any game. (a) F1®2021 menu (b) Menu bar detected by horizontal checker Figure 3.24: Horizontal checker for menu bar detection on a F1®2021 menu As can be seen in Figure 3.24, the menu bar is detected correctly and even includes which button is currently selected. Grid Checker This type of checker uses the grid element detection mentioned above which combines both horizontal and vertical groups to find a grid which correctly is a menu interface. Uses the same rule as the previous checkers, if the elements share the same or some of the labels belonging to a menu interface. After the process of data classification and checking, the tool returns all the collected information to the navigation application for it to use. This information includes texts, icons, contours and groups of menu elements with their selected element. Figure 3.25 represents a visual example of the final result.
3.4. Choose the element to interact 35 Figure 3.25: Example result of all the final information gathered by the tool. 3.4. Choose the element to interact The Cogito application is able to run a game, take screenshots, send those screenshots to the Navigation pipeline and based on the results returned by the detection and classification workflows it will perform some input actions. It is important to highlight that the navigation part was not the main focus of this project. Still, its design is briefly explain as how it has been thought, Once the identification and classification of elements is done, now the navigation starts. It uses the data obtained by the previous steps to perform an automatic navigation through the entire menu of a video game, selecting all the menu buttons. This approach is a simple start to demonstrate the potential of the tool. From the data obtained, the input made by the tool changes according to the type of navigable menu in which it is located. If it is horizontal or vertical it will move along that axis and if it is a grid it will move along both axis. The tool will search for the destination element on the menu and if it does not find it, it will search for elements with the same label as the destination. The tool considers that it has reached the destination if it has selected the element or if it has found it in the screen. In case the navigation gets stuck or does not reach the desired destination it will stop and declare the test as a fail. 3.5. Conclusion Throughout this section the pipeline of the Cogito tool has been described. This is divided into multiple parts. The work done has mainly focused on the step regarding identification and classification of elements, which forms the entire analysis part of the tool and its the one explained with more detail.
42 Chapter 4. Development ing. Two machine learning text detection models, AWS Rekognition and AWS Textract, were tested. Rekognition was shown to work with various types of fonts of different titles, while Textract was a model focused on document text detection, so the first text detection model was chosen. The process to use the OCR is described on subsection 3.2.5. (a) Example of AWS Textract, almost none of the text was detected. (b) Example of AWS Reckognition, most of the text was correctly detected. Figure 4.6: Comparison between AWS text detection services on Madden. As can be seen in Figure 4.6, Rekognition’s text detection outperforms Textract’s in video game cases, detecting all the relevant text of the screen. Although Tesseract OCR was investigated at the beginning of the project, its results were not satisfactory due to font detection limitations. Additionally, it had the same problem as AWS Textract, it worked better with documents than with dynamic interfaces. 4.2.1.1. Text detection limitations and improvements Rekognition text detection requires a byte-encoded image as input and returns a dictionary object, which indicates attributes about the detected texts, such as position, detected words, confidence and an unique id for each phrase. It should be noted that texts can be detected as separate words or as phrases. However, it has occurred that words that were part of the same phrase were not always grouped correctly. In addition, words were only grouped horizontally, but not vertically. For this reason, word detection mode is used, and an internal adjustment is made that forms groups based on the vertical alignment of words, and the distance between words, based on their font size. One problem encountered in testing was the one hundred word limit: Rekognition limit restrict its detection to a hundred words per call. This caused some images exceeding this amount to have missing words at the bottom of the screen, because word detection goes from the top left position of the image to the bottom right, reading words from left to right and top to bottom. This was solved by making several calls, adding a black box to the regions before where the last word was detected in the previous call and combining the results from the different calls. Thanks to this solution, the tool is able to detect all texts correctly and thus also classify them correctly. 4.2.2. Second Iteration - Image processing Although the use of models that detect any type of buttons was discarded, an attempt was still made to simplify the data for both training and validation, because if what
4.2. Iterative development 43 hindered the model was unnecessary information, keeping only the necessary information would improve the results. This led to the creation of an image processing module, which simplified a screenshot of an interface to red and yellow boxes, signifying contours and texts respectively. Due to the great results provided by this solution, the button detection model was ultimately discarded and the project focused into improving the image processing. The objective of this image processing is to obtain those elements that are in the foreground of the image, performing edge and contour detection techniques on images with specific blur and contrast filters. The whole final process is explained with detail above (section 3.2). Even so, after the whole process some cases may occur in which the elements still do not have their contours correctly detected (Figure 4.7). Figure 4.7: Missing contours in a FIFA 23 settings menu 4.2.2.1. Missing contours solution The detection of bounding boxes is not perfect, so a missing contour detection algorithm has been developed that based on alignment creates a new contour for the contourless text or icon. The algorithm replicates the bounding boxes of near aligned elements to fit the missing space. If the element is not aligned with any other, it is assumed that it does not belong to a button list or anything like that so no contour is applied to it. Figure 4.8: Artificial contours for missing contours detected
44 Chapter 4. Development 4.2.3. Third Iteration - Element classification Once the button tiles were correctly detected, the next goal was to be able to classify each element with a meaningful label that can be used in future steps for navigation. Elements are shapes reassembling buttons on the screen that can contain either a text, an icon, or both. Multiple approaches were tested for this task. 4.2.3.1. General icon object detection model Using the AWS Rekogntion custom labels service, several models were trained with the objective of detecting just the icon positions, but not its meaning, as it was described on subsubsection 4.2.3.2. This was done in order to facilitate the image processing step, since the general positions are needed to know what is a button and what is not, even when the icon is too abstract for the models to determine its meaning with the next model. The idea was using multiple screenshots from video games labeling all menu icons under the same label. However, in order to achieve a good accuracy, models need from regularization data to avoid overfitting, a problem that would severely affect the usefulness of this mode. The dataset used for this model includes not only video games screenshots. but a combination of screenshots and artificially created menus with generic icons (Delapouite and Lorc, 2022) over backgrounds. Over these artificial menus, multiple things were tested, for example changing its orientation, transparency, color and background. The final dataset is composed of 44 game screenshots and 167 generated images for training, 9 game screenshots and 46 generated images for testing. A small script was made in order to generate this artificial menus with variations and obtain their positions to label them automatically with the generic label and its position on the screen. The reason for doing this is that the model must be an object detector, so it needs to be trained with positions so that later it can also detect icon positions. Except for the modifications to the transparency, all other changes were satisfactory improvements, resulting in a highly accurate model. (a) Artificially created test interface (b) Example of generic icons model on FIFA 23 Figure 4.9: Example of generic icon’s dataset and its use on FIFA 23 In the previous figure Figure 4.9 (a) shows one image from the dataset with the previously mentioned modifications, whereas (b) shows how generic icons are detected with a confidence over 80%, without filtering the icons not needed.
4.2. Iterative development 45 4.2.3.2. Icon detection model This model is based on part of the dataset used for the generic icons model (see subsection 3.3.2). However, generic icons can not be used for this approach, so regularization must be done with specific icons, which causes on a larger sized amount of icons used. This is due to finding specific icons is a harder task which will require more effort than in the general model. In addition to that, this model includes multiple labels for the most common elements that have the same meaning between different video games genres. For example, some labels used are settings, audio, accessibility or social. It is important to note that this model will not be used on icons which meaning varies depending on what genre you are playing. An example of this issue would be an icon of a house. In the case of a generic game, this icon usually means "return to the main menu". However, in a racing game, a house icon can be identified as "garage" or "customization". Since icons that are from the same label can appear in different shapes, multiple sublabels for the same label are used when needed. An example of this would be the most common icons for sound, a speaker icon, and a headphones icon. If only a label was used for each kind of icon, the model would fit worse to the already limited train icons, which would result on worse prediction scores. For both generic and specific icons, a SageMaker model was trained as well using the ResNet-50 Convolutional Neural Network (see subsection 2.4.1) 4.2.3.3. SageMaker text classification Text classification has been tried with multiple approaches. Three kinds of models were tested and compared to know which one was able to give better predictions. Furthermore, training a model from scratch is very challenging, and needs of large amounts of data to be reliable. However, this was tried for research purposes at this iteration. The accuracy of this model is very low, having the mean average precision (mAP) fluctuating out of control. Also it is not able to detect similar semantic relationships, having a hard time to classify even variations of words with the same roots under the same label. The second approach was training over an already trained model. SageMaker allows transfer learning for text on a list of models. In the case of text, it supports BERT model variations. BERT (Bidirectional Encoder Representations from Transformers) provides dense vector representations for natural language by using a deep, pre-trained neural network with the Transformer architecture (Devlin et al., 2019). Although its accuracy is more stable compared to the previous approach and part of the text is correctly labeled, it still happens that on the same label, successfully classified text scores can vary greatly. This is a huge problem, causing the classification to be unreliable, since a low score can mean either a correct or incorrect classification at the same time. The third approach was using a revolutionary technology called Zero-Shot learning. It consist on models trained on natural language processing techniques with the difference of them being able to predict labels that were not specifically trained with. This model by itself is versatile, allowing to detect any existent labels if enough information is used. A
46 Chapter 4. Development disadvantage that it has compared to previous models is that it does not allow tuning or transfer learning using SageMaker, so the results are limited to what the model offers by default. In the end, due to the unreliability of these solutions, it was decided to implement a dictionary-based text classification system, which is a more robust solution than the previous ones. 4.2.3.4. Dictionary text classification Dictionaries appear as an attempt to improve text classification. Each label has a list with the most common words for each label gathered from multiple titles from Electronic Arts. This guarantees phrases being correctly labeled when detected, but at the same time it lacks adaptability. The use of dictionaries is explained on subsection 3.3.1. Something that is done to increase the chances of a correct classification is detecting partial match instead of the full word. The reason to do this is that the OCR may read a letter wrongly, causing it to fail in a limited amount of cases. In order to fix that and similar issues like plurals of words, this method goes letter by letter and returns a percentage with how similar to the original text a label is, doing this for each phrase inside that label (a) Settings menu screenshot of FIFA 23 (b) Gamemodes on FIFA 23 Figure 4.10: Example of screenshots of different menus from FIFA 23 However, even with the subsequent improvements, there is a problem that these text classifiers cannot avoid, which is lack of context. For example, on Figure 4.10, on (a) the word "MATCH" can be interpreted by trained models as "play a match", when right here its context suggests it actually means "match settings". In addition to that, models can not detect proper nouns. Taking as example the word "SEASONS" on (b), models would assign a "season pass" label in the best of the scenarios, instead of "game mode". It does not matter how extensive the training is, it can not detect words it has not seen before. Figure 4.11 is an example of an entry in the data returned by the tool after the text classification using the dictionary solution. As can be seen, the text SOLO is classified as single player. This completes the most vital information about the objects detected in the image.
4.2. Iterative development 47 { "Type": "Text", "Text": "SOLO", "Box": { "Left": 987, "Top": 319 "Width": 125, "Height": 74, }, "ContourBox": { "Left": 967, "Top": 299, "Width": 358, "Height": 299 }, "Labels": [ { "Label": "single_player", "Confidence": 1.0 } ] } Figure 4.11: Combined dictionary result example. This example shows the type of element, the text it contains with its position and dimensions as well as the position and dimensions of its contour, and finally its labels. 4.2.4. Fourth Iteration - Checkers and Highlighted Button An addition to the tool is the use of checkers. Checkers, as we define them, are classes that check whether certain labels are contained in aligned groups of elements in order to find navigable menus. This is useful to detect components such as menu bars, or to detect which is the first menu found that fulfills the rules to be a main menu. Thanks to the checkers, the context of the tool is updated, allowing it to understand better its current state. For instance, a common element in video game interfaces are menu bars. Knowing what a menu bar is, they will be considered as such, facilitating navigation. In combination with checkers, there is a second improvement related to understanding the context of a video game state. Highlighted buttons are considered as the most differentiated buttons from a group. Two methods have been tested, being the first one detecting the highest mean deviation of V components in images with HSV format, and the second one doing histogram intersections in order to find the lowest intersection value. Although the first method works in some F1 2022 test cases, it does not always work, since the ratio between the number of background and text pixels is not always the same. For this reason, a generic comparison of histograms by applying intersections works better. Both of these additions are explained on subsubsection 3.3.3.3. The basic process is the opposite: instead of looking for the most different button, the
48 Chapter 4. Development tool focuses on what makes all these buttons similar and then excludes the one with the least similarity. This solution works on all tested games without any false detection (see chapter 5). At the end of this whole Cogito navigation pipeline process the information is stored in a dictionary object and used to perform input. The information is stored as follows: Data: A list containing all the detected texts and icons stored in raw form. Each element maintains the same structure as Figure 4.11. RawText: A list which contains all the texts without further information. This list is used in order to determine if a menu has changed considerably from one input to another in the navigation. MenuInfo: This entry on the dictionary stores the different horizontal, vertical or grid menus that were determined by the checkers. Each menu contains a list of its elements and the index of the selected element at the moment. 4.2.5. Fifth Iteration - Lambda The tool at this point consists of multiple ways to analyze what is on screen. In the future, another tool designed to navigate using the information currently obtained should be running at the same time. For this reason, and also for convenience, the objective of this iteration is porting the code so it can run on a python lambda, in order to facilitate remote access on another device that will be doing the navigation while communicating with this lambda. Specifically, the service used to host this lambda is AWS Lambda, described on subsection 4.1.4. A continuous integration system updates the code with the newest updates, and uploads it to the lambda. Some basic tests can be done this way to guarantee that the tool is working as intended, but for now there are not any. In the future it would be a good idea to have them to speed up the work between iterations. 4.3. Architecture Cogito is a console application implemented in Python and composed of two Python modules: CogitoApp, a console application that contains the main loop of the tool. This application is in charge of executing a given game, taking screenshots and sending them to the lambda function and based on the results of the function it will perform input to fulfill its objective. This application uses an appsettings.json file to define which game executable to use and an input module to navigate through a menu. The main focus of this project has been the Cogito module and this CogitoApp only contains what is necessary to execute a navigation loop. Cogito, a module stored as a lambda function in the AWS Lambda service. This module is the central part of the tool, since it is in charge of all image processing, element detection and classification process explained before (section 3.2). The lambda
4.3. Architecture 49 function takes an image as input and returns a dictionary object containing all the detected and classified elements, as well as the type of menu and selected button. This module can also be used locally as a Python module. The architecture of the Cogito module is divided into five sub-modules, each one in charge of a part of the image processing, element detection and classification process explained above (chapter 3). The following UML diagram graphically depicts the Cogito architecture (Figure 4.12). Figure 4.12: Cogito UML architecture diagram 4.3.1. Image Processing module This module is divided into several classes that are then combined to obtain the result of contour and edge detection, the classes are as follows: BrightnessContrastFilterer - As the name suggests, this class is responsible for adjusting the brightness and contrast of an input image to better adapt to contour and edge detection. BlurAutomation - It uses the output of the BrightnessContrastFilterer class to apply the different types of blur filter by obtaining the sharpness and contrast as explained in subsection 3.2.2. ContourDetector - This class takes an image as input to detect its contours and contains methods to filter those contours based on text and icons. MissingContourDetector - As explained earlier in this section, this class detects missing contours that might not have been correctly recognized by the previous algorithms. It detects these contours based on alignment, distances and already existing contours. ImageProcessor - The ImageProcessor class is the main focus of this module, containing the rest of the classes to combine their results and return the final output.
50 Chapter 4. Development EdgeDetectionStrategy - An abstract class whose children define the different Canny algorithms to use. The different strategies are as follows: •MultiChannelStrategy - Applies the median Canny algorithm to each channel of the input image and combines them all. •OtsuStrategy - Applies the Otsu thresholding algorithm which returns an intensity threshold to define the background and foreground of an image (Sezgin and Sankur (2004)). This threshold is used for the Canny algorithm. •StraightLineStrategy - Uses OpenCv’s straight line detection algorithm to detect only the horizontal and vertical lines of an image in combination with the Canny algorithm. The strategy used at the moment is the MultiChannelStrategy. This class is used by the ImageProcessor to properly detect the edges in a screenshot. 4.3.2. Element Detection module The Element Detection module contains the two classes of machine learning used to detect features in an input image: TextDetect - This class is responsible for making calls to AWS Rekognition to detect text in an image. It has methods that based on the words detected by the model discards words not aligned horizontally and combines those words into sentences or paragraphs based on alignment, distance and font size. IconDetect - Similar to the TextDetect, is responsible for making calls to AWS Rekognition to detect icons in an image, this class needs a properly trained model to work with and currently uses a model trained and tested with over 250 images for general icon detection. 4.3.3. Element Classification module It follows a similar structure containing two classes to classify text and icons respectively. They rely on Strategy classes to establish different types of classification. TextClassifier and TextClassifierStrategy - These classes are responsible for classifying the text detected by the Element Detection module. The TextClassifier class can take the output of the TextDetect class and classify it directly, it uses a label dictionary where each label contains a list of words related to it. This class uses the abstract class TextClassifierStrategy to define what kind of classification to use, at the moment, a SimilarityClassifierStrategy is used to compare the detected words with those in the label dictionary based on word similarity, but it can also be configured to use an ExactClassifierStrategy, which only labels detected words if they are exactly in the label dictionary. IconClassifier and IconClassifierStrategy - These classes follow the same structure as the text classification classes, but instead of using a dictionary of labels.
4.3. Architecture 51 The IconClassifier uses an IconClassifierStrategy abstract class which calls a model that looks for common icons in a video game interface and classifies them. The Strategy used can implement a Rekognition or SageMaker model, which can be configured on the models.py script. Then the image is sent to the specified model, and each icon is classified with its label. 4.3.4. Meaningful Element Identification module This module uses the classification results to find significant elements of a video game menu. It contains the following classes: AlignmentElementDetector - One of the pillars of the module, this class uses the results obtained in the detection of texts and icons to group these elements in different horizontal and vertical groups, according to their alignment and distance. This class stores the groups detected for the other classes to use. Checker - The Checker is an abstract class that takes an array of labels, an alignment detector and a highlighted button detector and uses them to check for significant items in a menu. Its way of checking is to look for whether a given number of labels from the label array are found in the groups of aligned items. It also defines functions to check specific labels in the data output returned by the classification and a simple set of rules for checking these significant items. Horizontal, Vertical and Grid Checkers - These classes inherit from the Checker class, they are in charge of checking for each type of group of elements if there are some labels of a given list of labels. This solution is used to determine if an aligned group of elements is truly part of a navigable menu, since elements in a menu should be related to specific menu labels. HighlightedButtonDetector - This is one of the most important classes of the tool, because knowing the exact button where the tool is located greatly aids navigation. The HighlightedButtonDetector uses a group of aligned elements and the original image to work properly. This class acquires the histogram of each element in the group and compares it using an intersection algorithm. Once all the intersections of the histogram of all the buttons are obtained, the sum of all the intersections of each button is done and the lower one will be the selected button, since if its intersections with the rest of the buttons is low it means that it does not look like the rest of the buttons which makes it the highlighted button. OpenCV allows the developer to define the size of the histogram to be more or less detailed. In the case of this class small size histograms are used due to the level of detail in some buttons which can complicate the detection, having a small histogram will keep the general details of the button and will allow a more accurate comparison between the other buttons. 4.3.5. Configuration module In order to properly configure the tool a module was created. This configuration module contains two .json files which one stores the tool configuration (appsettings.json) and the
58 Chapter 5. Evaluation 5.2. Time performance As a matter of fact, obtaining better times has not been the primary objective of this proof of concept, but is still necessary to understand the current state of the tool. The main goal of this evaluation will finding the bottlenecks on the workflow of the tool in order to know which parts need to be more time efficient. 5.2.1. Methodology This evaluation has been done monitoring the time employed by each step on every image from the last evaluation. In addition to the images from F1®2022, time has also been monitored on screenshots from another video game, FIFA 2023. This time measurement has only been done once due to the amount of images used, which should be descriptive enough about the state of the tool. Time has been measured on the following steps: contrast and brightness, blur filter, edge detector, contour detector, text detector, icon detector, text classification, icon classification and highlighted tiles detection. It is important to note that these services include network latency on the calls to the models responsible of text detection, icon detection, and icon classification, which are cloud-based online services, but the rest of the steps are done locally on a virtual machine with 16 CPU, 110 GB of RAM, and an NVIDIA Tesla T4 as GPU (1 GPU and 16 GB). The metrics used to determine how much time it takes for the tool to process an image will the calculated this way: 1. Time events will be stored on a list each time an important part of the tool starts and finishes. This is repeated for each image and it is done in the same way a telemetry system would work, but at a much smaller scale. 2. When these two time stamps are obtained, a subtraction will be done. The time obtained will be calculated by subtracting the end time from the start time, and then final times will be stored on a data frame (for easier later display of the results) With this information, it can also be calculated the total time needed to process each image. 5.2.2. Results and conclusions The same number of images has been used than in the previous evaluation: 129 for F1®2022, and 72 for FIFA 20231. The full results are included on a drive folder, but only a fraction of those are included on the tables from the figures since not all entries are needed to understand the objective. As it can be seen on Figure 5.2 and Figure 5.3, in both tables each column show the time needed for each step for each image of each game. All results are sorted by the total time 1Full results area available at https://drive.google.com/drive/folders/1on6ZYTw0sAniN4AEGEaUqITnbzMLw- dC?usp=sharing
5.3. Conclusions 59 needed to process an image, going from the lower to the highest times. The slowest step is highlighted in red, and the total processing time for that image is highlighted in green. Analyzing the results from both games the same limitation appears. One of the most time consuming parts is detecting the text on the screen using Rekognition’s OCR model. In addition to this, there is another bottleneck that appears mostly on FIFA 2023 sometimes when adding blur filters, which can be seen on the third column. More specifically, it has been observed that higher times only occur when Bilateral filters are applied, although this information is not visible on the table. The reason why this is chosen automatically for the most fitting images and why the filter takes longer is explained on subsection 3.2.2. This is due to it is based on a time consuming algorithm which takes each pixel and converts it to the weighted average of its neighbours, and the time needed really depends on the hardware on which the tool is running. An obvious limitation this proof of concept has is working on a single thread. The use of synchronous calls to the models used on text detection, icon detection, and icon classification forces the tool to wait until models have done their work. However, there are parts of the tool that could be working at the same time. If calls to these three models were done at the same time while blur filters are applied, a lot of time could be potentially saved. On Figure 5.4 and Figure 5.5 it can be seen the results from the tables in the shape of graphs. Observing the metrics this way shows in a more obvious way how time is wasted waiting for the response of machine learning models, when it is not really necessary to wait for their results since the content of these models is not needed to calculate previous steps. Finally, on Figure 5.7 and Figure 5.6 boxplot diagrams can be seen. These are only to prove that the steps of blue filter and text detection keep the values shown on the time tables. This can be seen on the blue lines inside the boxes, representing the median of the seconds per step of each image. 5.3. Conclusions After obtaining these results, some points have been clarified. First, the quality of machine learning models related to icons needs to be improved. While the icon detection model has shown results that start to get close to being reliable, it still is not, and neither the icon classification is. More training should be done with a better dataset to increase their confidence. In addition to this, other steps not related to machine learning need more work, which is the case of the highlighted buttons detector. Now it has to be studied the reason why these results aren’t reliable. The high amount of false negatives in comparison with false positives included on Figure 5.1 seem to indicate something is failing in on some images where no highlighted button is detected at all, so that should be studied. Finally, the total times obtained for this proof of concept are reasonable. However, the whole process of the tool is expected to run multiple times on tests. For this reason, time should be reduced as much as possible to avoid unreasonable long tests in the future. An effective way to eliminate the problem of wasting execution time would be to use a multi-threaded implementation, as it would reduce the unproductive waits to a minimum, achieving a possible improvement of reducing the time needed on F1®by half in the best
60 Chapter 5. Evaluation of situations.
5.3. Conclusions 61 Figure 5.2: Table of times of each step of the tool applied to FIFA 2023 screenshots (in seconds)
62 Chapter 5. Evaluation Figure 5.3: Table of times of each step of the tool applied to F1®2022 screenshots (in seconds)
5.3. Conclusions 63 Figure 5.4: Graph of times of each step of the tool applied to FIFA 2023 screenshots (in seconds) Figure 5.5: Graph of times of each step of the tool applied to F1®2022 screenshots (in seconds) Figure 5.6: Boxplot of times of each step of the tool applied to FIFA 2023 screenshots (in seconds)
64 Chapter 5. Evaluation Figure 5.7: Boxplot of times of each step of the tool applied to F1®2022 screenshots (in seconds)
Chapter 6 Conclusions and Future Work Manual testing is a costly and tedious job that involves a large number of testers performing simple tasks that are performed repetitively over a large number of video games. The job of these testers should be to focus on testing those elements of the game that are complex and thus have a more polished game. This is why an automatic navigation tool would be ideal for testing a video game, since the menus in the industry are usually similar and testing in such menus is relatively simple. This project has described the design and development of the Cogito tool, which through the use of image processing, element detection and classification is able to identify the elements of a video game menu using a screenshot and perform the necessary input to navigate through that menu. Cogito is divided into two parts: (1) writing a script based on human-like commands such as Go to Settings and (2) visual navigation to run the script. This navigation is mainly focused on detecting outlines of buttons, text and icons, with that information it is able to classify the elements and performs input based on it. This project has been mainly focused on the navigation part of the tool. The development of Cogito started with a prototyping phase in which team members looked for capabilities to implement from other existing tools. Once all the necessary information was gathered, the iterative development process began, with each iteration resulting in an improved version of the tool. This iterative process was strongly based on the SCRUM agile methodology. Cogito started as a proof of concept that over time grew into a project with a lot of potential, which can be worked on further to correctly navigate through a menu as a scripting language for testers to use. Now, Cogito is a tool in development which has been implemented as described throughout this document, implemented on python. It makes use of a potent library for image processing, OpenCV, as well as implements machine learning models using Amazon Web Services for the specific tasks of text detection, icon detection and icon classification. An evaluation of the tool has been done, and it has been determined that it still has lots of room for improvement referring both to quality and times of each step. However, it is clear now which steps need to be more efficient, and which steps need to improve their predictions. After working on the issues mentioned, the tool could significantly improve. 65
66 Chapter 6. Conclusions and Future Work The following section will discuss the improvements that can be applied to Cogito and future work for the tool. 6.1. Future work Although the results obtained are promising, the tool is not perfect. Since it is a proof of concept, there is plenty of room for improvement. A few items about the most important upgrades that can be done would be: Continue developing a separated navigation app that relies on Cogito implementation to understand and store states of the game. This app would run locally where the game is running, and using information provided by the Cogito running on AWS Lambda, it would understand in what menu the game is, which ones are the possible input actions, and how to find a specific text by using labels. An additional use for the tool that does not rely on labeling would be a menu crawler. After obtaining the structure of a menu using visual testing techniques, functional testing ones could be applied over it in order to create a graph that maps each different node from the graph to a specific menu. This would be useful to automatically find out if all the menus before launching a game mode are accessible, which is an important common task done while testing GUIs. Doing more research about possible ways to reduce unproductive waiting times. One way would include a multi thread implementation, as it was mentioned on the time performance conclusions (subsection 5.2.2), that calls the models in parallel while executing the image processing steps on another thread, and then only waiting when it actually reaches the point they are needed. That would allow minimizing the total time for the process, reducing the unproductive waits to zero if the models finish their tasks before reaching the point they are needed. Improve efficiency in some of the most time consuming steps of image processing, such as applying bilateral filters, which can take whole seconds to be applied. A possible way that has not been tested on this project to improve this is using Fourier Transform, a process that is based on the idea of all functions can be approximated as the sum of infinite sinus and cosines. Image operations may be optimized using these transformations. Once the datasets used by Rekognition models have shown good results, these could be converted to the format SageMaker uses. This can be done with a script that was created during the creation of the first SageMaker models, which takes a .lst file and converts it to a .manifest one. The reason to do this is SageMaker allows to have more control of model training. It does not necessarily mean the results are going to be better, since this has been already tried with the general icons model obtaining a worse mAP. Even so, it would be worth trying, but it is not a critical issue right now. Train AWS Comprehend models to be used in combination with the already existing checkers in order to get a better context of the situation of interfaces in video games. This could be used for very specific menus, such as settings, popups, or "press x button to play" menus. These would be good examples of use since the text contained
6.1. Future work 67 in these menus is always very similar, allowing a possible integration of Comprehend within the tool that runs a custom classifier model for these menus. However, it would only work with detailed menus. More abstract menus such as a main menu, which can contain words related to all the menus mentioned before, would not work on this model. Checkers still will have a reason to exist in these cases, which is why a combination of both would give better results.
74 Appendix A. Appendix A - Contributions Creation of scripts to automate the generation of datasets separated on training and test sets for Rekognition and SageMaker images classification models. •Investigation about the use of a graphic annotation tool to obtain labeled files in YOLO .’txt’ format. Configuration of default labels to match the ones of our models. •Automatic detection of labels used on the previous tool to use them directly, without converting the format to another one. •Conversion from ’.txt’ labeled files to ’.lst’ for SageMaker and ’.manifest’ for Rekognition. •Use of AWS S3 service to host the images only once. The upload is done automatically, as well as the deployment of the models when they finish training. Collaborative work on research about OpenCV and its functionalities: •Investigation about the possibility of using simpler solutions such as template matching instead of object detection models. •Investigation of more complex image comparison techniques such as feature extraction or histogram comparison, and for what situations they are more suitable for. •Research about possible solutions to improve canny edge detection, such as morphological operators, and the implementation of canny edge detection applied to every color channel to avoid losing information. •Research about other edge detection solutions like straight lines detectors. •Work on contour filtering to avoid saving non closed shapes as tiled buttons. Collaborative work on grouping tiled buttons based on their alignment, mainly focused on grids. Later this was useful to group elements into specific objects, such as menu bars. Investigation of text classification alternatives such as zero-shot models and other natural language processing techniques. Also investigation about using already existing datasets in order to do fine-tuning to get custom text classification models, instead of building one from scratch. That would require a huge amount of resources that are not reasonable. •At the end the text classification models were discarded since keeping a general approach to test different games opposed having a specific trained model for each game. Training of object detector and image classification models using AWS Rekognition and SageMaker. At the end, SageMaker models were relegated as possible future work. The reason for that is that Rekognition allowed a faster iteration in training models, while SageMaker costed not only more time, but also better fine-tuning. Rekognition also does this automatically. •Training of icon detection models, for which I gathered a large quantity of images and tuned them to improve model confidence to reliable levels. This model only had one label, since it had one specific purpose: finding every icon on the screen, without focusing on their meaning. This included the creation of a script
A.2. Iago Quintas Diz 75 that enhanced icons so the model could learn faster with less data, performing operations such as changing icon sizes, colors, orientations and backgrounds being some of those. •Training of icon classification models, which are less reliable than the detection model. This is due to increasing the number of labels and the lower amount of images appearing on the dataset. Gathering images for specific icons was a much more complex task. In addition to this, it is important to highlight that public icon datasets for the specific icons that are needed do not exist. Evaluation of the tool, planning the different objectives, designing the methodology to do it and analysing the results after that. More specifically, these were the steps done •Adding a simplified telemetry system to the tool to record time events, gathering dataframes for each game tested. Events were sent to a class to perform the time measuring operation, and then each value was stored on their corresponding image and step. •After that, the tool run throughout all images. Then. manually classification of images was done to determine true positives, false positives, true negatives and false negatives. •With the results obtained, graphics and tables were created in order to visualize better the data and reach conclusions faster about what steps have more issues. •Finally, with this information, future work was decided about what steps needed more work to improve and be reliable.