Full text
University of Minho School of Engineering José Carlos Oliveira Martins Omnidirectional Vision: Self-Localization and Object Detection with YOLO Dissertação de Mestrado Mestrado Integrado em Engenharia Eletrónica Industrial e Computadores Trabalho efetuado sob a orientação do Professor Doutor António Fernando Ribeiro Professor Doutor Agostinho Gil Teixeira Lopes june 2024
University of Minho School of Engineering José Carlos Oliveira Martins Omnidirectional Vision: Self-Localization and Object Detection with YOLO Dissertação de Mestrado Mestrado Integrado em Engenharia Eletrónica Industrial e Computadores Trabalho efetuado sob a orientação do Professor Doutor António Fernando Ribeiro Professor Doutor Agostinho Gil Teixeira Lopes june 2024
Copyright and Terms of Use for Third Party Work This dissertation reports on academic work that can be used by third parties as long as the internationally accepted standards and good practices are respected concerning copyright and related rights. This work can thereafter be used under the terms established in the license below. Readers needing authorization conditions not provided for in the indicated licensing should contact the author through the RepositóriUM of the University of Minho. License granted to users of this work: https://creativecommons.org/licenses/by/4.0/ [Esta licença permite que outros distribuam, remixem, adaptem e criem a partir do seu trabalho, mesmo para fins comerciais, desde que lhe atribuam o devido crédito pela criação original. É a licença mais flexível de todas as licenças disponíveis. É recomendada para maximizar a disseminação e uso dos materiais licenciados.] CC BY-SA i
Acknowledgements I express my sincere gratitude to Professor António Fernando Ribeiro, my supervisor, for providing the opportunity to revive the Middle Size League (MSL) team at the Laboratory of Automation and Robotics. His unwavering support, guidance, patience, and availability were indispensable, and none of our achievements would have been possible without him. I am particularly grateful for his belief in our team’s capabilities and his continuous efforts to advance the team and fulfil our objectives. The lasting memory of that heartfelt hug during the last RoboCup match, where we proved our goal-scoring abilities, will stay with me for a lifetime. I extend my thanks to the entire LAR@MSL team, which came together over the past year to relaunch the team. Special acknowledgements to Rui Lima, responsible for low-level communications and robot skills; António Ribeiro, managing robots’ strategy and communication; Rúben Silva, the ”power guy,” overseeing power distribution and goalkeeper localization; Joel Costa, in charge of positioning the robot in goal; and Carolina Lopes, handling ball detection and team management. Without their dedication, skills, and collaboration, our achievements, including heart-stopping penalty kicks in the RoboCup, would not have been possible. Gratitude also extends to the new team members Rui Martins, Rui Pereira, Cláudio, Paulo, and Tiago, for ensuring the team’s continuity in the next RoboCup. I offer a heartfelt thank you to all LAR members, especially Professor Gil Lopes, for supporting us with mechanical aspects and unwavering assistance during the RoboCup. Tiago Ribeiro, a key figure in my academic journey, thank you for your motivation, and support, and for keeping me up with CHARMIE. I would also like to thank Botnroll for all their support and the material provided, without their help the viability of this project would have been uncertain. Special thanks to the TechUnited team for welcoming us to their lab in Eindhoven, facilitating our progress, and enabling the restart of our MSL team. Gratitude to Ruben for being an exceptional host. I also appreciate all other MSL teams for sharing their progress and contributing to the competitiveness of ii
MSL. My deepest gratitude goes to my parents, whose support and belief in my dreams made my journey much smoother. I extend my thanks to my sister for her exemplary motivation. Last but not least, a massive thank you to my girlfriend, who has been my steadfast companion throughout my academic career, providing support, guidance through challenges, and celebration of my achievements. iii
Statement of Integrity I hereby declare having conducted this academic work with integrity. I confirm that I have not used plagiarism or any form of undue use of information or falsification of results along the process leading to its elaboration. I further declare that I have fully acknowledged the Code of Ethical Conduct of the University of Minho. University of Minho, Braga, june 2024 José Carlos Oliveira Martins iv
Abstract RoboCup is an international robotics competition event held annually since 1997, with the aim of advancing the state of the art of robotic intelligence. The Middle Size League is one of the leagues in this event, requiring a large amount of time, effort and resources to develop a robotic football team. This master’s thesis presents a system for self-localization and object detection in a football robot using a catadioptric vision system. For localization, basic computer vision functions are used in conjunction with the value provided by odometry and a Kalman filter. Two methods were tested for real-time object detection: computer vision and YOLOv8 with object segmentation. After testing the localization system, it was found to be easy to implement and capable of having a mean absolute error of less than the robot’s radius itself. An MSL football field is normally 20 meters long by 12 meters wide and the robots have a radius of 25 centimeters. As the error obtained is practically insignificant given the environment in which it is located, it can be concluded that the system is capable of obtaining the location of a robot within a robotic football field. Detecting objects using computer vision, proved easy to implement but requires constant calibration. It was therefore decided to adopt a method that would be more advantageous in the long term through deep learning. YOLOv8 is the solution presented, and small models were trained. The results obtained show that the neural network’s detection improves when it is trained with more images. The model’s final results show a latency of 180 FPS in the object segmentation task with a small neural network. This model has 60% mean average precision (mAP50-95) and 90% mean average precision with 50% confidence (mAP50), as there are only 7200 objects in total for training, this value was higher than expected. The team intended to compete in RoboCup 2023 with less than a year to prepare. The solutions adopted proved to be suitable considering the speed of implementation and also can evolve and be improved, which makes them viable in the long term. Keywords Calibration, Catadioptric Camera, Dataset, gRPC, Instance Segmentation, Kalman Filter, Localization, Middle Size League, Object Detection, Odometry, Omnidirectional Camera, OpenCV, RoboCup, Robotic Football, Self-Localization, YOLO. v
Resumo O RoboCup é um evento internacional de robótica, que ocorre anualmente desde 1997, com o objetivo de progredir o estado de arte da inteligência robótica. A Middle Size League é uma das ligas em competição neste evento, sendo necessário, uma grande quantidade de tempo, esforço e recursos para o desenvolvimento de uma equipa de futebol robótico. Nesta dissertação de mestrado, é apresentado um sistema para auto-localização e deteção de objetos num robô de futebol usando um sistema de visão catadióptrica. Para a localização, são utilizadas funções básicas de visão computacional em conjunto com o valor fornecido pela odometria e um filtro de Kalman . Na deteção de objetos em tempo real foram testados dois métodos: visão por computador clássica e YOLOv8 com segmentação de objetos. Após testes ao sistema de localização chegou-se à conclusão que é um sistema fácil de implementar e capaz de ter um erro médio absoluto menor que o raio do próprio robô. Um campo da MSL normalmente tem 20 metros de comprimento por 12 metros de largura e os robôs tem 25 centímetros de raio. Então o erro obtido mostrou-se desprezável no ambiente onde está inserido, conclui-se que o sistema está apto para obter a localização dum robô num campo de futebol robótico. Na deteção de objetos através de visão por computador mostrou-se fácil de implementar, mas requer calibração constante. Por isso foi decidido adotar um método que fosse mais vantajoso a longo prazo através de aprendizagem profunda. O YOLOv8 é a solução apresentada, tendo sido treinados modelos de tamanho pequeno. Os resultados obtidos comprovam que a deteção da rede neuronal melhora quando treinada com mais imagens. Os resultados finais do modelo mostram uma latência de 180 FPS na tarefa de segmentação de objetos com uma rede neuronal de tamanho pequeno. Este modelo apresenta 60% de precisão média (mAP50-95) e 90% de precisão média com a confiança a 50% (mAP50), como no total só há 7200 objetos para treino, este valor mostrou-se mais satisfatório que o esperado. A equipa pretendia competir no RoboCup 2023 com menos de um ano de preparação. As soluções adotadas mostraram-se adequadas devido à rapidez de implementação, tendo também capacidade de evoluir e serem melhoradas, o que as torna viáveis a longo prazo. Palavras-chave Calibração, Câmara Catadióptrica, Dataset, gRPC, Filtro de Kalman, Localização, vi
23 Orientation Methodology using Histograms (a) Lines acquisition, (b) Scaled lines, (c) Orientated lines using histograms . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 24 TechUnited’srobot .................................. 31 25 Omni-vision software’sflowchart............................ 34 26 Object detection using computer vision flowchart . . . . . . . . . . . . . . . . . . . . 36 27 Object detection using YOLO flowchart . . . . . . . . . . . . . . . . . . . . . . . . . 38 28 Examples of auto annotation failures . . . . . . . . . . . . . . . . . . . . . . . . . . 42 29 Self-localization’s flowchart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 30 Get Scaled Field flowchart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 31 RotateandOutsideClean............................... 46 32 Kalman filter input and output in practice . . . . . . . . . . . . . . . . . . . . . . . 47 33 Calibration tool - Center calibration . . . . . . . . . . . . . . . . . . . . . . . . . . 48 34 Calibration tool - HSV calibration . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 35 Calibration tool - Map calibration . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 36 Createlookuptable.................................. 51 37 Calibration tool - Field calibration . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 38 Fields generated by the Calibration Tool - (a) LAR field, (b) Portuguese Open field, (c) RoboCupfield..................................... 52 39 (a) Board and enclosure 3D model, (b) Board layout design, (c) Board final result . . . . 54 40 (a) Camera support 3D model, (b) Camera support final result . . . . . . . . . . . . . 55 41 (a) Robot top 3D model, (b) Display interface . . . . . . . . . . . . . . . . . . . . . 56 42 YOLO box precision with different network sizes . . . . . . . . . . . . . . . . . . . . 58 43 YOLO mask precision with different network sizes . . . . . . . . . . . . . . . . . . . 58 44 YOLO inference time with different network sizes . . . . . . . . . . . . . . . . . . . 59 45 YOLO Resolution - Inference time comparison . . . . . . . . . . . . . . . . . . . . . 59 46 Robotreceiveandpass................................ 60 47 Robotreceiveandkick ................................ 60 48 (a) Ball detection in the penalty circle, (b) Annotation examples to remove field circles detection (c) Detection after new annotations . . . . . . . . . . . . . . . . . . . . . 61 49 (a) Segmentation with the first model, (b) Segmentation with the seventh model, (c) Segmentation with the tenth model . . . . . . . . . . . . . . . . . . . . . . . . . . 62 xiii
50 FinalYOLOv8predition ................................ 63 51 Dataset labels information - (a) Class balance, (b) Object distribution, (c) Object size distribution...................................... 64 52 Precision-recall curve graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 53 Traininglosscurve .................................. 66 54 Confusiongraph ................................... 67 55 Time comparison of Unary and Stream gRPC . . . . . . . . . . . . . . . . . . . . . 68 56 Comparison of resolution and latency for template matching .............. 69 57 Comparison of different curve approximations . . . . . . . . . . . . . . . . . . . . . 69 58 Comparison line detection methods - (a) Direct, (b) Without spacing, (c) 3-pixel spacing, (d) 5-pixel spacing, (e) 8-pixel spacing . . . . . . . . . . . . . . . . . . . . . . . . . 72 59 Self-Localization processing time . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 60 Unexpected variations in CMPS14 data . . . . . . . . . . . . . . . . . . . . . . . . 74 61 Comparison between vision, encoders and Kalman localization . . . . . . . . . . . . . 75 62 Sequential robot’s point of view during data collection . . . . . . . . . . . . . . . . . 76 63 Representation of the test to obtain the self-localization error . . . . . . . . . . . . . . 77 64 Self-localization error throughout the frames . . . . . . . . . . . . . . . . . . . . . . 77 65 Base Station representing robots and ball position . . . . . . . . . . . . . . . . . . . 78 66 (a) Game situation to obtain ball localization error (b) Illustration provided by Base Station 79 67 Robots entering the field at RoboCup . . . . . . . . . . . . . . . . . . . . . . . . . 80 68 Box Precision-recall curve graph of first train session . . . . . . . . . . . . . . . . . . 89 69 Mask Precision-recall curve graph of first train session . . . . . . . . . . . . . . . . . 89 70 Confusion matrix of first train session . . . . . . . . . . . . . . . . . . . . . . . . . 90 71 Loss graphs of first train session . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 72 Labels analysis of first train session . . . . . . . . . . . . . . . . . . . . . . . . . . 92 73 Validation labels of first train session . . . . . . . . . . . . . . . . . . . . . . . . . . 93 74 Validation Predict of first train session . . . . . . . . . . . . . . . . . . . . . . . . . 94 75 Box Precision-recall curve graph of seventh train session . . . . . . . . . . . . . . . . 95 76 Mask Precision-recall curve graph of seventh train session . . . . . . . . . . . . . . . 95 77 Confusion matrix of seventh train session . . . . . . . . . . . . . . . . . . . . . . . 96 78 Loss graphs of seventh train session . . . . . . . . . . . . . . . . . . . . . . . . . . 97 79 Labels analysis of seventh train session . . . . . . . . . . . . . . . . . . . . . . . . 98 xiv
80 Validation labels of seventh train session . . . . . . . . . . . . . . . . . . . . . . . . 99 81 Validation Predict of seventh train session . . . . . . . . . . . . . . . . . . . . . . . 100 82 Box Precision-recall curve graph of tenth train session . . . . . . . . . . . . . . . . . 101 83 Mask Precision-recall curve graph of tenth train session . . . . . . . . . . . . . . . . 101 84 Confusion matrix of tenth train session . . . . . . . . . . . . . . . . . . . . . . . . 102 85 Loss graphs of tenth train session . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 86 Labels analysis of tenth train session . . . . . . . . . . . . . . . . . . . . . . . . . 104 87 Validation Labels of tenth train session . . . . . . . . . . . . . . . . . . . . . . . . . 105 88 Validation Predict of tenth train session . . . . . . . . . . . . . . . . . . . . . . . . 106 89 Finaldatasetexamples ................................107 90 (a) Wheel 3D parts, (b) Wheel final result . . . . . . . . . . . . . . . . . . . . . . . 134 91 (a) Calibration roller 3D model, (b) Rollers second iteration 3D model, (c) Rollers final iteration 3D model, (d) Rollers final result . . . . . . . . . . . . . . . . . . . . . . . 135 92 (a) Battery enclosure 3D model, (b) Battery final result . . . . . . . . . . . . . . . . . 136 93 (a) Computer support, (b) Computer support on goalkeeper . . . . . . . . . . . . . . 136 xv
List of Tables 1 Computers’specifications............................... 8 2 YOLOv8 - Main arguments to training . . . . . . . . . . . . . . . . . . . . . . . . . 18 3 YOLOv8 - Main arguments to prediction . . . . . . . . . . . . . . . . . . . . . . . . 18 4 Comparison of training parameters . . . . . . . . . . . . . . . . . . . . . . . . . . 40 5 Comparison of the errors obtained when approximating the curves that convert pixels intorealdistances. .................................. 70 6 Comparison line detection methods. . . . . . . . . . . . . . . . . . . . . . . . . . . 71 7 Error obtained in the localisation of objects already filtered and merged by Base Station . 79 8 RoboCup failures throughout matches . . . . . . . . . . . . . . . . . . . . . . . . . 81 xvi
Acronyms AMCL Adaptive Monte Carlo Localization CMPS14 Tilt Compensated Magnetic Compass CPU Central Processing Unit FPS Frames Per Second GigE Gigabit Ethernet GK Goalkeeper gRPC Google Remote Procedure Call GTX Giga Texel Shader eXtreme HSV Hue Saturation Value I2C Inter-Integrated Circuit IPC Inter-Process Communication LAR Laboratory of Automation and Robotics LAR@MSL Laboratory of Automation and Robotics at Middle Size League LIDAR Light Detection And Ranging MSL Middle Size League NPU Neural Processing Unit PLA Polylactic Acid PWM Pulse Width Modulation xvii
RCT Robot Club Toulon RTX Ray Tracing Texel eXtreme SLAM Simultaneous Localization and Mapping ToF Time-of-Flight TPU Tensor Processing Unit YOLO You Only Look Once xviii
Chapter 1 Introduction This chapter provides an overview of the key concepts, problem statement, aims and objectives, solution approach, and contributions of this master’s dissertation. It serves as the foundation for understanding the project’s context, motivations, and the methodologies employed to address the challenges in robotic football. 1.1 Background Self-localization and object detection are crucial for any robot operating in an unknown environment, as they allow the robot to orient itself and navigate the surroundings. In robotic football, self-localization and object detection are necessary for a robot to move around the field and respond to game situations. The most commonly used devices for these tasks are cameras, but other sensors, such as Light Detection And Ranging (LIDAR), encoders or compass, can also be used. 1.2 Problem Statement A group of six decided to restart the LAR@MSL team, which had not competed since 2015. In other words, both the hardware and the software were deprecated. It was therefore decided to make new software from scratch. The proposed problem is to develop software, on the robot, that not only obtains the coordinates and the robot’s orientation itself, but also the coordinates of all the elements in the field. All the software should be based on a catadioptric vision system, already implemented by the old teams. It has been established that the average localization error should not exceed the robot’s radius, which is 25 centimetres. In terms of object detection, there are not as many restrictions in terms of precision, because there is a front camera dedicated to skills that require more precision. Even so, object detection must be able to obtain the position of each object. Additionally, the team had in mind participating in RoboCup 1
2023, which was only ten months away when the project started. 1.3 Aims and Objectives The main aim of this master’s dissertation is to develop a system for self-localization and to obtain elements’ position in a football field using a camera and a catadioptric mirror. The objective is to accurately locate and track the position of a robot football player, as well as all the objects on the field. To achieve this aim, a camera and a catadioptric mirror are used to track all elements on the field using different algorithms and techniques. The goal is to be able to adapt easily to any field and be robust. It should be easily integrated with the other programmes involved. This allows the team to compete in RoboCup 2023. 1.4 Solution Approach To achieve the aim and objectives of this master dissertation, the following solution approach is adopted. A camera is placed on the robot and facing upwards to capture the field’s images. A catadioptric mirror is placed facing the camera to reflect the field’s image to the camera, creating a 360-degree field view. These images are processed using image processing algorithms to perform self-localization and tracking of objects on the field. For the robot’s self-localization, several methods are tested, including odometry, Template Matching and Kalman filter. The Kalman filter can be used to combine the outputs of different localization methods and filter out any noise or errors. For object detection, two algorithms are evaluated. The first is simple blob detection, which is the quickest solution to test, allowing the ball to be detected so that other members already have the data to orientate the robots towards the ball. The second is You Only Look Once (YOLO)v8, which is a long-term solution, as it requires a lot of game situation data. These methods are tested and compared to determine the best approach for self-localization and the system’s object detection. The processing time and accuracy of the different methods are measured and analyzed to identify the best solution for the problem. These tests include not only testing in a laboratory environment but also in real competitions such as robotics events, the Portuguese Open and RoboCup. 2
1.5 Summary of contributions and achievements The main contributions of this work are: • The development of a system that can accurately locate and track the position of a robot football player on the field. This system combines different methods for self-localization, including odometry, Template Matching , and uses a Kalman filter to improve localization accuracy. • The development of a system that can accurately track the ball, team’s robots, opponent’s robots, goals posts, and humans on the field. This system compares the performance of two different methods for object tracking: YOLO and simple blob detection. • The creation of documentation and source code that serves as a support not only for the next members of the Laboratory of Automation and Robotics (LAR) team but also for other teams competing in the MSL. The main achievements of this master’s dissertation are: • The successful detection of all elements in an MSL field, even distinguishing between the team and the opponent’s robots. • The design and implementation of a self-localization method using classical computer vision methods. • The evaluation of different algorithms for self-localization and tracking, and identification of the best approach for the problem. Overall, this master’s dissertation represents a significant contribution to robotic football self-localization and object detection, and it provides valuable insights and recommendations for future research and development in this area. 3
1.6 Document’s organization The document is divided into the following chapters: • Chapter 2 describes the essential theoretical foundations and contextualises previous work within the framework of MSL. • Chapter 3 presents the project’s development. • Chapter 4 analyses the tests and results obtained. • Chapter 5 discusses the conclusive findings and outcomes of this project. 4
Python Service C++ Service Python Service gRPC Server gRPC Client gRPC Client Proto Response gRPC Stream gRPC Request Computer 1 Computer 2 gRPC Request Figure 4: Communication between processes with gRPC This approach offers advantages such as language independence, efficient serialization, and the ability to define service methods and message types clearly. gRPC communicates in a way that is both flexible and performant, making it a valuable tool for building scalable and interoperable distributed systems. 2.2.3 Object Detection Some tools and software were used to detect objects, which need to be explained to also clarify some important concepts for understanding this project. 2.2.3.1 RoboFlow RoboFlow [6] is an important web-based tool designed to help manage datasets. This versatile platform gives users the ability to handle datasets effortlessly and offers perfect options for exporting them in various formats. RoboFlow’s user-friendly interface and powerful functionalities make it an indispensable asset for data management, meeting diverse needs with efficiency and ease. Annotation RoboFlow contains a large range of annotation tools designed to simplify the annotation process. Achieving precise outlines, particularly for objects with consistent colours such as a ball, becomes notably straightforward using these tools. For a visual representation of the annotation user interface, refer to 11
Figure 5. This figure provides a glimpse into the efficient and user-friendly annotation capabilities offered by RoboFlow. Figure 5: Roboflow’s annotation Dataset Health This web tool extends its functionality to include dataset health analysis, with a critical focus on aspects like class balance. In Figure 6, visual tools’ representation analysis results are presented. Notably, the illustration highlights the disparity in representation among classes, particularly in the blue_shirt and red_shirt categories. This insightful output serves as a valuable indicator, guiding users to identify and address the underrepresented classes in their dataset for comprehensive and balanced training. 12
Figure 6: Roboflow’s dataset health Roboflow’s heatmap tool provides users with a visual representation of class distribution across the dataset. As depicted in Figure 7, the heatmap reveals a spatial arrangement aligning with the omnidirectional camera’s perspective. It is noticeable a concentration of objects is observed in the frontal robot’s region. This feature equips users with valuable insights into the dataset, aiding in the understanding of class distribution patterns and spatial prevalence within the captured images. Figure 7: Roboflow’s heat map Dataset Generator The dataset generator within RoboFlow emerges as an extremely relevant tool, offering functionalities crucial for dataset refinement and enhancement. •Split Dataset Figure 8 illustrates the capability to balance image distribution for training (2.2.3.2), validation (2.2.3.2), and testing (2.2.3.2). 13
Figure 8: RoboFlow’s split dataset •Preprocessing Enabling adjustments to image attributes, the preprocessing tool facilitates tasks like resizing images uniformly. Figure 9 presents a comprehensive list of options, providing users with flexibility in preparing images to meet specific size requirements. Figure 9: RoboFLow’s preprocessing options •Augmentation Augmentation is a powerful strategy for dataset enrichment and involves creating variations in original images. As highlighted in Figure 10, RoboFlow’s free plan allows users to triple their dataset. 14
Figure 10: RoboFLow’s augmentation options To enhance sensitivity to light variations, manipulating key components such as hue, saturation, and brightness becomes essential. Figures 11a, 11b, and 11c exhibit the impact of varying these components, representing the HSV (Hue Saturation Value) channels. Additionally, Figure 11d demonstrates exposure variation, responsive to changes in the camera’s exposure. This array of augmentation options allows users to effectively diversify datasets. 15
(a) (b) (c) (d) Figure 11: (a) Hue augmentation, (b) Saturation augmentation, (c) Brightness augmentation, (d) Exposure augmentation •Dataset Export The web tool provides extensive flexibility in exporting the generated dataset, supporting a diverse range of formats. Figures 12a and 12b showcase the user interface, illustrating the ease with which users can select the desired format and customize their download preferences. This feature ensures compatibility with various platforms and tools, enhancing the accessibility and dataset’s usability across different applications. 16
(a) (b) Figure 12: (a) Dataset export format GUI, (b) Dataset download GUI 2.2.3.2 YOLOv8 The integration of deep learning-based object detection algorithms, such as YOLO, has been explored for effective object detection on the football field. YOLO, a convolutional neural network-based algorithm, excels in real-time object detection and classification. YOLOv8 is the latest iteration of object detection algorithms and is significant in this project. Therefore, it is necessary to explore some theoretical aspects associated with YOLOv8. Using YOLO for object detection and tracking offers relevant advantages, including high accuracy and efficiency. It is crucial to acknowledge certain limitations associated with YOLO. The computational resources are high and can be a challenge for robots with limited processing capacity. Additionally, the implementation of YOLO requires significant training data, contributing to a slow training process. YOLOv8 Modes In YOLO, there are three main steps: to train, to validate, and to predict. Each mode corresponds to a specific set of images, with a standard dataset division of 70% for training, 15% for validation, and 15% for testing. •Train Training serves the purpose of preparing the model, requiring a sufficient amount of data for optimal performance. While a larger dataset enhances the model’s capabilities, it concurrently extends the training duration. Key arguments, detailed in Table 2, allow for precise training process customization. 17
Table 2: YOLOv8 - Main arguments to training Argument Default Description model None path to model file, i.e. yolov8s.pt, yolov8s-seg.pt data None path to data file of the dataset, i.e. data.yaml epochs 100 number of epochs to train patience 50 epochs to wait for no observable improvement for early stopping of training imgsz 640 size of input images in pixels (imgsz x imgsz) save True save train checkpoints and predict results device None device to run on, i.e. cuda device=0 or device=0,1,2,3 or device=cpu lr0 0.01 initial learning rate (i.e. SGD=1E-2, Adam=1E-3) lrf 0.01 final learning rate (lr0 * lrf) val True validate/test during training plots False save plots and images during train/val •Validation Validation is essential to assess the model’s viability and allows continuous monitoring network’s evolution. Additionally, the save plots option can be activated during training, generating graphs ideal for model analysis and error detection. •Predict The predict mode allows the trained model’s utilization for object detection in images, whether captured by a camera or sourced from a computer file. It is essential to use the same settings for prediction as those employed during training to ensure consistent results. The frequently used arguments are as demonstrated below in Table 3. Table 3: YOLOv8 - Main arguments to prediction Argument Default Description source ’ultralytics/assets’ source directory for images or videos conf 0.25 object confidence threshold for detection (25%) iou 0.7 intersection over union (IoU) threshold for NMS imgsz 640 image size as scalar or list (h, w), i.e. (480, 640) device None device to run on, i.e. cuda device=0/1/2/3 or device=cpu max_det 300 maximum number of detections per image visualize False visualize model features 18
YOLOv8 Tasks In YOLO, three primary tasks guide its functionality: Classification, Detection, and Segmentation. The selection of a task depends on the specific needs of each project. •Classification It serves the purpose of identifying the classes present in the camera’s view. This is particularly useful in industrial settings where objects’ knowledge in front of the camera is essential, even without precise positional information. However, classification might be insufficient for projects requiring object position data. •Detection It is represented by bounding boxes and it is the most widely employed task. It provides coordinates for the bounding box, allowing extraction of key points such as the centre, highest point, lowest point, leftmost point, and rightmost point. In catadioptric systems, obtaining precise bottom contours is crucial to determining the position of an object on the ground, which in certain situations is inaccurate with detection. •Segmentation In addition to providing the bounding box, instance segmentation provides all detected objects’ contours. This increases the accuracy of determining the object’s position relative to the ground. The output from segmentation can be interpreted either as a mask or as a list of points, offering detailed insights into the object’s spatial relationships. Figure 13 illustrates the comparison between the bounding box and the mask, highlighting the disparity in accuracy at the location nearest to the centre, which is the object’s closest point at the ground. 19
Bounding box closest point Mask closest point Robot / Image centre Bounding box centre Figure 13: YOLO bounding box in comparison with mask 2.2.4 Localization The robot self-localization method uses odometry and classic computer vision. Subsequently, the data collected from these two components is filtered through a Kalman filter. Therefore, it is necessary to acquire some knowledge involving these three concepts. 2.2.4.1 Odometry Odometry is a method of self-localization that involves the use of sensors such as IMU and encoders to measure the robot’s movement and estimate its location within the football field. This can be carried out by measuring the distance travelled by the robot’s wheels, as well as the robot heading direction. In the case of an omnidirectional robot with three wheels arranged in a triangle with 120-degree angles between them [7], the wheels’ movement can be used to calculate the robot’s direction and distance travelled. Figure 14 shows the wheels’ arrangement on the robot. 20
(a) (b) Figure 20: (a) Falcons’ Omni-camera setup, (b) Image taken by a single Raspberry camera 2.3.3.3 Vision + LIDAR As shown in Figure 21, Robot Club Toulon (RCT) team adopted a distinct approach compared to other teams, using a high-performance LIDAR to achieve precise object detection on the field, excluding the ball, with an impressive accuracy of 1 cm, as reported by the team [18]. Complementing this, they incorporated four cameras, each equipped with an embedded Coral Tensor Processing Unit (TPU) and a Neural Processing Unit (NPU). This setup allows the execution of a neural network directly on each camera. 27
LIDAR Cameras Figure 21: RCT’s robot 2.3.4 Object Detection Within the MSL context, acquiring real-time positional information for all involved objects is fundamental. Various solutions address this challenge, and it is noteworthy that each of them relies on the utilization of cameras, with optionally the use of another type of sensor to improve accuracy. 2.3.4.1 Computer Vision Established teams with several years of experience in the league persist in utilizing colour segmentation methods on images to extract elements from the field. This continued reliance is facilitated by the robust data fusion system and the distinguishable colours present on the field. The long-standing use of this method for object detection by veteran teams has resulted in a comprehensive system built around it. Transitioning to alternative methods would pose significant challenges, requiring extensive testing and adjustments across various aspects of their existing setups. 28
2.3.4.2 YOLO The versatility of YOLO [4, 19] allows its implementation in any robotic context, thanks to its diverse modes and network sizes. By utilizing a customized dataset, it becomes feasible to train a network specifically for detecting the desired elements. LAR Prior Projects Some projects in the lab had already tried to detect objects with a personalised [20] network. This project proved to be very accurate and enables real-time detection. Figure 22 shows the detection in YOLOv3. Although the context is not MSL, the accuracy obtained is very satisfactory for a customised network. In the example shown, only bounding boxes were used to obtain the object’s margins, as the orientation of the objects is not relevant in this case. This project proves the concept and its documentation makes it easy to understand YOLO. Figure 22: Example of YOLOv3 detection RCT In the domain of object detection, the RCT team sets itself apart by employing a combination of LIDAR data and a camera-based algorithm. This unique approach enables the team to filter out all field elements, excluding the ball, which improves the precision of acquired coordinates. The ball’s position is determined exclusively through camera-based object detection, as the LIDAR’s elevation prevents direct ball detection. The RCT team utilizes the YOLOv3tiny algorithm [21], a streamlined variant of YOLOv3 featuring a smaller neural network. This design enables on-camera prediction capabilities, leveraging dedicated hard- 29
ware such as Tensor Processing Unit (TPU) and NPU. 2.3.5 Self-Localization All MSL teams try to achieve precise positioning for each robot on the football field, enabling the formulation of strategic game plans. 2.3.5.1 LAR Prior Work In a previous MSL iteration, the LAR team employed a histogram-based method to ascertain the robot’s heading [22]. Figure 23a illustrates the process: field lines are obtained, and the results in the original orientation are represented in Figure 23b, accompanied by respective horizontal and vertical histograms. The most probable orientation, determined by the highest value on the histograms, is depicted in Figure 23c. Historically, challenges arose from electric cables beneath the field, causing magnetic interference which prevented the use of a compass for self-localization and tracking. (a) (b) (c) Figure 23: Orientation Methodology using Histograms (a) Lines acquisition, (b) Scaled lines, (c) Orientated lines using histograms 2.3.5.2 TechUnited The team undertook a visit to the Technical University of Eindhoven, where they engaged with the laboratory of TechUnited, the current MSL world champion. This visit played a crucial role in acquiring insights into TechUnited’s internal management practices and attending their team meetings. Subsequently, the team engaged with TechUnited members to address specific queries related to the ongoing project. 30
This collaborative interaction facilitated a valuable exchange of knowledge and insights, enriching the understanding and management team’s practice by aligning them with the experiences of a world-leading MSL team. Figure 24 shows a robot from the world champion team. Figure 24: TechUnited’s robot Their self-localization strategy looks like a scan match, where they overlay a line map obtained from each robot onto the original field to verify its current position. Unlike LAR, TechUnited relies on encoders to measure wheel movement and does not use the compass for orientation due to potential magnetic field disruptions on the football field. Instead, they use vision-based methods for precise orientation determination [23]. This information did not change the LAR team’s chosen sensor, which incorporated a compass and gyroscope with an internal Kalman filter. TechUnited, when presented with the idea of implementing self-localization through template matching, 31
considered the approach interesting. They emphasise the easy development while acknowledging the associated higher latency. TechUnited highlighted that precision was not a critical requirement for their self-localization and the significance of combining the locations of allied robots to improve accuracy. While acknowledging the potential utility of neural networks, the LAR team took a practical step by capturing videos from the robot’s perspective. This initiative aimed to create diverse datasets for potential neural network-based object detection methodologies in the future, ensuring comprehensive data availability to enhance model effectiveness. 2.3.5.3 RCT Utilizing high-precision, wide-range LIDAR technology, the RCT team achieves self-localization by leveraging data from the goalposts. The process involves data fusion, as detailed in Section 2.3.4.2. In instances where goalposts are not detected, the robot seamlessly relies on odometry data to ascertain its position. 2.4 Conclusion The catadioptric vision system is a good solution because with a single camera, it is possible to get a 360- degree environment’s view. However, this approach can cause deformation in the image and the elements to be detected. Another disadvantage is that traditional box detection methods, which are usually vertically orientated, cannot be used due to the radial representation of objects. It is necessary a system that detects contours to achieve greater precision. Concerning object detection, it can be concluded that the older teams have not yet fully integrated detection systems using neural networks, which is because they all already have a consolidated robot’s behaviour and the system’s dependence on their detection. However, the use of neural networks is the most plausible way forward, specifically YOLO. RoboFlow has also proved to be a very useful tool for managing datasets. Regarding self-localization, it can be concluded that, apart from the RCT team, the teams use traditional vision to obtain the field lines and use comparison methods close to scan matching or template matching. It is also noticeable that all teams complement with other types of sensorisation, such as LIDAR, odometry and compass. 32
Chapter 3 Development 3.1 Introduction In Chapter 3, the algorithms are separated into individual modules and explained in such a way as to ensure a comprehensive understanding of the final algorithm. This not only aids clarifying the process but also significantly eases the acquisition of essential information for teams that follow. The detailed presentation of these core algorithms serves to enhance collaboration and knowledge transfer and a smoother transition for subsequent teams involved in the project. This chapter describes the development process, and the core algorithms integral to individual segments. The software’s implementation, self-localization, and object detection methods like Blob Detection and YOLOv8 are explored. The integration of a calibration tool stands out as an important component and helps the process of adjusting key variables for optimal performance. 3.2 Omni-Vision Software The Omni-Vision software is integrated with the project as explained in Section 2.2.2, and it is only necessary to read and write from the Local Database. Figure 25 shows the general flowchart of the Omni-Vision software. It can be seen that the first predefined processes are the initialisation of variables and communications. Given the field’s symmetrical nature, it is necessary to provide information indicating which field’s side the algorithm is positioned on. The strategy employed involves to orientating the robot towards the goal it intends to attack, with the Base Station supplying information about the field’s side. This approach proves beneficial in game situations and test scenarios where only half of the field is available, allowing the robot to attack its own goal if needed. The colour of the team’s jersey is also obtained to distinguish robots from the team itself and its opponents. Next, the absolute location of the robotic football field needs to be obtained. To do this, Global Local- 33
ization is used, which is a crucial aspect that considers the location of the entire field. This process is only carried out ten times at the programme’s start, and an average is calculated based on these ten points. It turned out that running ten times was enough to get the correct starting position because occasionally one of the points deviated from the real value and ten points are enough to reduce these deviations. Object Detection also needs to be run in this cycle as it is the function responsible for collecting the image. Once the ten localization points have been obtained, they must be averaged and the Kalman filter started. The programme then enters the cycle where it stays in permanent mode. Figure 25: Omni-vision software’s flowchart The cycle begins by obtaining the image and detecting objects, which is carried out in Object Detection. With the image obtained, Close Localization can be used, allowing localization within a maximum radius of two metres between frames, which allows for a shorter execution time, as shown in the 4.4.1 section, and reduces false localization due to similarities between parts of the field. It also uses the encoder data obtained from the Local Database. Close Localization aims to iteratively return the robot’s absolute position and orientation in the field, as explained in the section 3.4. When these two processes are finished, all that remains is to save all this data in the Local Database. Initially, this data was stored with absolute 34
coordinates. Still, as almost all processes on the robot use relative localization, it was decided that the conversion to absolute would be carried out by the Base Station . So except for the robot’s own location, all the others were stored with coordinates relative to the robot. 3.3 Object Detection At the development’s beginning process, the computational performance of the computers used was relatively low. Consequently, traditional computer vision solutions emerged as the most feasible option. The limitations inherent in computing power meant that conventional methodologies had to be used, which are usually less demanding from a computational point of view, but effective in carrying out simple visual perception tasks. These traditional computer vision methods typically included techniques such as edge detection, corner detection, and image segmentation, as they were computationally lighter and compatible with the hardware constraints present at the time. While these approaches might lack the sophistication and accuracy of modern deep learning methods, they were the cornerstone of early vision systems due to their efficiency on limited computational resources. 3.3.1 Blob Detection Blob detection, a straightforward approach in computer vision, is implemented using OpenCV [24] functions. However, its sensitivity to environmental changes requires constant recalibration. Although effective for quick application, this method does not distinguish between objects of the same type nearby. For example, if two robots are adjacent, the algorithm identifies them as a single entity. This simplicity poses challenges in scenarios with densely clustered or visually similar objects, limiting practical applicability without continuous adjustments and calibration. Despite its limitations, this object detection was crucial at the project’s start, allowing team members to obtain the ball’s position when a suitable dataset was unavailable. To do this, the first step is to obtain the image, which is also used for self-localization (section 3.4). Then the HSV channels need to be filtered, resulting in a monochromatic image with only the pixels on the selected tonal ranges (in white), as shown in Figure 26. Next, OpenCV’s SimpleBlobDetector function is used to obtain the contours of each pixel cluster. The ball used in the tests by the other members is the one closest to the robot, so it was decided to choose the blob closest to the image’s centre, representing the ball closest to the robot. The point of contact between the ball and the ground is then required. To do this, the point closest to the centre of the 35
image is found on the contour obtained. The pixel’s coordinates obtained are converted to real distances using the lookup table. Object Detection (Blob Detection) HSV filter SimpleBlobDetection Get Closest Blob Get Contour Closest Pixel Return Image and Object Coordinates (in pixels) Get Image Figure 26: Object detection using computer vision flowchart 3.3.2 YOLOv8 Due to the high calibration requirements and vulnerability inherent in traditional vision methods, the decision was taken to employ neural networks for object detection in the field. This approach distinguishes between opponent robots, own team robots, and humans. Additionally, it facilitates the detection of goalposts, which presents a challenge using traditional methods due to their colour similarity with the field lines. The chosen algorithm for this purpose was YOLOv8, which, at the time, was not only the most current but also offered the best compromise between latency and accuracy [25]. 36
the Template Matching process substantially shorter, as the tests in Section 4.4.4 show. This region of interest is 180x180 pixels, meaning the robot has a margin of one metre on either side to move between frames. Template Matching provides the field image of the real coordinates in pixels, which are then converted into real coordinates in millimetres for the Kalman filter. To ensure data stability, a Kalman filter is applied, as explained in Section 3.4.3. The final output includes filtered actual coordinates, in centimetres, contributing to the overall system’s accuracy. Close Localization Filter HSV Get Scaled Field Rotate and Clean Template Matching Kalman Filter Return Angle and Coordinates Region of Interest ROI Template Matching ROI 2x2m Figure 29: Self-localization’s flowchart 3.4.1 Get Scaled Field As the filtered image has distorted lines, it is necessary to place them at scaled distances. Figure 30 shows the flowchart for converting the filtered image into a scalar image. The process begins by identifying the line transitions (in this case: green, white, green) horizontally in the filtered image. To optimise computational 43
efficiency, this operation is performed every five lines. The red arrows represent the locations where transitions are horizontally searched. Once a white line is detected, the midpoint coordinates (red dot) are used to get to real distances using the lookup table. Afterwards, a white pixel is placed on the final image at a real distance from the robot. This process is also carried out vertically. To reduce noise, a maximum and minimum width margin of the detected line was selected, for example, if the detected line is larger than 30 pixels it no longer saves that transition, because the maximum width detected is 25 pixels. This method reduces the noise caused by external light, which is significant. The lines detected by the robot are represented, and subsequent comparison with the full field is possible. This method allows the detection of lines behind obstacles, without the need for any extra equations such as radial [26] or spiral [27]. Get Scaled Field Verify Horizontal Transitions in Index Line Return Scaled Field Index > 480? Index = 0 Index = Index + 5 Verify Horizontal Transitions in Index Column Horizontal Transition? Save Pixel in Scaled Image Get Lookup Table Vertical Transition? Save Pixel in Scaled Image Get Lookup Table 5 pixels Line middle points Yes Yes No No Yes No Figure 30: Get Scaled Field flowchart 44
3.4.2 Rotate and Outside Clean Template Matching is insensitive to rotations, necessitating the actual robot angle to pre-rotate the image before Template Matching . Moreover, a global understanding of the robot’s orientation is crucial. Initially, the algorithm included the CMPS14 sensor. The value obtained from this is used as the robot’s current angle. In turn, the robot’s current angle is used to rotate the scaled field obtained, preparing it for Template Matching . After several tests in different environments, it was decided to remove the CMPS14 data from the algorithm, as explained in Section 4.4.5. Then, a technique previously employed by the LAR@MSL team is used (described in Section 2.3.5.1). This involves rotating the image at various angles and identifying the position with the most horizontal and vertical lines using a histogram. This method aims to obtain the angle difference for the previous frame, which is then added to the robot’s current angle. Figure 31 shows the flowchart of this process, it starts by rotating the image to the latest angle of the robot. The image is not perfectly orientated and there is a lot of noise outside the field lines. Then, the entire outside of the field is removed based on the previous position with a one-metre margin so as not to obscure the field lines. This image is then rotated at various angles and the maximum values of the horizontal and vertical histograms are added. The correct orientation is considered when the sum of these values is maximum. Then this deviation found in the angle is added to the last value of the robot’s angle and the correctly orientated image is returned. In other words, the image is ready to be compared with the real field and the robot’s actual angle is obtained. 45
Rotate and Clean Outside Rotate to Lastest Angle Clean Outside Field Rotate to Index Return Orientated Scaled Field and Actual Angle Histograms Index ≥ 10? Index = -10 Index = Index + 1 Get Best Histogram Yes No Figure 31: Rotate and Outside Clean 3.4.3 Kalman Filter To improve the odometry value with computer vision localization, a Kalman filter is combined with. Figure 32 shows the inputs and outputs of the Kalman filter. The computer vision-based localization is used as a noisy input ( ˆ Zk), so it requires filtering. The encoder values are in millimetres (Uk), representing the actual distance travelled by the robot since the last frame. The constant matrices A(state transfer), B(control) and H(observation) are identity matrices. The matrix Qwhich is the process noise covariance matrix, was set to a value of 0.5. The Rmatrix, which is the measurement covariance matrix, is considerably higher (3000) because the computer vision localization value needs a lot of filtering. The values of Qand Rare adjusted to remove some noise from the computer vision localization and allow for rapid updating with the value of the encoders. Finally, the actual filtered coordinates are returned, in millimetres, which are then converted into centimetres. 46
Encoders Kalman Filter Vision Zk Final Localization X k Uk X -k-1 A, B, H Q 0.5 0 0 0.5 1 0 0 1 R 3000 0 0 3000 Figure 32: Kalman filter input and output in practice 3.5 Calibration Tool Calibration stands as a cornerstone in computer vision, necessitating the development of an efficient tool. This tool was developed in Python. The primary objective is to facilitate visual adjustments to key variables and subsequently save them within a ”.go” file as constants. Through this approach, the main program can quickly access these calibrated values since it doesn’t require any additional calculations. This application is divided into tabs to facilitate access to different calibration tasks. Moreover, this calibration tool not only speeds up the adjustments but also significantly improves the accuracy and performance of computer vision systems. By allowing for rapid fine-tuning and storage of essential parameters, it ensures precise and efficient operations, thereby contributing to improved overall system reliability and functionality. Given the frequent robots’ disassembly during the project’s development, the camera’s recalibration and the associated variables presented are simplified by this tool. 3.5.1 Center Calibration Aligning the camera perpendicular to the mirror and keeping the entire support structure parallel to the ground was no easy task. To facilitate this process a tab was developed with the specific aim of verifying the alignment of the camera’s centre with the mirror and identifying any potential camera rotation. In Figure 33 it is possible to see an example of misalignment between the camera and the mirror, which is easily detected with this tool. 47
Figure 33: Calibration tool - Center calibration 3.5.2 HSV Calibration Within this calibration software’s tab, the use of trackbars enables precise tuning of HSV boundaries for all objects and lines present in the field. The primary objective is to highlight only the desired object in white on the image to the right, as illustrated in Figure 34. Additionally, variables are incorporated to fine-tune camera settings, including exposure, gain, and saturation. This integration simplifies the process of optimizing the image, ensuring ideal conditions for accurate object differentiation. This task proved indispensable during the project for detecting lines and, initially, for detecting the ball, This tab also changed some camera variables that contributed to enhanced line distinction and improved the precision of YOLO under varying conditions. 48
Figure 34: Calibration tool - HSV calibration 3.5.3 Pixels’ Distance Calibration For precise distance determination for each pixel, an external reference becomes indispensable. In this case, a striped carpet is used with a known distance between the stripes. The program requires the carpet’s presence in front of the robot’s camera. Upon detection of the start and end of each white line, the program associates specific pixels with distances, deriving an approximation. For example, for pixel 120, counted from the image centre, the distance is 500 centimetres. These points are approximated by a polynomial function. The polynomial equation chosen was the eleventh degree as shown in Section 4.4.2. As the mirror is centred with the camera and parallel to the ground, this data only needs to be collected on a single line of pixels (from the centre of the image). Therefore, this equation enables the distance determination of each pixel to the image centre (in pixels), providing the actual distance to the referred pixel. Since the angle of each pixel to the centre is readily obtained, decomposition yields distances in the cartesian reference frame, with the robot’s centre as the origin. Figure 35 shows an example of a calibration where the filtered carpet lines can be seen in the monochrome image. To make it clear to the user where the transitions occur, these points are drawn on the original image (red dots). To check the equation’s integrity obtained, a graph is printed that con- 49
verts from pixels to centimetres by this equation (blue dots). Figure 35: Calibration tool - Map calibration As soon as the user presses Save Distances, the tool saves the Cartesian and polar coordinates for each pixel, Figure 36 shows this process. The first step is to obtain the closest possible polynomial equation to the reference points obtained. This is done using the CurveFit function from the SciPy library, which returns the arguments of the polynomial equation. In this case, the equation used is of the eleventh degree (tests in section 4.4.2), so the function returns the twelve arguments for the equation. Next, the coordinates for each pixel are calculated. For the polar coordinates, the angle is obtained from the direction of the pixel to the centre, using atan2 , which returns the angle taking into account the four quadrants (- 180º to 180º). The real distance is obtained using the polynomial equation and the distance in pixels. The Cartesian coordinates are obtained by decomposing the polar coordinates into vectors. These coordinates are stored in a matrix and then saved in the file. 50
Save Lookup Table Store in Array Save to File End Curve Fit pixel_x < 480 ? pixel_y < 480 ? α <- atan²(240-pixel_y, pixel_x-240) pixel_dist <- sqrt( (240-pixel_y)² + (pixel_x-240)² ) dist <- EquationResult(pixel_dist) y <- sin(α) * dist x <- cos(α) * dist pixel_y <- pixel_y +1 pixel_x <- 0 pixel_x <- pixel_x +1 Yes No Yes No pixel_x <- 0 pixel_y <- 0 x, y, d, α x, y, d, α x, y, d, α x, y, d, α x, y, d, α x, y, d, α x, y, d, α x, y, d, α x, y, d, α ... ... 480 480 pixel_y pixel_x α pixel_dist Figure 36: Create lookup table 3.5.4 Field Calibration As shown in Figure 37, this functionality not only generates the file containing the lines’s distances in the competition rules but also produces a map image that is crucial for Template Matching . A vital consideration for this image is to maintain a significantly large margin concerning the field lines. This precaution ensures that even if the robot is positioned outside the field, it can still effectively determine its location. 51
Figure 37: Calibration tool - Field calibration Developing a method to dynamically alter the field’s size for the robot proved to be highly beneficial. This allowed for easy adjustment of dimensions whenever a change in the field layout was necessary. Figure 38 shows various field layouts. Figure 38a represents the LAR field, Figure 38b represents the Portuguese Open field and Figure 38c represents the RoboCup field. (a) (b) (c) Figure 38: Fields generated by the Calibration Tool - (a) LAR field, (b) Portuguese Open field, (c) RoboCup field 52
Figure 44: YOLO inference time with different network sizes 4.2.2 Image Resolution To verify how the image’s size influences the inference time, it was decided to test this aspect. Tests were conducted on various image sizes, from the image size used by previous generations of the team to the maximum size obtained by the camera. As illustrated in Figure 45, there is a decrease in FPS as the image size increases. The resolution used by previous generations (480x480) proved to be the fastest. As it has already been possible to play games at this resolution and the performance of the system as a whole is uncertain, it was decided to choose the lowest resolution (480x480). Figure 45: YOLO Resolution - Inference time comparison 4.2.3 Behaviour tests As many skills rely on the precise identification of objects as their primary reference points. A clear illustration of this dependency is evident in skills such as receiving a pass, where the ball serves as a crucial reference point, and in its subsequent return, when a human becomes the reference point, as depicted in the image sequence in Figure 46. 59
Figure 46: Robot receive and pass The skill of shooting on goal benefits significantly from object detection, particularly in identifying the goalposts for improved aim, as demonstrated in the sequence of images in Figure 47. The accurate detection of relevant objects becomes useful in refining and optimising the execution of these essential robotic football skills. Figure 47: Robot receive and kick These practical demonstrations not only demonstrated the robot’s ability in specific scenarios but also served to prove the overall capabilities and progress made within the project. In other words, this test proved the use of object detection to perform various skills, using the ball, the person and the goalposts as a reference for orientation. 60
4.2.4 False Positive Correction The Portuguese Open, was an opportunity to test and enhance the dataset, marking the team’s first experience on a standard-sized robotic football field in the competition setting. Using the model taken from the seventh training session, described in Section 3.3.2.2, the detection test was carried out and efforts were taken to identify false positives. One of these false detections occurred within the penalty circle and the middle circle, as shown in Figure 48a. To solve this misdetection, several images were taken with the penalty circle and the ball. An example of these new images is shown in Figure 48b. Figure 48c shows the segmentation after training with new images in the vicinity of the penalty mark. It became apparent that the false positives were successfully eliminated as well as the segmentation of light-coloured circles as balls. (a) (b) (c) Figure 48: (a) Ball detection in the penalty circle, (b) Annotation examples to remove field circles detection (c) Detection after new annotations 4.2.5 Model Evolution The improvement in accuracy is remarkable as more images are added to the dataset. Figure 49a shows the detection with the first model obtained (Section 3.3.2.2). It is noticeable that it is only possible to detect the balls in the RoboCup environment, and this confidence is very low. However, this behaviour is to be expected due to the small number of training classes. Figure 49b shows the detection result with the seventh model (Section 3.3.2.2). It should be noted that it already detects the blue_shirt class, which until then had not been added to the algorithm. It is also noticeable that it already detects some other classes, but confuses, for example, a human as a robot. In Figure 49c, which shows the final model’s detection (Section 3.3.2.2), practically all the elements in the field are detected. This discrepancy with the other models is due not only to having more images 61
for training but also to the fact that the dataset includes images taken on-site. One such example is the RCT team’s robots (described in Section 2.3.3.3), which have a completely different robot shape (cubic) to the other teams (usually more conical). So, without training with on-site images, it would have been very difficult to detect all the robots. (a) (b) (c) Figure 49: (a) Segmentation with the first model, (b) Segmentation with the seventh model, (c) Segmentation with the tenth model 62
4.2.6 Final Model This test was carried out with the last model developed, which came from the tenth training session (Section 3.3.2.2). In other words, the dataset already included images taken in the RoboCup environment. Figure 50a is an example of this test detecting all the elements in the MSL field. It is worth noting the confidence obtained in the detection that allows the threshold to be set high. In Figure 50b it is possible to see another result in the same environment, but there is a human who has not been detected. This is because few people wearing shorts existed in the dataset. However as the referee is the only one on the field and has to be able to avoid the robots, these detection failures were not relevant for this competition. However, in the future there will be games with human players, meaning that more images of humans have to be added to the dataset. (a) (b) Figure 50: Final YOLOv8 predition After each training session, there is an opportunity to analyze several graphs provided by training. These graphs were obtained when training the final model. 4.2.6.1 Labels Information The YOLO output provides the dataset’s health. In Figure 51a, notably, the class with the fewest appearances, such as the red_shirt class, is visible. This is due not only to the fact that few images were taken with this class but also to the fact that when images were taken, objects from other classes were inevitable, such as the ball and the goalposts. The figure shows that the ball and the goalposts are the classes with 63
the most instances. For a neural network, it is not crucial to maintain a balanced representation of appearances during training. Even so, this means that the class that most needs to be added to the dataset is red_shirt . In Figure 51b, the detection area is depicted, revealing that the majority of objects are concentrated in front and around the robot, with sparse presence in the robot’s vicinity. This graph highlights the amount of unused area in an image, leading to a loss of resolution and, consequently, precision in localizing other objects. Improving the model’s performance may involve diversifying the dataset to include more varied object placements. In Figure 51c, the graph illustrates the sizes of objects used for training, indicating that they are predominantly small, likely due to their distance from the robot. Additionally, the dataset includes many images with objects leaning against the robot, as evident with a red circle. This strategic addition aims to enhance the model’s ability to detect and recognize objects at all distances from the robot. (a) (b) (c) Figure 51: Dataset labels information - (a) Class balance, (b) Object distribution, (c) Object size distribution 4.2.6.2 Precision-Recall Curve Figure 52a illustrates the trade-off between precision and recall across different confidence thresholds. This curve corresponds to the bounding box, offering valuable insights into finding the optimal balance for detection. In Figure 52b, the curve relates to instance segmentation. The class person exhibits the least favourable relationship, likely attributed to either a lack of examples for validation or inaccuracies in the available examples’ labelling. This observation highlights the importance of a well-annotated and balanced dataset for achieving optimal performance, especially for classes with limited representation. 64
(a) (b) Figure 52: Precision-recall curve graph 4.2.6.3 Training Loss Curve The graphs display the training loss progression across epochs, providing a visual representation of the model’s learning journey and its convergence towards optimal performance. In Figure 53, it is evident that the graph related to the validation of contour boundaries is converging towards a relatively high value, whereas the bounding box’s validation is converging towards a lower value. This observation leads to the conclusion that the segmentation process is encountering challenges in accurately adjusting the contours. This difficulty is likely attributed to imperfections in the dataset contours’ correctness, highlighting the importance of refining and improving the dataset for enhanced model performance. 65
Figure 53: Training loss curve 4.2.6.4 Confusion Graph This graph provides a clear visualization of classes that may be misidentified or confused with the background or other classes (Figure 54). It facilitates the easy identification of false positives, false negatives, and instances of class mislabeling. In the presented graph, it is noticeable that the person class has the highest number of false negatives. This observation suggests a potential challenge in distinguishing the person class from the background, indicating the presence of confusion or misclassification between instances of the person class and the background itself. Further analysis and potential adjustments in the training data or model parameters may be warranted to address this particular issue. 66
Figure 54: Confusion graph 4.3 gRPC To decide which method to use for transferring gRPCs, some tests were carried out. The time taken for each part to transmit unary and stream gRPCs was measured, as shown in Figure 55. With unary gRPCs, it can be seen that the programme needs to wait for the entire cycle to be completed before starting to capture a new image. With server streaming gRPCs, on the other hand, new image capture is started when the data is transmitted, while Close Localisation runs in parallel. This means that image capture takes place around 25% faster than unary gRPC. It can also be seen that the time it takes from the image being captured to the data being written to the Local Database is practically the same for unary and stream gRPC. But even so, the server streaming gRPCs is a little faster because the server doesn’t need a request from the client to send a new sequence of data. In other words, it uses one less request and one less acknowledgement each cycle. The Computer B (described in Section 2.2.1.2) is used for this test. The current camera only allows images to be captured at 30 FPS, so for this test images from a video file were used to realise the maximum real performance. These tests make it possible to understand which method offers the best performance and to see how much latency can be achieved with this software. So, to create a parallelism between processes and to capture images more frequently, it was decided to use the server streaming gRPCs. 67
Get Image 0.66 ms YOLO Inference 5.52 ms Object Sort 1.45 ms gRPC Transmission 1.96 ms Close Localization 2.55 ms Unary gRPC 12.14 ms Get Image 0.66 ms YOLO Inference 5.52 ms Object Sort 1.45 ms gRPC Transmission 1.76 ms Close Localization 2.55 ms Server Streaming gRPC 9.39 ms Media File Local Database Local Database Time from camera to database: 13.74 ms Time from camera to database: 13.94 ms Max 106.49 FPS Max 82.37 FPS Media File Figure 55: Time comparison of Unary and Stream gRPC 4.4 Self-Localization This section covers the key aspects of self-localization, including resolution considerations, lookup table equation determination, the integration of wheel encoders, and the system’s performance in various environments. 4.4.1 Resolution The template image’s resolution constitutes a critical balance between latency and precision. It was decided to run the tests at different self-localization algorithm resolutions. Consequently, testing was undertaken at resolutions of 5cm/pixel, 10cm/pixel, and 20cm/pixel. The results, as shown in Figure 56, revealed that in close localization it hardly varies between 20 cm/pixel and 10 cm/pixel. At a resolution of 5 cm/pixel, however, it takes 18 milliseconds. This difference is most evident in Global Localization , which takes 50 milliseconds in processing time with the same resolution. With 10 cm/pixel, it takes 20 milliseconds. This test is executed in Computer A however the processor to be used and resources used by each process in the robot are uncertain at this part of the project. It was decided to choose the lowest possible value. However, since the Close Localization ’s value with a resolution of 20 cm/pixel and 10 cm/pixel has practically the same processing time. To increase the localization resolution obtained by 68
can be used to remove drift from the odometry. The red line shows the two components’ combination mentioned above using a Kalman filter. Figure 62 shows the robot’s point of view during the collection of this data. It can be seen that the robot rotates by about 45º just walking in a straight line, a behaviour due to the Omni-3MD Max firmware. This test proved that the current firmware on the motor controller board is not working properly, as it is practically impossible to walk in a straight line with the current control settings. The low turning capacity is also proven. As a result, there are constant deviations between the desired path and the path to the final localization. Overall, this test proved that the Kalman filter is capable of filtering the vision localization’s values and that the drift produced by the encoders does not interfere with the result. The integration of wheel encoders has improved the system’s responsiveness, providing near-instantaneous feedback. Furthermore, the use of computer vision facilitated error correction, ensuring a more robust and accurate localization system. 1 2 3 Figure 61: Comparison between vision, encoders and Kalman localization 75
1 2 3 Figure 62: Sequential robot’s point of view during data collection 4.4.7 Self-Localization Error Tests were conducted to assess the localization error by attempting to move the robot in a straight line, using a remote control, at a consistent speed of 500 millimetres per second. The movement should be perfectly straight from one goal line to the other, which in this case is 18 metres. However, achieving perfect straight-line motion with the robot proved challenging, requiring multiple attempts, and even then, it was not flawless. The speed was not perfectly constant either. This is caused by hardware problems, particularly with the wheels and the motor control board. Despite these challenges, the results were encouraging. Figure 63 shows the movement of different localization methods. The green line represents the odometry’s movement, which is shown smoothly but with a drift from the real value. The yellow line represents the coordinates obtained from computer vision. It is noticeable that this line has a lot of noise, but the values are always around the real value, which makes it possible to obtain an absolute position. The red line shows the final coordinates given by the self-localization system. As this trajectory has an odometry component, there is no delay in obtaining the current location. It also contains the computer vision location already filtered, allowing an absolute localization to be obtained. Therefore, the trajectory obtained by the robot is close to the real value. 76
Figure 63: Representation of the test to obtain the self-localization error Obtaining the absolute error throughout the iterations makes it easier to analyse where the greatest deviation occurs, as shown in Figure 64. It is noticeable that up to frame 600 there are many variations in the error, which is because the trajectory realised by the robot was not perfect either. But from frame 600 onwards it can be seen that the error is mostly below the mean absolute error, which in this case is 81 millimetres. This is because, in this part of the trajectory, the robot was moving very close to linearly. Despite the difficulties encountered in this test due to the hardware itself, it was possible to realise that the mean absolute error is smaller than the robot’s radius itself. These results met the requirements set by the team, which was to have a mean absolute error of less than 25 centimetres. In addition, the maximum value obtained is also smaller than the robot’s radius. Figure 64: Self-localization error throughout the frames 4.4.8 Base Station Integration The Base Station serves as a central hub for visualizing the behaviour of robots on the field, providing a comprehensive overview of their positions and interactions [28]. Figure 65 illustrates a typical scenario where the Base Station , denoted by the red square, displays raw information about various objects’ 77
positions in the field. In this visual representation, the positions of allied robots are depicted, offering insights into their strategic placements during the game. However, it is important to note that information related to opponent robots has not undergone the filtering process, providing an unprocessed view of their positions. This unfiltered opponent information is a raw data snapshot received from the robots. Figure 65 also showcases a filtered ball’s position representation. The ball, highlighted in the visualization, has undergone a filtering process, enhancing the accuracy and reliability of its positional information. This filtered data contributes to a more refined ball’s location’s understanding, crucial for strategic decision-making during the game. The Base Station , with its ability to process and display both raw and filtered information, plays a main role in monitoring and analyzing the robotic football match’s dynamics. This visual feedback is needed for teams to make informed decisions, refine their strategies, and adapt to the evolving conditions on the field. BALL Figure 65: Base Station representing robots and ball position To check the error obtained when combining all data, some real or simulated game situations were used to collect this data. The Base Station collects all the data from the objects seen by each robot in the team and filters and combines this data. As the position of some objects is known, it is possible to remove the total error from the system. Figure 66a shows an example of the collection of the ball error in a real game situation. Figure 66b shows the illustration made by the Base Station and shows the representation 78
of the ball obtained by each robot and its location already merged and filtered. The results obtained in these various tests are shown in Table 7. The results obtained were positive, since the average absolute error of the ball is 93.03 millimetres, taking into account that the radius of the ball is around 111 millimetres. The error in the location of the opposing robot is greater, due to the different base shapes of the robots, but on the other hand, the radius of the robots is around 250 millimetres and the maximum error obtained was 216.40 millimetres. As expected, data fusion improved the quality of object localisation, thus improving the system as a whole. (a) Merged ball Ball by robots Robots (b) Figure 66: (a) Game situation to obtain ball localization error (b) Illustration provided by Base Station Table 7: Error obtained in the localisation of objects already filtered and merged by Base Station . Object Mean Absolute Error (mm) Maximum Absolute Error (mm) Ball 93.03 179.77 Opponent Robot 119.54 216.40 4.4.9 RoboCup The Laboratory of Automation and Robotics at Middle Size League (LAR@MSL) team dedicated the whole year to preparing for the RoboCup competition. This section shows some of the results of that competition. 79
4.4.9.1 Setup to Game Before the commencement of each game, a crucial pre-match routine was run to verify whether all robots displayed the correct image and detections, ensuring accurate orientation and location within the Base Station . Once all criteria were met and confirmed to be accurate for location, orientation, and object detection, the robots were considered prepared for the game. They lined up in the field’s blue area. Upon receiving the referee’s signal, the robots proceeded to their respective positions on the field. At the start of each match, a command is sent via the Base Station for all robots to position themselves in a specific location. The movement skill uses the self-localization value to calculate its trajectory to that value. Figure 67 shows the initial movement taken by the robots. All the robots position themselves in a specific position in the field. This shows the self-localization software’s integrity in the rest of the project. It also proves to be able to move using the localization system presented. 1 2 34 Figure 67: Robots entering the field at RoboCup 4.4.9.2 Robot failures Both hardware and software failures were common problems during the games. Some of these failures were caused by the self-localization system, which was affected by very strong impacts during the games. These collisions with other robots caused the field visualised by self-localization to become deformed. As a result, the system for obtaining the robot’s orientation would sometimes reorient itself to another reference. As the system does not distinguish between the touchline and the goal line, it would sometimes 80
be reoriented with an error of ±90◦. As the self-localization system depends on orientation, this failure is critical for the whole system. Until the RoboCup, there have not been such strong impacts between robots, so this problem in orientation has not yet occurred. Table 8 shows the total number of failures during each game. The number of failures decreases as more games are played. This is because the robots’ behaviour has improved, i.e. their field skills (which were developed by another member) allowed for fewer clashes. In other words, there was a noticeable improvement throughout RoboCup. Table 8: RoboCup failures throughout matches Game Failures Game time (minutes) Failures per minute 1 11 23 0.48 2 9 15 0.6 3 10 30 0.33 4 9 30 0.3 5 9 30 0.3 6 6 30 0.2 7 7 30 0.23 8 6 30 0.2 9 2 30 0.067 10 4 50 0.08 4.5 Conclusion This chapter concluded that the neural network with the best trade-off between latency and accuracy is yolov8s-seg, as analysed in Section 4.2.1. Networks with different resolutions were also tested, as discussed in Section 4.2.2. It was concluded that the difference in latency between 480x480 and 640x640 is not significant. So the camera resolution decision is flexible between these two resolutions. Throughout the project, the YOLOv8 model’s evolution has been positive, due to the inclusion of images in different environments and the constant correction of false detections. It is also concluded that the dataset needs more red_shirt classes, but when images containing this class are obtained, they inevitably contain others in the same environment, such as the ball and the goalposts. Concerning computer vision, it was concluded that a resolution of 480x480 should be adopted due to 81
concerns about the reduced latency of the robot’s entire system. Tests were also carried out on the degree of the polynomial equation that converts pixels into real distance. The sixth-degree polynomial equation proved to be better than the others. As it already showed results with reduced errors, it was not necessary to test the seventh-degree polynomial equation, as presented in Section 4.4.2. Concerning orientation, the tests concluded that it was not possible to use the CMPS14 and that with strong collisions it is susceptible to disorientation. In the tests following self-localization, it was proven that the coordinates obtained by computer vision contained a lot of noise, but at the same time, their value was around the real value. With the Kalman filter, this noise is easily converted into a smoother trajectory. However, in this filtering, there is a compromise between precision and delay, as analysed in Section 4.4.6. That is why odometry has the fundamental role of removing this delay. When analysing the error obtained in self-localization, as presented in Section 4.4.7, it is possible to see that it fulfils the requirements, with the mean absolute error being less than half the robot’s radius. The tests also demonstrate the omnidirectional vision system’s integrity with the rest of the robot’s systems involved. 82
Chapter 5 Conclusions and future work This chapter concludes the research undertaken, summarizing findings and outlining future directions for the team’s work in both object detection and self-localization. 5.1 Conclusions It can be concluded that the software developed was successfully integrated with the rest of the project, allowing skills to be performed in the context of MSL, using the data provided for self-localization and object detection. As a result, the team competed in RoboCup 2023 and achieved fourth place. This result was very motivating given the short time the team had to develop the entire project practically from scratch. 5.1.1 Object Detection Regarding object detection, it can be concluded that YOLOv8, compared to computer vision, is more viable in the long term. However, developing a customised model that accurately detects objects involves several challenges, with the annotation process being a critical factor. Common errors during annotation can significantly affect the dataset’s quality and, consequently, the object detection model’s performance. The model’s accuracy evolved throughout the project, as images were added to the dataset. The final model proved to have a mAP50-95 of 60% and a mAP50 of 90%, i.e. in the instance segmentation task with the confidence threshold equal to 50% the network correctly detects, on average, 90% of the objects. The inference time tests also proved that using an Nvidia GeForce RTX 3060 Laptop graphics card as a prediction device, it is possible to obtain a latency of 180 FPS, using a small-sized network and the instance segmentation task. It is also worth noting that the RoboFlow’s integration tool, together with an YOLOv8 model, proved to be robust, especially as deep learning was taken advantage of by analysing images. The success of this approach exceeded initial expectations, as the accuracy results were very high even using a small dataset, establishing it as a scalable and viable long-term solution. 83
5.1.2 Self-Localization The approach chosen for self-localization encountered challenges that deviated from initial expectations, mainly influenced by the unexpected CMPS14 sensor’s behaviour. This unforeseen circumstance led to the exploration of alternative orientation methods, leading to the development of an approach based on histograms. However, this method proved susceptible to false orientations due to strong clashes between robots. The use of Template Matching presented a pragmatic solution within the time project’s constraints. However, there are several drawbacks, including challenges in calibration - both hardware and software. Since Template Matching is based on image alignment, any deviations from the catadioptric vision system directly affect the localization system’s reliability. However, the final results proved that the self-localization accuracy met the requirements, in this case, the mean absolute error is around 8 centimetres, which is less than the robot’s radius. Using a Lenovo Legion 5 computer, with a 12-core AMD Ryzen 5 5600h, 8 GiB of RAM, GeForce RTX 3060 Mobile / Max-Q, with the Ubuntu 22.04.3 operating system, it also proved capable of achieving a latency of around 400 FPS for Close Localisation and 106 FPS for all the omnidirectional vision software. Thus, the results exceeded expectations due to their performance and precision. 5.2 Prospect for future work 5.2.1 Object Detection Considering the challenges encountered in object detection methodologies, the team’s future endeavours should continue to incorporate advanced deep learning solutions such as YOLOv8. This solution is promising for continuing to improve object detection capabilities, providing a robust foundation for the team’s evolving needs. A primary focus in future initiatives should be directed towards improving the datasets’ quality. The priority lies in increasing the dataset, and this process should persist in the field of instance segmentation (contours). This strategic choice not only facilitates current object detection but also prepares the dataset for the future. This makes it possible to preserve the dataset’s adaptability for both detection (box) and instance segmentation (contours), the team guarantees flexibility in its application in the dynamic context of MSL. As the team progresses, continued commitment to refining the datasets and adopting the latest tech- 84
Figure 71: Loss graphs of first train session 91
Figure 72: Labels analysis of first train session 92
Figure 73: Validation labels of first train session 93
Figure 74: Validation Predict of first train session 94
A.2 Seventh Train Session Results Figure 75: Box Precision-recall curve graph of seventh train session Figure 76: Mask Precision-recall curve graph of seventh train session 95
Figure 77: Confusion matrix of seventh train session 96
Figure 78: Loss graphs of seventh train session 97
Figure 79: Labels analysis of seventh train session 98
Figure 80: Validation labels of seventh train session 99
Figure 81: Validation Predict of seventh train session 100
Figure 89: Final dataset examples 107
Appendix B Source Code B.1 Golang File B.1: Code of player.go 1package main 2 3i m p o r t ( 4” f m t ” 5” os ” 6OmniVision ” player/OmniVision_pkg” 7”strconv” 8” s y n c ” 9 ) 10 11 // W a i t G r o u p i s us e d t o w a i t f o r t h e p ro gr a m t o f i n i s h g o r o u t i n e s . 12 var WG s y n c . W a i t G r o u p 13 var goroutines_nmr = 3 14 15 func m ain ( ) { 16 f m t . P r i n t l n ( ” START P l a y e r ” ) 17 // Add a c o u n t o f t h r e e , one f o r e ach g o r o u t i n e . 18 WG.Add ( g o r o u t i n e s _ n m r ) 19 20 // O t h e r g o r o u t i n e s 21 // ( . . . ) 22 23 my_id : = o s . A r g s [ 3 ] 24 m y _ g r p c _ i p : = o s . A r g s [ 6 ] 25 s h i r t , _ : = s t r c o n v . A t o i ( o s . A r g s [ 7 ] ) // 0 r e d _ s h i r t 1 b l u e s h i r t 26 ID , _ : = s t r c o n v . A t o i ( m y _ i d ) 27 28 // # S t a r t O m n i V i s i o n g o r o u t i n e 29 go O m n i V i s i o n . R u n ( s h i r t == 1 , m y _ gr p c _ ip , I D ) 30 31 32 // W a i t f o r t h e g o r o u t i n e s t o f i n i s h . 33 W G . W a i t ( ) 34 } File B.2: Code of omnivision.go 1package OmniVision_pkg 2 3i m p o r t ( 4”context” 108
5” f m t ” 6”image” 7” l o g ” 8 coms ” p l a y e r / c o m m u n i c a t i o n ” // C o m m u n i c a t i o n pkg 9 pb ” p l a y e r / pb ” // gRPC G r e n e r a t e d pkg 10 ” g o c v . i o / x / g o c v ” 11 ” g o o g l e . g o l a n g . o r g / g r p c ” 12 ) 13 14 // O m n i V i s i o n S t r u c t c o n t a i n s a l l t h e d a t a n e ede d by O m n i V i s i o n ’ s s o f t w a r e , e l i m i n a t i n g t h e need t o c r e a t e new v a r i a b l e s e v e r y c y c l e . 15 // 16 t y p e O m n i V i s i o n s t r u c t { 17 I D i n t // R o b o t I D 18 shirt b o o l // R o b o t S h i r t 19 x_vision i n t // R o b o t X P o s i t i o n C o m p u t e r V i s i o n 20 y _ v i s i o n i n t // R o b o t Y P o s i t i o n C o m p u t e r V i s i o n 21 x _ e n c i n t // R o b o t X P o s i t i o n E n c o d e r s 22 y_enc i n t // R o b o t Y P o s i t i o n E n c o d e r s 23 x float64 // R o b o t X P o s i t i o n F i n a l 24 y float64 // R o b o t Y P o s i t i o n F i n a l 25 a n g l e i n t // R o b o t A n g l e 26 original_image gocv.Mat // RGB Frame 27 h s v _ i m a g e gocv.Mat // HSV Frame 28 viewed_field gocv.Mat // L i n e s F i l t e r e d 29 c a l c _ f i e l d gocv.Mat // R e a l D i s t a n c e L i n e s 30 calc_rotated_field gocv.Mat // O r i e n t a t e d R e a l D i s t a n c e L i n e s 31 ideal_field gocv.Mat // Image o f F u l l F i e l d 32 ideal_field_to_edit gocv.Mat // Im ag e o f F u l l F i e l d ( f o r d e b u g ) 33 mask gocv.Mat // TemplateMatching Mask 34 result gocv.Mat // TemplateMatching Result 35 maxL oc image.Point // T e m p l a t e M a t c h i n g R e s u l t P o s i t i o n 36 kalman *Kalman // Kal man V a r i a b l e s 37 lowerMask gocv.Scalar // Low M a r g i n HSV F i l t e r 38 upperMask gocv.Scalar // U p p er M a r g i n HSV F i l t e r 39 } 40 41 // T h i s f u n c t i o n i n i t a l l v a r i a b l e s o f O m n i V i s i o n . 42 // I t i s a meth od o f t h e O m n i V i s i o n s t r u c t . 43 // 44 func ( vision *OmniVision ) I n i t ( ) { 45 // I n i t V a r i a b l e s 46 v i s i o n . h s v _ i m a g e = g o c v . N e w M a t ( ) 47 v i s i o n . c a l c _ f i e l d = g o c v . N e w M a t W i t h S i z e ( 1 6 0 , 160 , g o c v. M a t T y p e C V 8U C 1 ) 48 v i s i o n . c a l c _ r o t a t e d _ f i e l d = g o c v . N e w M a t W i t h S i z e ( 1 6 0 , 160 , gocv.MatTypeCV8UC1 ) 49 v i s i o n . v i e w e d _ f i e l d = g o c v . N e w M a t ( ) 50 v i s i o n . i d e a l _ f i e l d = g o c v . I M R e a d ( ” O m n i V i s i o n _ p k g / F I E L D . p n g ” , gocv.IMReadGrayScale ) 51 v i s i o n . i d e a l _ f i e l d _ t o _ e d i t = g o c v . I M R e a d ( ” O m n i V i s i o n _ p k g / F I E L D . p n g ” , gocv.IMReadGrayScale ) 52 w h i t e : = g o c v . N e w S c a l a r ( 2 5 5 , 255 , 255 , 2 55) 53 v i s i o n . m a s k = g o c v . N e w M a t W i t h S i z e F r o m S c a l a r ( w h i t e , 1 60 , 160 , gocv.MatTypeCV8UC1 ) 54 v i s i o n . l o w e r M a s k = g o c v . N e w S c a l a r ( M I N _ H _ l i n e s _ o m n i , M I N _ S _ l i n e s _ o m n i , MIN_V_lines_omni , 0.0 ) 55 v i s i o n . u p p e r M a s k = g o c v . N e w S c a l a r ( M A X _ H _ l i n e s _ o m n i , M A X _ S _ l i n e s _ o m n i , MAX_V_lines_omni , 0.0 ) 109
56 v i s i o n . r e s u l t = g o c v . N e w M a t ( ) 57 } 58 59 // The Run f u n c t i o n i s r e s p o n s i b l e f o r s t a r t i n g a l l o f O m n i V i s i o n and i s i n a p e r m a n e n t c y c l e . 60 // I n t h i s p e r m a n e n t c y c l e , i t must r e c e i v e t h e im age and d a t a f r o m YOLO , 61 // p e r f o r m C l o s e _ L o c a l i z a t i o n and s a v e t h e r e s u l t a n t d a t a i n t h e L o c a l Database. 62 // 63 // P a r a m e t e r s : 64 // 65 // − ‘ s h i r t ‘ : b o o l −> R o b o t S h i r t ( b l u e = t r u e r e d = f a l s e ) 66 // − ‘ i p _ g r p c ‘ : s t r i n g −> gRPC I P 67 // − ‘ ID ‘ : i n t −> R o b o t Number ( 0 i s GK − 1 , 2 , 3 , 4 a r e f i e l d p l a y e r s ) 68 // 69 func Run ( s h i r t b o o l , ip_grpc string , I D i n t ) { 70 71 f m t . P r i n t l n ( ”OmniVision !”) 72 // # I n i t v a r i a b l e s 73 var omnivision OmniVision 74 omnivision.Init () 75 b u t t o n s : = 0 76 s i d e : = false 77 omnivision.shirt = shirt 78 o m n i v i s i o n . I D = I D 79 // R o b o t B u t t o n s , R o b o t S h i r t , F i e l d S i d e 80 c o m s . G e t B u t t o n s ( & b u t t o n s , & o m n i v i s i o n . s h i r t , & s i d e ) 81 82 // # I n i t gRPC 83 a d d r : = i p _ g r p c + ” : 4 0 0 0 0 ” 84 f m t . P r i n t l n ( ” GRPC Omni s e r v i c e o p e n n i n g . . . ” , a d d r ) 85 conn , e r r : = g r p c . D i a l ( a d d r , g r p c . W i t h I n s e c u r e ( ) , g r p c . W i t h B l o c k ( ) ) 86 i f e r r ! = n i l { 87 l o g . F a t a l ( e r r ) 88 } 89 d e f e r conn.Close () 90 client := pb.NewYolo_OmniClient ( conn ) 91 req := pb.Request_Omni_Calib { 92 Ch e c k : f a l s e , 93 } 94 s tr e am , _ : = c l i e n t . S e n d _ O m n i ( c o n t e x t . B a c k g r o u n d ( ) , & r e q ) 95 f m t . P r i n t l n ( ” GRPC Omni s e r v i c e o pen e d ! ” , a d d r ) 96 97 98 // # G l o b a l L o c a l i z a t i o n 99 f m t . P r i n t l n ( ”Global localization !”) 100 N_GLO BAL_I TERATION S : = 10 101 x _ g l o b a l : = 0 102 y _ g l o b a l : = 0 103 n u m _ i t : = 0 104 105 for i : = 0 ; i < N_GLOBAL_ITERA TIONS ; i ++ { 106 // # R e q u e s t D a t a ( Image ) 107 r e sp , e r r : = s t r e a m . R e c v ( ) 108 i f e r r ! = n i l { 109 l o g . F a t a l ( e r r ) 110 } 111 o m n i v i s i o n . o r i g i n a l _ i m a g e , _ = g o c v . N e w M a t F r o m B y t e s ( 4 8 0 , 480 , 110
g o c v . M a t T y p e C V 8 U C 3 , r e s p . O m n i ) 112 113 // # G l o b a l L o c a l i z a t i o n 114 o m n i v i s i o n . G l o b a l _ L o c a l i z e ( ) 115 i f ( o m n i v i s i o n . x _ v i s i o n < 0 && ! s i d e ) || ( o m n i v i s i o n . x _ v i s i o n > 0 && s i d e ) { 116 x _ g l o b a l += o m n i v i s i o n . x _ v i s i o n 117 y _ g l o b a l += o m n i v i s i o n . y _ v i s i o n 118 f m t . P r i n t l n ( ”� G l o b a L L o c a l i z a t i o n X= ” , omnivision.x_vision , ” Y = ” , o m n i v i s i o n . y _ v i s i o n ) 119 n u m _ i t ++ 120 } 121 } 122 i f n u m _ i t ! = 0 { 123 o m n i v i s i o n . x _ v i s i o n = x _ g l o b a l / n u m _ i t 124 o m n i v i s i o n . y _ v i s i o n = y _ g l o b a l / n u m _ i t 125 } 126 f m t . P r i n t l n ( ” L o c a l i z a t i o n R e a d y ! X= ” , omnivision.x_vision , ” Y = ” , o m n i v i s i o n . y _ v i s i o n ) 127 128 // # I n i t Kalma n 129 omnivision.Init_Kalman ( float64 ( o m n i v i s i o n . x _ v i s i o n ) , float64 ( o m n i v i s i o n . y _ v i s i o n ) ) 130 131 f m t . P r i n t l n ( ” O m n i V i s i o n R e a dy ! ” ) 132 for { 133 c o m s . G e t B u t t o n s (& b u t t o n s , & o m n i v i s i o n . s h i r t , & s i d e ) 134 // # R e l o c a t i o n 135 i f b u t t o n s == 2 { 136 o m n i v i s i o n . G l o b a l _ L o c a l i z e ( ) 137 o m n i v i s i o n . R e s e t _ K a l m a n ( ) 138 } 139 // # R e c i e v e D a t a ( Image and YOLO d a t a ) 140 r e sp , e r r : = s t r e a m . R e c v ( ) 141 i f e r r ! = n i l { 142 l o g . F a t a l ( e r r ) 143 } 144 // C o n v e r t gRPC b y t e s i n g o c v . M a t 145 o m n i v i s i o n . o r i g i n a l _ i m a g e , _ = g o c v . N e w M a t F r o m B y t e s ( 4 8 0 , 480 , g o c v . M a t T y p e C V 8 U C 3 , r e s p . O m n i ) 146 147 // # C l o s e S e l f − L o c a l i z a t i o n 148 omnivision.Close_Localize () 149 150 // # S a v e D a t a 151 o m n i v i s i o n . S a v e O m n i D a t a ( r e s p ) 152 } 153 } File B.3: Code of Localize.go 1package OmniVision_pkg 2 3i m p o r t ( 4” f m t ” 5”image” 6 GK ” p l a y e r / G K _ P o s i t i o n ” 7” g o c v . i o / x / g o c v ” 111
8 ) 9 10 // The G l o b a l _ L o c a l i s e f u n c t i o n o b t a i n s t h e r o b o t ’ s p o s i t i o n and a n g l e b a se d on t h e e n t i r e f i e l d . 11 // I t i s a m etho d o f t h e O m n i V i s i o n s t r u c t . 12 // 13 // R e t u r n s : 14 // 15 // − ‘ x ‘ : i n t −> R o b o t X P o s i t i o n i n c e n t i m e t r e s 16 // − ‘ y ‘ : i n t −> R o b o t Y P o s i t i o n i n c e n t i m e t r e s 17 // − ‘ a n g l e ‘ : i n t −> R o b o t a n g l e 18 // 19 func ( vision *OmniVision ) G l o b a l _ L o c a l i z e ( ) ( x , y , a n g l e i n t ) { 20 // V a r i a b l e s 21 r e s u l t : = g o c v . N e w M a t ( ) 22 d e f e r result.Close () 23 v i s i o n . i d e a l _ f i e l d . C o p y T o (& v i s i o n . i d e a l _ f i e l d _ t o _ e d i t ) 24 v i s i o n . c a l c _ f i e l d . S e t T o ( g o c v . N e w S c a l a r ( 0 , 0 , 0 , 0 ) ) 25 26 // # HSV F i l t e r 27 g o c v . C v t C o l o r ( v i s i o n . o r i g i n a l _ i m a g e , & v i s i o n . h s v _ i m a g e , gocv.ColorBGRToHSV ) 28 g o c v . I n R a n g e W i t h S c a l a r ( v i s i o n . h s v _ i m a g e , v i s i o n . l o w e r M a s k , v i s i o n . u p p e r M a s k , & v i s i o n . v i e w e d _ f i e l d ) 29 30 // # G e t R e a l F i e l d 31 G e t R e a l F i e l d (& v i s i o n . v i e w e d _ f i e l d , & v i s i o n . c a l c _ f i e l d ) 32 33 // # R o t a t e and C l e a n O u t s i d e L i n e s 34 v i s i o n . a n g l e = v i s i o n . a d j u s t A n g l e (& v i s i o n . c a l c _ f i e l d ) 35 36 // # T e m p l a t e M a t c h i n g 37 g o c v . M a t c h T e m p l a t e ( v i s i o n . i d e a l _ f i e l d _ t o _ e d i t , v i s i o n . c a l c _ f i e l d , & r e s u l t , g o c v . T m C c o e f f , v i s i o n . m a s k ) 38 _ , _ , _ , max Loc : = g o c v . M i n M a x L o c ( r e s u l t ) 39 40 // A b s o l u t e C o o r d e n a t e s 41 v i s i o n . x _ v i s i o n , v i s i o n . y _ v i s i o n = P i x e l s _ t o _ M M ( m a x Lo c . X +80 , m a x L o c . Y + 8 0 ) 42 f m t . P r i n t l n ( ” V i s i o n L o c a l i z a t i o n X= ” , vision.x_vision , ” Y = ” , vision.x_vision ) 43 44 r e t u r n v i s i o n . x _ v i s i o n , v i s i o n . y _ v i s i o n , v i s i o n . a n g l e 45 } 46 47 // The C l o s e _ L o c a l i z e f u n c t i o n o b t a i n s t h e r o b o t ’ s p o s i t i o n and a n g l e b a se d on t h e p r e v i o u s p o s i t i o n , 48 // i . e . i t o n l y h a s a r a d i u s o f 1 m e t r e ( 10 p i x e l s ) t o move f r o m t h e l a s t position. 49 // I t i s a m etho d o f t h e O m n i V i s i o n s t r u c t . 50 // 51 // R e t u r n s : 52 // 53 // − ‘ x ‘ : i n t −> R o b o t X P o s i t i o n i n c e n t i m e t r e s 54 // − ‘ y ‘ : i n t −> R o b o t Y P o s i t i o n i n c e n t i m e t r e s 55 // − ‘ a n g l e ‘ : i n t −> R o b o t a n g l e 56 // 57 func ( vision *OmniVision ) Close_Localize () (x float64 , y float64 , a n g l e i n t 112
) { 58 // V a r i a b l e s 59 v i s i o n . i d e a l _ f i e l d . C o p y T o (& v i s i o n . i d e a l _ f i e l d _ t o _ e d i t ) 60 x _ v i s i o n , y _ v i s i o n : = C M _ t o _ P i x e l s ( v i s i o n . x , v i s i o n . y ) 61 v i s i o n . c a l c _ f i e l d . S e t T o ( g o c v . N e w S c a l a r ( 0 , 0 , 0 , 0 ) ) 62 63 // # HSV F i l t e r 64 g o c v . C v t C o l o r ( v i s i o n . o r i g i n a l _ i m a g e , & v i s i o n . h s v _ i m a g e , gocv.ColorBGRToHSV ) 65 g o c v . I n R a n g e W i t h S c a l a r ( v i s i o n . h s v _ i m a g e , v i s i o n . l o w e r M a s k , v i s i o n . u p p e r M a s k , & v i s i o n . v i e w e d _ f i e l d ) 66 67 // # G e t R e a l F i e l d 68 G e t R e a l F i e l d ( & v i s i o n . v i e w e d _ f i e l d , & v i s i o n . c a l c _ f i e l d ) 69 70 // # R o t a t e and C l e a n O u t 71 v i s i o n . a d j u s t A n g l e (& v i s i o n . c a l c _ f i e l d ) 72 73 // # R e g i o n o f I n t r e s t t o T e m p l a t e m a t c h i n g 74 i d e a l _ f i e l d _ r o i : = v i s i o n . i d e a l _ f i e l d _ t o _ e d i t . R e g i o n ( i m a g e . R e c t ( x _ v i s i o n −90 , y _ v i s i o n − 90 , x _ v i s i o n + 90 , y _ v i s i o n + 90) ) 75 76 // # T e m p l a t e M a t c h i n g 77 g o c v . M a t c h T e m p l a t e ( i d e a l _ f i e l d _ r o i , v i s i o n . c a l c _ f i e l d , & v i s i o n . r e s u l t , g o c v . T m C c o e f f , v i s i o n . m a s k ) 78 _ , _ , _ , m a x L o c _ r o i : = g o c v . M i n M a x L o c ( v i s i o n . r e s u l t ) 79 80 // A b s o l u t e C o o r d e n a t e s 81 v i s i o n . x _ v i s i o n , v i s i o n . y _ v i s i o n = P i x e l s _ t o _ M M ( x _ v i s i o n −90+ m a x L o c _ r o i . X +80 , y _ v i s i o n −90+ m a x L o c _ r o i . Y + 80) 82 83 // # Kalm an F i l t e r 84 i f v i s i o n . I D == 0 { 85 x _ l i d a r , y _ l i d a r , a n g l e : = G K . G e t _ G K P o s i t i o n ( A / 2 ) 86 i f x ! = 999999 || y ! = 999999 { 87 v i s i o n . x _ v i s i o n = x _ l i d a r 88 v i s i o n . y _ v i s i o n = y _ l i d a r 89 v i s i o n . x , v i s i o n . y = v i s i o n . U p d a t e _ K a l m a n ( ) 90 i f a n g l e > 70 || a n g l e < −70 { 91 vision.angle = i n t ( a n g l e ) 92 } 93 } e l s e { 94 v i s i o n . x , v i s i o n . y = v i s i o n . U p d a t e _ K a l m a n ( ) 95 } 96 } e l s e { 97 v i s i o n . x , v i s i o n . y = v i s i o n . U p d a t e _ K a l m a n ( ) 98 } 99 r e t u r n v i s i o n . x , v i s i o n . y , v i s i o n . a n g l e 100 } File B.4: Code of GetRealField.go 1package OmniVision_pkg 2i m p o r t ( 3” math ” 4” g o c v . i o / x / g o c v ” 5 ) 6c o n s t MIN_LINE_WIDTH = 1 113
7c o n s t MAX_LINE_WIDTH = 60 8 9// G e t R e a l F i e l d i s a f u n c t i o n t h a t t a k e s t h e f i l t r e d f i e l d and t r a n s f o r m i t i n r e a l f i e l d 10 // The r e s o l u t i o n i s 10cm f o r p i x e l 11 // C o n s i d e r i n g t h a t r o b o t s c a n v i e w 6 m e t e r i n e ach d i r e c t i o n 12 // 13 // P a r a m e t e r s : 14 // 15 // − ‘ i m a g e _ f i e l d ‘ : g o c v . M a t −> B i n a r y I m a g e o f F i e l d 16 // − ‘ r e a d e d _ f i e l d ‘ : g o c v . M a t −> M a t r i x 120 x120 t o s a v e r e a l f i e l d 17 // 18 func G e t R e a l F i e l d ( i m a g e _ f i e l d *gocv.Mat , readed_field *gocv.Mat ) { 19 20 i m a g e _ f i e l d _ p t r , _ : = i m a g e _ f i e l d . D a t a P t r U i n t 8 ( ) 21 r e a d e d _ f i e l d _ p t r , _ : = r e a d e d _ f i e l d . D a t a P t r U i n t 8 ( ) 22 d e l t a : = 0 23 l a s t _ p i x e l _ f i e l d : = 0 24 for a : = 0 ; a < 4 8 0 ; a += 5 { 25 l a s t _ p i x e l _ f i e l d = 0 26 // V e r t i c a l V e r i f i c a t i o n o f t r a n s a t i o n s g re e n − w h i t e − g r e e n 27 for y : = 0 ; y < 4 8 0 ; y ++ { 28 i f image_field_ptr [y*4 80 + a ] == 0 { 29 d e l t a = y − l a s t _ p i x e l _ f i e l d 30 i f MAX_LINE_WIDTH > d e l t a && d e l t a > MIN_LINE_WIDTH { 31 x _ d i s t : = i n t ( real_coordenates_omni [a][ i n t ( m a t h . R o u n d ( float64 ( l a s t _ p i x e l _ f i e l d + y ) /2 . 0 ) ) ] [ 0 ] / 1 0 ) + 80 32 y _ d i s t : = − i n t ( real_coordenates_omni [a ][ i n t ( m a t h . R o u n d ( float64 ( l a s t _ p i x e l _ f i e l d + y ) /2 . 0 ) ) ] [ 1 ] / 1 0 ) + 80 33 i f 0 < x _ d i s t && x _ d i s t < 160 && 0 < y _ d i s t && y _ d i s t < 160 { 34 readed_field_ptr [y_dist*1 6 0 + x _ d i s t ] = 255 35 l a s t _ p i x e l _ f i e l d = y 36 } e l s e { 37 l a s t _ p i x e l _ f i e l d = y 38 } 39 } e l s e { 40 l a s t _ p i x e l _ f i e l d = y 41 } 42 } 43 } 44 l a s t _ p i x e l _ f i e l d = 0 45 // H o r i z o n t a l V e r i f i c a t i o n o f t r a n s a t i o n s g re e n − w h i t e − g r e e n 46 for x : = 0 ; x < 4 8 0 ; x ++ { 47 i f image_field_ptr [a*480 + x ] == 0 { 48 49 d e l t a = x − l a s t _ p i x e l _ f i e l d 50 i f MAX_LINE_WIDTH > d e l t a && d e l t a > MIN_LINE_WIDTH { 51 x _ d i s t : = i n t ( r e a l _ c o o r d e n a t e s _ o m n i [ l a s t _ p i x e l _ f i e l d + i n t ( d e l t a / 2 ) ] [ a ] [ 0 ] / 1 0 ) + 80 52 y _ d i s t : = − i n t ( r e a l _ c o o r d e n a t e s _ o m n i [ l a s t _ p i x e l _ f i e l d + i n t ( d e l t a / 2 ) ] [ a ] [ 1 ] / 1 0 ) + 80 53 i f 0 < x _ d i s t && x _ d i s t < 160 && 0 < y _ d i s t && y _ d i s t < 160 { 54 readed_field_ptr [ y_dist*1 6 0 + x _ d i s t ] = 255 55 l a s t _ p i x e l _ f i e l d = x 56 } e l s e { 57 l a s t _ p i x e l _ f i e l d = x 114
58 } 59 } e l s e { 60 l a s t _ p i x e l _ f i e l d = x 61 } 62 } 63 } 64 } 65 } File B.5: Code of Rotation.go 1package OmniVision_pkg 2i m p o r t ” g o c v . i o / x / g o c v ” 3 4// The a d j u s t A n g l e f u n c t i o n c h o o s e s t h e b e s t o r i e n t a t i o n f o r t h e i m a g e u s i n g t h e f i e l d l i n e s a s a r e f e r e n c e . 5// 6// P a r a m e t e r s : 7// 8// − ‘ r o t a t e d ‘ : *g o c v . M a t −> R o t a t e d M a t r i x 9// 10 // O u t p u t s : 11 // 12 // − ‘ a n g l e ‘ : i n t −> R o b o t c a l c u l a t e d a n g l e 13 // 14 func ( vision *OmniVision ) a d j u s t A n g l e ( i m a g e _ r *gocv.Mat )i n t { 15 16 17 MIN_HISTOGRAM : = −10 18 MAX_HISTOGRAM : = 10 19 r o t a t e d : = g o c v . Z e r o s ( 1 6 0 , 1 6 0 , g o c v . M a t T y p e C V 8 U C 1 ) 20 d e f e r rotated.Close () 21 var m a x _ v a l u e s [ ] i n t 22 23 R o t a t e ( *i mag e _ r , i m age _ r , v i s i o n . a n g l e ) 24 h i s t H : = g o c v . Z e r o s ( 1 , 1 6 0 , g o c v . M a t T y p e C V 3 2 S C 1 ) 25 h i s t V : = g o c v . Z e r o s ( 1 6 0 , 1 , g o c v . M a t T y p e C V 3 2 S C 1 ) 26 27 // # C l e a n O u t s i d e L i n e s 28 v i s i o n . C l e a n _ O u t F i e l d ( i m age _ r , i n t ( v i s i o n . x ) , i n t ( v i s i o n . y ) ) 29 30 for i : = MIN_HISTOGRAM ; i <= MAX_HISTOGRAM ; i ++ { 31 R o t a t e ( *i m a g e _ r , & r o t a t e d , i ) 32 g o c v . R e d u c e ( r o t a t e d , & h i s t V , 0 , g oc v. Red uc eS um , g o c v . M a t T y p e C V 3 2 S C 1 ) 33 g o c v . R e d u c e ( r o t a t e d , & h i s t H , 1 , g oc v. Red uc eSu m , g o c v . M a t T y p e C V 3 2 S C 1 ) 34 _ , m a x Va l V , _ , _ : = g o c v . M i n M a x L o c ( h i s t V ) 35 _ , maxValH , _ , _ : = g o c v . M i n M a x L o c ( h i s t H ) 36 m a x _ v a l u e s = append ( m a x _ v a l u e s , i n t ( m a x V a l V + m axVa lH ) ) 37 } 38 39 a d j u s t : = ( A rg Ma x ( m a x _ v a l u e s ) ) + MIN_HISTOGRAM 40 v i s i o n . a n g l e += a d j u s t 41 i f −180 > v i s i o n . a n g l e { 42 v i s i o n . a n g l e += 360 43 } 44 i f vision.angle > 180 { 115
45 v i s i o n . a n g l e −= 360 46 } 47 48 R o t a t e ( *i m a g e _ r , i m a g e _ r , a d j u s t ) 49 50 r e t u r n vision.angle 51 } File B.6: Code of CleanOutField.go 1package OmniVision_pkg 2i m p o r t ( 3”image” 4” i m a g e / c o l o r ” 5” g o c v . i o / x / g o c v ” 6 ) 7// C l e a n _ O u t F i e l d i s a f u n c t i o n t h a t c l e a n a l l t h e n o i s e o u t s i d e t h e f o o t b a l f i e l d u s i n g l a s t r o b o t p o s i t i o n . 8// I s was c o n s i d e r o u t s i d e o f t h e f i e l d when i s 1 m e t e r way o f o u t s i d e l i n e s ( 1 0 p i x e l s ) 9// 10 // P a r a m e t e r s : 11 // 12 // − ‘ r e a d e d _ f i e l d ‘ : g o c v . M a t −> M a t r i x 160 x160 t o r e a d and s a v e r e a l field 13 // − ‘ x ‘ : i n t −> p r e v i o u s x r o b o t ’ s c o o r d i n a t e 14 // − ‘ y ‘ : i n t −> p r e v i o u s y r o b o t ’ s c o o r d i n a t e 15 // 16 // O u t p u t s : 17 // 18 // − ‘ r e a d e d _ f i e l d ‘ : g o c v . M a t −> B i n a r y Image o f l i n e s i n r e a l d i s t a n c e w i t h f i e l d ’ s o u t s i d e w i t h no n o i s e 19 20 func ( vision *OmniVision ) C l e a n _ O u t F i e l d ( r e a d e d _ f i e l d *gocv.Mat , x i n t , y i n t ) { 21 b l a c k : = c o l o r . R G B A { 0 , 0 , 0 , 0 } 22 L i m i t _ L _ x : = 80 − ( ( B / 2 0 ) − y / 1 0 ) − 10 23 L i m i t _ R _ x : = 80 + ( ( B / 2 0 ) + y / 1 0 ) + 10 24 L i m i t _ T _ y : = 80 − ( ( A / 2 0) − x / 1 0) − 10 25 L i m i t _ B _ y : = 80 + ( ( A / 20 ) + x / 10 ) + 10 26 27 i f ( L i m i t _ L _ x >0 && L i m i t _ L _ x <160) { 28 g o c v . R e c t a n g l e ( r e a d e d _ f i e l d , i m a g e . R e c t ( 0 , 0 , L i m i t _ L _ x , 1 6 0 ) , b l a c k , −1) 29 } 30 i f ( L i m i t _ R _ x >0 && L i m i t _ R _ x <160) { 31 g o c v . R e c t a n g l e ( r e a d e d _ f i e l d , i m a g e . R e c t ( L i m i t _ R _ x , 0 , 160 , 16 0 ) , b l a c k , −1) 32 } 33 i f ( L i m i t _ T _ y >0 && L i m i t _ T _ y <160) { 34 g o c v . R e c t a n g l e ( r e a d e d _ f i e l d , i m a g e . R e c t ( 0 , 0 , 160 , L i m i t _ T _ y ) , b l a c k , −1) 35 } 36 i f ( L i m i t _ B _ y >0 && L i m i t _ B _ y <160) { 37 g o c v . R e c t a n g l e ( r e a d e d _ f i e l d , i m a g e . R e c t ( 0 , L i m i t _ B _ y , 160 , 1 60) , b l a c k , −1) 38 } 39 } 116
43 // − ‘ x ‘ : i n t −> X i n P i x e l s 44 // − ‘ y ‘ : i n t −> Y i n P i x e l s 45 // 46 func CM_to_Pixels (x , y float64 ) ( i n t ,i n t ) { 47 r e t u r n i n t ( − ( y / 1 0 ) + 2 7 0 ) , i n t ( − ( x / 1 0 ) + 3 1 0 ) 48 } 49 50 // The A rgMa x f u n c t i o n g e t s t h e i n d e x o f t h e l a r g e s t e l e m e n t i n an a r r a y . 51 // 52 // P a r a m e t e r s : 53 // 54 // − ‘ v ‘ : [ ] i n t −> A r r a y 55 // 56 // R e t u r n s : 57 // 58 // − ‘ m a x _ i n d e x ‘ : i n t −> I n d e x o f max v a l u e 59 // 60 func A r g M a x ( v [ ] i n t )i n t { 61 m : = 0 62 m a x _ i n d e x : = 0 63 for i , e : = range v { 64 i f i == 0 || e > m { 65 m = e 66 m a x _ i n d e x = i 67 } 68 } 69 r e t u r n m a x _ i n d e x 70 } 71 72 // R o t a t e i s a f u n c t i o n t h a t r o t a t e s t h e i m a ge t o a s p e c i f i c a n g l e u s i n g n e a r e s t n e i g h b o u r i n t e r p o l a t i o n . 73 // 74 // P a r a m e t e r s : 75 // 76 // − ‘ o r i g i n a l ‘ : g o c v . M a t −> M a t r i x t o r o t a t e 77 // − ‘ r o t a t e d ‘ : *g o c v . M a t −> R o t a t e d M a t r i x 78 // − ‘ a n g l e ‘ : i n t −> r o t a t i o n a n g l e 79 // 80 func R o t a t e ( o r i g i n a l gocv.Mat , rotated *gocv.Mat , a n g l e i n t ) { 81 c o l s , r o w s : = o r i g i n a l . C o l s ( ) , o r i g i n a l . R o w s ( ) 82 c e n t e r : = image.Point { c o l s / 2 , r o w s / 2 } 83 r o t a t i o n : = g o c v . G e t R o t a t i o n M a t r i x 2 D ( c e n t e r , float64( − a n g l e ) , 1 . 0 ) 84 g o c v . W a r p A f f i n e W i t h P a r a m s ( o r i g i n a l , r o t a t e d , r o t a t i o n , image.Point { cols , r ow s } , g o c v . I n t e r p o l a t i o n N e a r e s t N e i g h b o r , g o c v . B o r d e r C o n s t a n t , c o l o r . R G B A { 0 , 0 , 0 , 0 } ) 85 } B.2 Protocol Buffers File B.10: Code of message.proto 1 syntax = ” p r o t o 3 ” ; 2package pb ; 3 4option g o _ p a c k a g e = ” g i t h u b . c o m / a r d a n l a b s / p y t h o n − go / g r p c / pb ” ; 5 123
6message O b j e c t _ O m n i { 7uint32 i d = 1 ; 8uint32 x = 2 ; 9uint32 y = 3 ; 10 uint32 d i s t = 4 ; 11 uint32 c o n f = 6 ; 12 } 13 14 message Request_Omni_Calib { 15 b o o l c h e c k = 1 ; 16 } 17 18 message R e s p o n s e _ O m n i { 19 bytes omn i = 1 ; 20 uint32 img_to_send = 2; 21 repeated O b j e c t _ O m n i o b j e c t s = 3 ; // l i s t o f 3 b y t e s ’ c l a s s e ’ ’ x ’ ’ y ’ 22 23 } 24 25 service Yolo_Omni { 26 rpc Send_Omni( Request_Omni_Calib ) returns ( s t r e a m R e s p o n s e _ O m n i ) { } 27 } B.3 Python B.3.1 gRPC Server File B.11: Code of server.py 1f r o m concurrent.futures i m p o r t T h r e a d P o o l E x e c u t o r 2i m p o r t grpc 3i m p o r t numpy as np 4i m p o r t PySpin 5i m p o r t EasyPySpin 6i m p o r t c v 2 a s c v 7 print (” I m p o r t i n g Y O L O . . . ” ) 8f r o m ultralytics i m p o r t YOLO 9 print (” YOLO I m p o r t e d ! ” ) 10 i m p o r t c v 2 11 i m p o r t time 12 f r o m message_pb2 i m p o r t Resp onse_O mni , O b j e c t _ O m n i 13 f r o m m e s s a g e _ p b 2 _ g r p c i m p o r t Yolo_OmniServicer , add_Yolo_OmniServicer_to_server 14 i m p o r t time 15 i m p o r t bisect 16 i m p o r t sys 17 18 # Load model 19 m o d e l = YOLO ( ” t r a i n e d _ w e i g h t s / b e s t . p t ” ) 20 21 # D e f i n e t h e c o o r d i n a t e s t o f i n d t h e c l o s e s t p o i n t t o 22 t a r g e t = n p . a r r a y ( [ 4 8 0 , 4 8 0 ] ) 23 24 # Pr e − c o m p u t e t h e d i s t a n c e m a t r i x 25 x , y = n p . m e s h g r i d ( n p . a r a n g e ( 4 8 0 ) , n p . a r a n g e ( 4 8 0 ) ) 124
26 d i s t a n c e s = n p . s q r t ( ( x − t a r g e t [ 0 ] ) **2 + ( y − t a r g e t [ 1 ] ) **2 ) 27 28 d e f s o r t _ o m n i ( i t e m ) : 29 r e t u r n i t e m . d i s t 30 31 a c t u a l _ f r a m e = n p . z e r o s ( ( 4 8 0 , 4 8 0 , 3 ) , d t y p e = n p . u i n t 8 ) 32 d e f o p e n _ f r a m e _ s o u r c e ( ) : 33 g l o b a l o m n i c a p 34 try : 35 o m n ic a p = E a s y P y S p i n . V i d e o C a p t u r e ( 0 ) 36 o m n i c a p . c a m . P i x e l F o r m a t . S e t V a l u e ( P y S p i n . P i x e l F o r m a t _ R G B 8 P a c k e d ) 37 r e t u r n 38 except : 39 p r i n t ( ” Can ’ t Open Omni C a m e r a . . . V e r i f y C o n n e c t i o n ” ) 40 omnicap = cv2.VideoCapture (” / home / r o b o t 3 / D e s k t o p / T e se S L e n d e r / R e s u l t a d o s SASUM /3/ M y V i d e o . a v i ” ) 41 o m n i c a p . s e t ( cv.CAP_PR OP _FPS , 3 0 0 ) 42 43 l a s t _ f r a m e = n p . z e r o s ( ( 4 8 0 , 4 8 0 , 1 ) , d t y p e = n p . u i n t 8 ) 44 a c t u a l _ f r a m e _ o m n i = n p . z e r o s ( ( 4 8 0 , 4 8 0 , 1 ) , d t y p e = n p . u i n t 8 ) 45 d e f g e t _ o m n i _ f r a m e ( f r a m e _ b c k u p = 1 ) : 46 g l o b a l o m n i c a p 47 g l o b a l m o d e l 48 g l o b a l distances 49 g l o b a l last_frame 50 r e t , i m a g e _ t e s t = o m n i c a p . r e a d ( ) 51 i f ( r e t ) : 52 f r a m e _ o m n i = c v . c v t C o l o r ( i m a g e _ t e s t , cv.COLOR_BGR2RGB ) 53 l a s t _ f r a m e = f r a m e _ o m n i 54 e l s e : 55 f r a m e _ o m n i = l a s t _ f r a m e 56 r e t u r n 1 , f r a m e _ o m n i 57 c l a s s e s 2 = [ ” B a l l ” ,” B l u e _ S h i r t ” ,” G o a l ” ,” P e r s o n ” ,” R e d _ S h i r t ” ,” R o b o t ” ] 58 59 d e f Yolo_Ifer_Omni () : 60 g l o b a l actual_frame_omni 61 _ , f r a m e = g e t _ o m n i _ f r a m e ( ) 62 f r a m e _ o r i = f r a m e . c o p y ( ) 63 r e s u l t s = m o d e l . p r e d i c t ( s o u r c e = frame , c o n f =0 .60 , v e r b o s e = F a l s e ) 64 o b j e c t s = [ ] 65 i d x =0 66 for i n d e x , b o x i n e n u m e r a t e ( r e s u l t s [ 0 ] . b o x e s ) : 67 i d x = i n d e x 68 p o i n t s = r e s u l t s [ 0 ] . m a s k s . x y [ i n d e x ] 69 # F i n d t h e i n d e x o f t h e p o i n t w i t h t h e s m a l l e s t d i s t a n c e 70 i f l e n ( p o i n t s [ : , 1 ] ) >0: 71 c l o s e s t _ i n d e x = n p . a r g m i n ( d i s t a n c e s [ p o i n t s [ : , 1 ] . a s t y p e ( i n t ) , p o i n t s [ : , 0 ] . a s t y p e ( i n t ) ] ) . a s t y p e ( i n t ) 72 o b j e c t _ a t u a l = O b j e c t _ O m n i ( i d = i n t ( b o x . c l s [ 0 ] ) , x = i n t ( p o i n t s [ c l o s e s t _ i n d e x ] [ 0 ] ) , y = i n t ( p o i n t s [ c l o s e s t _ i n d e x ] [ 1 ] ) , d i s t = i n t ( distances [ i n t ( p o i n t s [ c l o s e s t _ i n d e x ] [ 0 ] ) ] [ i n t ( p o i n t s [ c l o s e s t _ i n d e x ] [ 1 ] ) ] ) , c o n f = i n t ( b o x . c o n f [ 0 ] *100 ) ) 73 i f ( i d x > 0 ) : 74 b i s e c t . i n s o r t ( o b j e c t s , o b j e c t _ a t u a l , k e y = s o r t _ o m n i ) 75 a c t u a l _ f r a m e _ o m n i = f r a m e 76 r e t u r n f r a m e _ o r i , o b j e c t s 77 c l a s s e s = [ ” B a l l ” ,” B l u e _ S h i r t ” ,” G o a l ” ,” P e r s o n ” ,” R e d _ S h i r t ” ,” R o b o t ” ] 78 125
79 o m n i i m g _ t o _ s e n d = n p . z e r o s ( ( 4 8 0 , 4 8 0 , 1 ) , d t y p e = n p . u i n t 8 ) 80 81 class Y o l o _ g r p c S e r v e r _ o m n i ( Y o l o _ O m n i S e r v i c e r ) : 82 d e f Send_Omni ( s e l f , r e q u e s t , c o n t e x t ) : 83 g l o b a l omniimg_to_send 84 g l o b a l start_time 85 s t a r t = t i m e . t i m e ( ) 86 w h i l e 1 : 87 img_ omni , o b j e c t s = Y o l o _ I f e r _ O m n i ( ) 88 i f ( r e q u e s t . c h e c k == T r u e ) : 89 o m n i i m g _ t o _ s e n d = n p . f r o m b u f f e r ( r e q u e s t . i m a g e , d t y p e = n p . u i n t 8 ) 90 r e s p = R e s p o n s e _ O m n i ( o mn i = bytes ( i mg _ o m n i ) , o b j e c t s = o b j e c t s ) 91 yield resp 92 93 94 i f __name__ == ’ __main__ ’ : 95 g l o b a l n_robot 96 p r i n t ( ” O p e n i n g O m n i C a m e r a . . . ” ) 97 o p e n _ f r a m e _ s o u r c e ( ) 98 p r i n t ( ” Omn iC ame ra o p e n e d ! ” ) 99 p r i n t ( ” O p e n i n g gRPC S e r v e r . . . ” ) 100 s e r v e r = g r p c . s e r v e r ( T h r e a d P o o l E x e c u t o r ( ) ) 101 a d d _ Y o l o _ O m n i S e r v i c e r _ t o _ s e r v e r ( Y o l o _ g r p c S e r v e r _ o m n i ( ) , s e r v e r ) 102 p r i n t ( ” Omni Add ed ” ) 103 n _ r o b o t = i n t ( s y s . a r g v [ 1 ] ) 104 i p _ g r p c = s y s . a r g v [ 2 ] 105 p o r t = 40000 106 server.add_insecure_port ( f ’ { i p _ g r p c } : { p o r t } ’ ) 107 server.start () 108 p r i n t ( f ’ gRPC S e r v e r r e a d y on I P { i p _ g r p c } : { p o r t } ’ ) 109 s e r v e r . w a i t _ f o r _ t e r m i n a t i o n ( ) B.3.2 Calibration Tool File B.12: Code of calibration_tool.py 1# ! / u s r / b i n / e n v p y t h o n 3 2” ” ” ! @ b r i e f C a l i b r a t i o n o f t h e c o l o r s o f t h e f i e l d . ” ” ” 3## 4# @mainpage C a l i b r a t i o n 5# 6# @ s e c t i o n d e s c r i p t i o n _ m a i n D e s c r i p t i o n 7# To e a s y c a l i b r a t e a l l c a m era v a r i a b l e s . 8# A l l t h e s e n t t i n g s s h o u l d be s a v e i n a . g o f i l e . 9# 10 # @ s e c t i o n n o t e s _ m a i n C a l i b r a t i o n s 11 # c a l i b _ c a m _ o m n i . p y −> C a l i b r a t e s Omni Camera C o l o u r . 12 # 13 # C o p y r i g h t ( c ) 2022 M i n h o T e a m . A l l r i g h t s r e s e r v e d . 14 ## 15 # @ f i l e c a l i b _ c a m _ o m n i . p y 16 # 17 # @ b r i e f C a l i b r a t e s Omni Ca m er a . 18 # 19 # 20 # @ s e c t i o n l i b r a r i e s _ m a i n L i b r a r i e s / M o d u l e s 126
21 # − t i m e s t a n d a r d l i b r a r y ( h t t p s : / / d o c s . p y t h o n . o r g /3/ l i b r a r y / t i m e . h t m l ) 22 # − A c c e s s t o s l e e p f u n c t i o n . 23 # − open CV s t a n d a r t l i b r a r y ( h t t p s : / / d o c s . p y t h o n . o r g /3/ l i b r a r y / o p e n c v . h t m l ) 24 # − A c c e s s t o Camera and C o mp u t er V i s i o n f u n c t i o n . 25 # 26 # @ s e c t i o n n o t e s _ d o x y g e n _ e x a m p l e N o t e s 27 # − Comments a r e D ox y g e n c o m p a t i b l e . 28 # 29 # 30 # \ t e s t 31 # − C a p t u r e i m age f ro m came r a 32 # 33 # \ bug 34 # − F l y c a m e r a c a p t u r e 35 36 # @section author_doxygen_example Author (s) 37 # − C r e a t e d b y J o s é M a r t i n s on 24/11/2022 . 38 # − M o d i f i e d by J o s é M a r t i n s on 01/03/2023 . 39 # 40 # C o p y r i g h t ( c ) 2023 M i n h o T e a m . A l l r i g h t s r e s e r v e d . 41 42 43 # Imports 44 i m p o r t os 45 i m p o r t PySpin 46 i m p o r t EasyPySpin 47 f r o m g c i m p o r t callbacks 48 i m p o r t PySimpleGUI as s g 49 i m p o r t c v 2 a s c v 50 i m p o r t numpy as np 51 f r o m numpy i m p o r t a r a n g e 52 i m p o r t math 53 i m p o r t sys 54 i m p o r t keyboard 55 f r o m time i m p o r t time 56 f r o m matplotlib i m p o r t pyplot a s plt 57 f r o m scipy.optimize i m p o r t curve_fit 58 59 60 d e f ma in ( ) : 61 sg.theme (”LightGreen”) 62 63 # C r e a t e t h e wi n d o w and show 64 w i n d ow = s g . W i n d o w ( ” LAR C a l i b r a t i o n ” , t a b g r p , b a c k g r o u n d _ c o l o r = ’ firebrick4 ’, l o c a t i o n = ( 8 0 0 , 4 00) ) 65 66 e v e n t , v a l u e s = w i n d o w . r e a d ( t i m e o u t = 2 0 ) 67 read_omni_consts_file (window) 68 r e a d _ f i e l d _ c o n s t s _ f i l e ( w i n d o w ) 69 o p e n _ f r a m e _ s o u r c e ( ) 70 r e t , f r a m e _ b c k u p = g e t _ f r a m e ( ) 71 u p d a t e _ s l i d e r s ( window , v a l u e s ) 72 n o w _ f r a m e =0 73 Pa u s e = F a l s e 74 R e c o r d = F a l s e 75 b a l l _ i n d e x = 0 76 x _ a r r a y _ b a l l = [ ] 77 x_array_ball.append (0) 127
78 y _ a r r a y _ b a l l = [ ] 79 y_array_ball.append (0) 80 g l o b a l o u t 81 w i n d o w [ ” −2MAXH2 − ” ] . u p d a t e ( v a l u e = 2 55 ) 82 w i n d o w [ ” −2MINH2 − ” ] . u p d a t e ( v a l u e = 0 ) 83 w i n d o w [ ” −2MAXS2 − ” ] . u p d a t e ( v a l u e = 2 55) 84 w i n d o w [ ” −2 MINS2 − ” ] . u p d a t e ( v a l u e = 0 ) 85 w i n d o w [ ” −2MAXV2 − ” ] . u p d a t e ( v a l u e = 2 55 ) 86 w i n d o w [ ” −2 MINV2 − ” ] . u p d a t e ( v a l u e = 0 ) 87 w i n d o w [ ” −OFF2 − ” ] . u p d a t e ( v a l u e = 2 40) 88 89 w h i l e T r u e : 90 91 i f ( n o t P a u s e ) : 92 r e t , f r a m e _ o r i = g e t _ f r a m e ( f r a m e _ b c k u p ) 93 h e i g h t = f r a m e _ o r i . s h a p e [ 0 ] 94 w i d t h = f r a m e _ o r i . s h a p e [ 1 ] 95 c h a n n e l s = f r a m e _ o r i . s h a p e [ 2 ] 96 e v e n t , v a l u e s = w i n d o w . r e a d ( t i m e o u t = 2 0) 97 r e a d _ s l i d e r ( v a l u e s ) 98 S e l e c t _ O b j e c t ( window , e v e n t , v a l u e s ) 99 update_me n u ( window , e v e n t ) 100 101 # BUTTON EVENT DETECTION 102 i f ( e v e n t == ” E x i t ” o r e v e n t == sg.WIN _CL OSED ) and s g . p o p u p _ y e s _ n o (’ Do y ou s a v e ? ’ ) == ’ Y e s ’ : 103 b r e a k 104 e l i f e v e n t == ” S a v e ” : 105 f i l e _ w = s a v e _ f i l e ( ) 106 e l i f e v e n t == ” C a l i b r a t e F r o n t ” o r e v e n t == ” C a l i b r a t e Omni ” : 107 u p d a t e _ s l i d e r s ( window , v a l u e s ) 108 e l i f e v e n t == ” P a u s e ” : 109 P a u s e = T r u e 110 e l i f e v e n t == ” C o n t i n u e ” : 111 Pau s e = F a l s e 112 e l i f e v e n t == ” R e s t a r t ” : 113 restart_video () 114 e l i f e v e n t == ” − R e c o r d − ” : 115 i f ( n o t R e c o r d ) : 116 R e c o r d = T r u e 117 w i n d o w [ ” − R e c o r d − ” ] . u p d a t e ( i m a g e _ f i l e n a m e = i m a g e _ r e c o r d i n g , image_subsample =4) 118 # D e f i n e t h e c o d e c and c r e a t e V i d e o W r i t e r o b j e c t . T h e o u t p u t i s s t o r e d i n ’ o u t p y . a v i ’ f i l e . 119 o u t = c v . V i d e o W r i t e r ( v a l u e s [ ” −SAVE_V − ” ] , cv.VideoWriter_fourcc ( ’M ’ ,’ J ’ ,’ P ’ ,’ G ’ ) , 10 , ( w i d t h , h e i g h t ) ) 120 e l i f e v e n t == ” S av e R e c o r d ” : 121 i f Record : 122 R e c o r d = F a l s e 123 w i n d o w [ ” − R e c o r d − ” ] . u p d a t e ( i m a g e _ f i l e n a m e = i m a g e _ r e c , image_subsample =4) 124 o u t . r e l e a s e ( ) 125 e l i f e v e n t == ” − SAVE_D IST − ” : 126 w i n d o w [ ” − SAV E_DIST − ” ] . u p d a t e ( ” S a v i n g . . . . ” ) 127 i f Calibration ==0: 128 c a l c _ d i s t _ o m n i ( a , b , c , d , e , f , g ) 129 s a v e _ o m n i _ t a b l e s _ f i l e ( ) 128
130 e l s e : 131 save_front_tables_file () 132 w i n d o w [ ” − SAVE_DIST − ” ] . u p d a t e ( ” D i s t a n c e s S av e d ! ” ) 133 e l i f e v e n t == ” − SA VE_DIST_ BAL L − ” : 134 w i n d o w [ ” − SAVE _DIST_BA LL − ” ] . u p d a t e ( ” S a v i n g . . . . ” ) 135 i f Calibration ==0: 136 c a l c _ d i s t _ o m n i _ b a l l ( a _ b a l l , b _ b a l l , c _ b a l l , d _ b a l l , e _ b a l l , f _ b a l l , g _ b a l l ) 137 save_omni_ball_tables_file () 138 e l s e : 139 save_omni_ball_tables_file () 140 w i n d o w [ ” − SAVE _DIST_BALL − ” ] . u p d a t e ( ” D i s t a n c e s S a ve d ! ” ) 141 e l i f e v e n t == ” −SAVE_CONST − ” : 142 window [ ” −SAVE_CONST − ” ] . u p d a t e ( ” S a v i n g . . . . ” ) 143 i f Calibration ==0: 144 save_omni_consts_file () 145 e l s e : 146 save_front_consts_file () 147 w i n d o w [ ” −SAVE_CONST − ” ] . u p d a t e ( ” C o n s t a n t s Sa v ed ! ” ) 148 e l i f e v e n t == ” − SAVE_ FIE LD − ” : 149 s a v e _ f i e l d _ c o n s t s _ f i l e ( v a l u e s ) 150 s a v e _ m a p _ f i e l d ( v a l u e s ) 151 s a v e _ m a p _ f i e l d 2 ( v a l u e s ) 152 153 i f ( R e c o r d ) : 154 o u t . w r i t e ( f r a m e _ o r i ) 155 156 f r a m e = c v . c v t C o l o r ( f r a m e _ o r i , cv.COLOR_BGR2HSV ) 157 158 # PROCESS THE SELECTED TAB 159 i f values [ ’_TAB_GROUP_ ’ ] == ” −TAB_CENTER − ” : 160 # === C e n t e r === 161 # P i x e l v a l u e s i n o r i g i n a l i m a ge 162 f r a m e _ c e n t e r = f r a m e _ o r i . c o p y ( ) 163 c v . l i n e ( f r a m e _ c e n t e r , ( i n t ( w i d t h / 2 ) , 0 ) , ( i n t ( w i d t h / 2 ) , h e i g h t ) , ( 0 , 0 , 2 5 5 ) , 1 ) 164 c v . l i n e ( f r a m e _ c e n t e r , ( 0 , i n t ( h e i g h t / 2 ) ) , ( w i d t h , i n t ( h e i g h t / 2 ) ) , ( 0 , 0 , 2 5 5 ) , 1 ) 165 c v . c i r c l e ( f r a m e _ c e n t e r , ( i n t ( w i d t h / 2 ) , i n t ( h e i g h t / 2 ) ) , 5 , ( 0 , 0 , 2 5 5 ) , −1) 166 c e n t e r b y t e s = c v . i m e n c o d e ( ” . p n g ” , f r a m e _ c e n t e r ) [ 1 ] . t o b y t e s ( ) 167 w i n d o w [ ” −IMAGE_CENTER − ” ] . u p d a t e ( d a t a = c e n t e r b y t e s ) 168 169 e l i f v a l u e s [ ’_TAB_GROUP_ ’ ] == ” −TAB_MAP − ” : 170 p l o t _ f u n c = n p . z e r o s ( ( 3 0 0 , 2 4 0 , 3 ) ) 171 f r a m e _ o r i _ d i s t = f r a m e _ o r i . c o p y ( ) 172 x _ a r r a y = [ ] 173 x_array.append (0) 174 y _ a r r a y = [ ] 175 y _ a r r a y . a p p e n d ( 0 ) 176 x_array.append (13) 177 y _ a r r a y . a p p e n d ( 8 ) 178 x_array.append (19) 179 y _ a r r a y . a p p e n d ( 1 2 ) 180 x_array.append (25) 181 y _ a r r a y . a p p e n d ( 1 5 ) 182 f r a m e _ d i s t = c v . i n R a n g e ( f r a m e , ( v a l u e s [ ” −2MINH2 − ” ] , values [” −2 MINS2 − ” ] , values [” −2 MINV2 − ” ] ) , ( v a l u e s [ ” −2MAXH2 − ” ] , values [” 129
−2MAXS2 − ” ] , values [” −2MAXV2 − ” ] ) ) # T r e s h 183 last=frame_dist [240][ i n t ( values [” −OFF2 − ” ] ) ] 184 c o u n t =0 185 l a s t _ i n d e x =0 186 for yi n r a n g e ( 2 4 0 ) : 187 i f ( f r a m e _ d i s t [ 2 4 0 + y ] [ i n t ( values [” −OFF2 − ” ] ) ] ! = l a s t an d c o u n t <len ( dists_calibration )): 188 c v . c i r c l e ( f r a m e _ o r i _ d i s t , ( i n t ( values [” −OFF2 − ” ] ) ,240+ y ) , 3 , ( 0 , 0 , 2 5 5 ) , −1) 189 l a s t = f r a m e _ d i s t [2 4 0 + y ] [ i n t ( values [” −OFF2 − ” ] ) ] 190 x_array.append (y) 191 y _ a r r a y . a p p e n d ( d i s t s _ c a l i b r a t i o n [ c o u n t ] ) 192 l a s t _ i n d e x = ( d i s t s _ c a l i b r a t i o n [ c o u n t ] ) 193 c v . c i r c l e ( p l o t _ f u n c , ( y , i n t (2 9 9 − ( d i s t s _ c a l i b r a t i o n [ c o u n t ]*0 . 3 ) ) ) , 5 , ( 2 5 5 , 0 , 0 ) , −1) 194 195 c o u n t +=1 196 i f ( c o u n t > 6 ) : 197 198 # c u r v e f i t 199 p opt , _ = c u r v e _ f i t ( o b j e c t i v e , x _ a r r a y , y _ a r r a y ) 200 # s u mm a ri z e t h e p a r a m e t e r v a l u e s 201 a , b , c , d , e , f , g = p o p t 202 p r i n t ( min ( x _ a r r a y ) ) 203 x _ l i n e = a r a n g e ( min ( x _ a r r a y ) , max ( x _ a r r a y ) , 1 ) 204 y _ l i n e = o b j e c t i v e ( x _ l i n e , a , b , c , d , e , f , g ) 205 e q u a t i o n = ” E q u a t i o n : y = ” + s t r ( a ) + ”⁶x + ” + s t r ( b ) + ”⁵x + ” + s t r ( c ) + ”⁴x + ” + s t r ( d ) + ” x ³ + ” + s t r ( e ) + ” x ² + ” + s t r ( f ) + ” x + ” + s t r ( g ) 206 w i n d o w [ ” − E q u a t i o n − ” ] . u p d a t e ( e q u a t i o n ) 207 208 for i n d e x , x i n e n u m e r a t e ( x _ l i n e ) : 209 210 i f (0 <= i n d e x <300 and 0<= x <300 ) : 211 i f 0> i n t (3 0 0 − ( y _ l i n e [ i n d e x ] *0 . 3 ) ) : 212 p l o t _ f u n c [ 2 9 9 ] [ x ] [ 2 ] = 2 5 5 213 e l i f i n t ( 3 0 0 − ( y _ l i n e [ i n d e x ] *0 . 3 ) ) > =30 0: 214 p l o t _ f u n c [ 0 ] [ x ] [ 2 ] = 2 5 5 215 e l s e : 216 plot_func [ i n t ( 2 9 9 − ( y _ l i n e [ i n d e x ] *0 . 3 ) ) ] [ x ] [ 2 ] = 2 5 5 217 218 p l o t _ f u n c [ 0 ] [ x ] [ 0 ] = 2 5 5 219 p l o t _ f u n c [ 5 0 ] [ x ] [ 0 ] = 2 5 5 220 p l o t _ f u n c [ 1 0 0 ] [ x ] [ 0 ] = 2 5 5 221 p l o t _ f u n c [ 1 5 0 ] [ x ] [ 0 ] = 2 5 5 222 p l o t _ f u n c [ 2 0 0 ] [ x ] [ 0 ] = 2 5 5 223 p l o t _ f u n c [ 2 5 0 ] [ x ] [ 0 ] = 2 5 5 224 p r i n t ( [ l a s t _ i n d e x ] ) 225 i m g o r i b y t e s 2 = c v . i m e n c o d e ( ” . p n g ” , f r a m e _ o r i _ d i s t ) [ 1 ] . t o b y t e s ( ) 226 i m g b y t e s 2 = c v . i m e n c o d e ( ” . p n g ” , f r a m e _ d i s t ) [ 1 ] . t o b y t e s ( ) 227 p l o t b y t e s = c v . i m e n c o d e ( ” . p n g ” , p l o t _ f u n c ) [ 1 ] . t o b y t e s ( ) 228 w i n d o w [ ” − IMAGE_ORI2 − ” ] . u p d a t e ( d a t a = i m g o r i b y t e s 2 ) 229 w i n d o w [ ” −IMAGE2 − ” ] . u p d a t e ( d a t a = i m g b y t e s 2 ) 230 w i n d o w [ ” −IMAGE_PLOT − ” ] . u p d a t e ( d a t a = p l o t b y t e s ) 231 i f c o u n t < len ( dists_calibration ): 232 p r i n t ( y , d i s t s _ c a l i b r a t i o n [ c o u n t ] ) 233 130
234 # when b a l l c a l i b r a t i o n t a b i s open 235 e l i f v a l u e s [ ’_TAB_GROUP_ ’ ] == ” −TAB_BALL − ” : 236 p l o t _ f u n c = n p . z e r o s ( ( 3 0 0 , 2 4 0 , 3 ) ) 237 f r a m e _ o r i _ d i s t = f r a m e _ o r i . c o p y ( ) 238 f r a m e _ d i s t = c v . i n R a n g e ( f r a me , ( c o d e _ o m n i [ 1 ] [ 1 ] , c o d e _ o m n i [ 3 ] [ 1 ] , c o d e _ o m n i [ 5 ] [ 1 ] ) , ( c o d e _ o m n i [ 0 ] [ 1 ] , c o d e _ o m n i [ 2 ] [ 1 ] , c o d e _ o m n i [ 4 ] [ 1 ] ) ) 239 c o n t o u r s , _ = c v . f i n d C o n t o u r s ( f r a m e _ d i s t , cv . R ETR_EX T E R NAL , cv.CHAIN_APPROX_SIMPLE ) 240 t r y : 241 b e s t _ c o n t o u r = c o n t o u r s [ 0 ] 242 b e s t _ d i s t =10000 243 b e s t _ x =0 244 for i , contour i n e n u m e r a t e ( c o n t o u r s ) : 245 i f c o d e _ o m n i [ 4 0 ] [ 1 ] < c v . c o n t o u r A r e a ( c o n t o u r ) < c o d e _ o m n i [39][1]: 246 247 e l l i p s e = c v . f i t E l l i p s e ( c o n t o u r ) 248 f r a m e _ o r i _ d i s t = c v . c i r c l e ( f r a m e _ o r i _ d i s t , ( r o u n d ( e l l i p s e [ 0 ] [ 0 ] ) , r o u n d ( e l l i p s e [ 0 ] [ 1 ] ) ) , 4 , ( 0 , 0 , 2 5 5 ) , −1) 249 i f a b s ( e l l i p s e [ 0 ] [ 0 ] − 2 3 9 ) < b e s t _ d i s t : 250 b e s t _ c o n t o u r = c o n t o u r s [ i ] 251 b e s t _ d i s t = abs ( e l l i p s e [ 0 ] [ 0 ] − 2 3 9 ) 252 b e s t _ y =239 − e l l i p s e [ 0 ] [ 1 ] 253 254 c v . d r a w C o n t o u r s ( f r a m e _ o r i _ d i s t , [ b e s t _ c o n t o u r ] , 0 , ( 0 , 0 , 0 ) , 3 ) 255 p r i n t ( r e a l _ d i s t _ o m n i _ b a l l [ r o u n d ( e l l i p s e [ 0 ] [ 0 ] ) ] [ r o u n d ( e l l i p s e [ 0 ] [ 1 ] ) ] [ 0 ] ) 256 coordenates_ball_str = ” X = ” + s t r ( r e a l _ d i s t _ o m n i _ b a l l [ r o u n d ( e l l i p s e [ 0 ] [ 0 ] ) ] [ r o u n d ( e l l i p s e [ 0 ] [ 1 ] ) ] [ 0 ] ) + ” Y = ” + s t r ( r e a l _ d i s t _ o m n i _ b a l l [ r o u n d ( e l l i p s e [ 0 ] [ 0 ] ) ] [ r o u n d ( e l l i p s e [ 0 ] [ 1 ] ) ] [ 1 ] ) + ”D= ” + s t r ( r e a l _ p o l a r _ o m n i _ b a l l [ r o u n d ( e l l i p s e [ 0 ] [ 0 ] ) ] [ r o u n d ( e l l i p s e [ 0 ] [ 1 ] ) ] [ 0 ] ) + ” A= ” + s t r ( r e a l _ p o l a r _ o m n i _ b a l l [ r o u n d ( e l l i p s e [ 0 ] [ 0 ] ) ] [ r o u n d ( e l l i p s e [ 0 ] [ 1 ] ) ] [ 1 ] ) 257 w i n d o w [ ” − C o o r d e n a t e s _ B a l l − ” ] .update ( coordenates_ball_str ) 258 259 except : 260 p r i n t ( ” Sem B o l a ” ) 261 262 263 i f event == ”−SAVE_BALL −” : 264 b a l l _ i n d e x +=1 265 i f b a l l _ i n d e x >= len ( b a l l _ c a l i b r a t i o n ) : 266 t e x t = ” B a l l C a l i b r a t i o n i s r e a d y ! ” 267 w i n d o w [ ” − P u t _ b a l l − ” ] . u p d a t e ( t e x t ) 268 p r i n t ( ” X1 ” , x_array_ball ) 269 p r i n t ( ” Y1 ” , y _ a r r a y _ b a l l ) 270 p o pt , _ = c u r v e _ f i t ( o b j e c t i v e , x _ a r r a y _ b a l l , y _ a r r a y _ b a l l ) 271 272 # s u mm a ri z e t h e p a r a m e t e r v a l u e s 273 a _ b a l l , b _ b a l l , c _ b a l l , d _ b a l l , e _ b a l l , f _ b a l l , g _ b a l l = p o p t 274 w i n d o w [ ” − SAVE _DI ST_BALL − ” ] . u p d a t e ( ” S a v i n g . . . . ” ) 275 i f Calibration ==0: 131
276 c a l c _ d i s t _ o m n i _ b a l l ( a _ b a l l , b _ b a l l , c _ b a l l , d _ b a l l , e _ b a l l , f _ b a l l , g _ b a l l ) 277 save_omni_ball_tables_file () 278 e l s e : 279 save_omni_ball_tables_file () 280 w i n d o w [ ” − SAVE _DIST_BALL − ” ] . u p d a t e ( ” D i s t a n c e s S a ve d ! ” ) 281 x _ l i n e = a r a n g e ( min ( x _ a r r a y _ b a l l ) , max ( x _ a r r a y _ b a l l ) , 1 ) 282 y _ l i n e = o b j e c t i v e ( x _ l i n e , a _ b a l l , b _ b a l l , c _ b a l l , d _ b a l l , e _ b a l l , f _ b a l l , g _ b a l l ) 283 #Plot 284 e q u a t i o n = ” E q u a t i o n : y = ” + s t r ( a _ b a l l ) + ”⁶x + ” + s t r ( b _ b a l l ) + ”⁵x + ” + s t r ( c _ b a l l ) + ”⁴x + ” + s t r ( d _ b a l l ) + ” x ³ + ”+ s t r ( e _ b a l l ) + ” x ² + ” + s t r ( f _ b a l l ) + ” x + ” + s t r ( g _ b a l l ) 285 w i n d o w [ ”−Equation_Ball −”] . u p d a t e ( e q u a t i o n ) 286 287 e l s e : 288 t e x t = ” P u t B a l l a t ” + s t r ( l a b e l _ b a l l _ c a l i b r a t i o n [ b a l l _ i n d e x ] / 1 0 0 ) + ” M e t e r s t o t h e c e n t e r o f t h e r o b o t ” 289 w i n d o w [ ” − P u t _ b a l l − ” ] . u p d a t e ( t e x t ) 290 x _ a r r a y _ b a l l . a p p e n d ( − b e s t _ y ) # C e n t e r o f t h e b a l l 291 y _ a r r a y _ b a l l . a p p e n d ( b a l l _ c a l i b r a t i o n [ b a l l _ i n d e x − 1 ] ) 292 p r i n t ( ” B e s t Y ” , − b e s t _ y , b a l l _ c a l i b r a t i o n [ b a l l _ i n d e x − 1 ] ) 293 294 295 296 297 i m g o r i b y t e s 3 = c v . i m e n c o d e ( ” . p n g ” , f r a m e _ o r i _ d i s t ) [ 1 ] . t o b y t e s ( ) 298 i m g b y t e s 3 = c v . i m e n c o d e ( ” . p n g ” , f r a m e _ d i s t ) [ 1 ] . t o b y t e s ( ) 299 p l o t b y t e s 1 = c v . i m e n c o d e ( ” . p n g ” , p l o t _ f u n c ) [ 1 ] . t o b y t e s ( ) 300 w i n d o w [ ” − IMAGE_ORI4 − ” ] . u p d a t e ( d a t a = i m g o r i b y t e s 3 ) 301 w i n d o w [ ” −IMAGE4 − ” ] . u p d a t e ( d a t a = i m g b y t e s 3 ) 302 w i n d o w [ ”−IMAGE_PLOT2 −” ] . u p d a t e ( d a t a = p l o t b y t e s 1 ) 303 304 e l i f v a l u e s [ ’ _TAB_GROUP_ ’ ] == ” −TAB_HSV − ” : 305 # === HSV T r e s h o l d === 306 f r a m e = c v . i n R a n g e ( f r a m e , ( v a l u e s [ ” −MINH − ” ] , values [” −MINS − ” ] , values [” −MINV − ” ] ) , ( v a l u e s [ ” −MAXH− ” ] , values [” −MAXS − ” ] , values [” −MAXV − ” ] ) ) # T r e s h 307 c o n t o u r s , h i e r a r c h y = c v . f i n d C o n t o u r s ( f r a m e , cv.RETR_CCOMP , cv.CHAIN_APPROX_NONE ) 308 i m g b y t e s = c v . i m e n c o d e ( ” . p n g ” , f r a m e ) [ 1 ] . t o b y t e s ( ) 309 w i n d o w [ ” −IMAGE − ” ] . u p d a t e ( d a t a = i m g b y t e s ) 310 # e x c e p t : 311 # i m g b y t e s = c v . i m e n c o d e ( ” . p n g ” , f r a m e ) [ 1 ] . t o b y t e s ( ) 312 # wi nd ow [ ” − IMAGE − ” ] . u p d a t e ( d a t a = i m g b y t e s ) 313 314 e l i f v a l u e s [ ’ _TAB_GROUP_ ’ ] == ” −TAB_WARP − ” : 315 # === Warp === 316 # P i x e l v a l u e s i n o r i g i n a l im a g e 317 f r a m e _ w a r p e d = f r a m e _ o r i . c o p y ( ) 318 t l _ p o i n t = [ 0 , 0 ] 319 t r _ p o i n t = [ w i d t h , 0 ] 320 b l _ p o i n t = [ 0 , h e i g h t ] 321 b r _ p o i n t = [ w i d t h , h e i g h t ] 132