Full text
id183136 ANIMAL TRACKING AND IDENTIFICATION IN SMART FARMS ALBERT COMPTE PRADES Director/a: SERGIOESCALERAGUERRERO(UniversitatdeBarcelona) Codirector/a: JULIOCEZARSILVEIRAJACQUES-JUNIOR Titulació:MasterinArtificialIntelligence Memòria del treball de fi de màster School of Engineering Universitat Rovira i Virgili (URV) Faculty of Mathematics Universitat de Barcelona (UB) Barcelona School of Informatics (FIB) Universitat Politècnica de Catalunya (UPC) - BarcelonaTech 15/05/2024
T´ıtol: Seguiment i identificaci´ o d’animals en granges intel·ligents Autor: Albert Compte Prades Directors: Sergio Escalera Guerrero Julio Cezar Silveira Jacques-Junior Data: 8 de maig de 2024 Resum Amb l’increment de la demanda de productes animals assequibles i les creixents preocupacions pel benestar dels animals, es fa imperatiu el desenvolupament de t` ecniques d’explotaci´ o ramadera m´ es eficients que no nom´ es milloren la productivitat sin´ o que tamb´ e garanteixen el compliment dels est` andards ` etics. Aix` o´ es especialment rellevant en el sector de la ramaderia de porcs, ja que la producci´ o porcina ´ es un dels mercats m´ es exigents del sector agr´ ıcola, contribuint a l’economia mundial. Aquesta import` ancia subratlla la necessitat de sistemes de monitoratge especialitzats adaptats als seus comportaments ´ unics i necessitats fisiol` ogiques. El prop` osit d’aquesta tesi ´ es el disseny, desenvolupament i prova dels components d’identificaci´ o i seguiment d’un algorisme de Seguiment Multi-Objecte (MOT) basat en la detecci´ o, com a part d’una col·laboraci´ o entre el grup de recerca HuPBA i Faromatics (AGCO). M´ es espec´ ıficament, aquest projecte es divideix en dues parts: el desenvolupament i creaci´ o d’un conjunt de dades de galeries de porcs, anomenat LehmanPigBoy-33 Dataset, i el disseny i prova experimental dels components de re-identificaci´ o i seguiment. Durant la creaci´ o del conjunt de dades, es van gravar diversos v´ ıdeos d’una granja de porcs als Estats Units amb un robot m` obil, i es van crear diferents plans d’anotaci´ o per millorar l’anotaci´ o de les identitats. El nostre model proposat consta de quatre components: un m` odul de detecci´ o basat en YOLOv8, un m` odul de re-identificaci´ o basat en ResNet-50, un m` odul de seguiment basat en l’algorisme de seguiment SORT, i un m` odul de votaci´ o que implementa un esquema de votaci´ o entre les ID produ¨ ıdes pel m` odul de re-identificaci´ o i les traject` ories del m` odul de seguiment. Aquest treball es centra exclusivament en aquests tres ´ ultims components. El m` odul de re-identificaci´ o va aconseguir una precisi´ o de prova del 85% en un conjunt de dades de 33 identitats, mentre que l’esquema de votaci´ o, basat en la votaci´ o de m` axima confianc¸a, va millorar la precisi´ o de prova d’un v´ ıdeo enregistrat del 90% al 98%.
T´ıtulo: Seguimiento e identificaci´ on de animales en granjas inteligentes Autor: Albert Compte Prades Directores: Sergio Escalera Guerrero Julio Cezar Silveira Jacques-Junior Fecha: 8 de mayo de 2024 Resumen Con la creciente demanda de productos animales asequibles y las crecientes preocupaciones sobre el bienestar animal, se vuelve imperativo el desarrollo de t´ ecnicas de ganader´ ıa m´ as eficientes que no solo mejoren la productividad, sino que tambi´ en garanticen que se cumplan los est´ andares ´ eticos. Esto es especialmente relevante en el sector de la ganader´ ıa de cerdos, ya que la producci´ on porcina se encuentra entre los mercados m´ as exigentes del sector agr´ ıcola, contribuyendo a la econom´ ıa mundial. Esta prominencia subraya la necesidad de sistemas de monitoreo especializados adaptados a sus comportamientos y necesidades fisiol´ ogicas ´ unicas. El prop´ osito de esta tesis es el dise˜ no, desarrollo y prueba de los componentes de identificaci´ on y seguimiento de un algoritmo de Seguimiento Multi-Objeto (MOT) basado en la detecci´ on, como parte de una colaboraci´ on entre el grupo de investigaci´ on HuPBA y Faromatics (AGCO). M´ as espec´ ıficamente, este proyecto se divide en dos partes: el desarrollo y creaci´ on de un conjunto de datos de galer´ ıa de cerdos, llamado LehmanPigBoy- 33 Dataset, y el dise˜ no y prueba experimental de los componentes de re-identificaci´ on y seguimiento. Durante la creaci´ on del conjunto de datos, se grabaron varios v´ ıdeos de una granja de cerdos en los Estados Unidos con un robot m´ ovil, y se crearon diferentes planes de anotaci´ on para mejorar la anotaci´ on de las identidades. Nuestro modelo propuesto consta de cuatro componentes: un m´ odulo de detecci´ on basado en YOLOv8, un m´ odulo de re-identificaci´ on basado en ResNet-50, un m´ odulo de seguimiento basado en el algoritmo de seguimiento SORT, y un m´ odulo de votaci´ on que implementa un esquema de votaci´ on entre las IDs producidas por el m´ odulo de re-identificaci´ on y las trayectorias del m´ odulo de seguimiento. Este trabajo se centra exclusivamente en estos tres ´ ultimos componentes. El m´ odulo de re-identificaci´ on logr´ o una precisi´ on prueba del 85% en un conjunto de datos de 33 identidades, mientras que el esquema de votaci´ on, basado en la votaci´ on de m´ axima confianza, mejor´ o la precisi´ on de prueba de un v´ ıdeo grabado del 90% al 98%.
Title : Animal tracking and identification in smart farms Author: Albert Compte Prades Advisors: Sergio Escalera Guerrero Julio Cezar Silveira Jacques-Junior Date: May 8, 2024 Overview With the rising demand for affordable animal products and the increasing concerns regarding animal welfare, it is becoming imperative the development of more efficient livestock farming techniques that not only enhances productivity but also ensures that ethical standards are met. That is specially relevant on the sector of pig farming, as pork production is among the most demanding markets in the agriculture sector, contributing on the worldwide economy. This prominence underscores the necessity for specialized monitoring systems tailored to their unique behaviors and physiological needs. The purpose of this thesis is the design, development and test of the identification and tracking components of a tracking-by-detection Multi-Object Tracking (MOT) algorithm as part of a collaboration between the HuPBA research group and Faromatics (AGCO). More specifically, this project is split into two folds: the development and creation of a pig gallery dataset, called LehmanPigBoy-33 Dataset, and the design and experimental test of the reidentification and tracking components. During the creation of the dataset, several videos of a pig farm in the United States were recorded using a mobile robot, and different annotation pipelines were created to improve the annotation of the identities. Our proposed model comprises four components: a detector module based on YOLOv8, a re-identification module based on ResNet-50, a tracker module based on the SORT tracker, and a voting module that implements a voting scheme between the IDs produced by the re-identification module and the trajectories of the tracker module. This work focused exclusively on the latter three components. The re-identification module achieved a test accuracy of 85% on a dataset of 33 identities, while the voting scheme, based on maximum confidence voting, improved the test accuracy of a recorded video from 90% to 98%.
I dedicate this master’s thesis to all the individuals involved in the animal re-identification and tracking project: To Dr. Sergio Escalera, professor at UB, head of HuPBA research group and the director of this thesis, for guiding me through the development of the tracker and providing continuous support to the team. To Dr. Julio Cesar Jacques, professor at UB and supervisor of this thesis, for his patient guidance throughout the project and valuable advice. To Xavier Cort´ es, software engineer at Faromatics (AGCO), for overseeing the project and contributing insightful ideas. To Yudong Yan, Ph. D. student at HuPBA research group, for accompanying me throughout the journey and collaborating on the most challenging aspects of the project. To Heiner Lehr, head of Faromatics (AGCO), for granting access to the robot to generate the dataset. To the staff from HuPBA research group, for their assistance with the server and continuous support. To my family, for their unwavering support during challenging times.
3.2010-fold distribution of the second dataset. . . . . . . . . . . . . . . . . . . . . 45 3.2110-fold distribution of the third dataset. . . . . . . . . . . . . . . . . . . . . . . 45 3.22Number of samples per ID. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 4.1 Overall Architecture of the proposed model. The detector module predicts the bounding boxes and masks of the instances detected, the re-identification module performs a first assessment of the instances IDs, and the tracker and voting modules provides ID correction to the re-id module. . . . . . . . . . . . . . . . 48 4.2 Re-identification model Architecture based on ResNet-50. The model contains a residual connection in each residual block to facilitate gradient flow through the network. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 4.3 Maximum confidence voting criteria. The sliding window pass through each SORT track and performs a weighted voting with the confidences of the reidentification predictions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 5.1 Data pre-processing performed by the re-identification module. The bounding boxes from the gallery are converted to grayscale and normalized with a database normalization. Then, they are masked with the mask predicted by the detector module, and the result is resized and padded to fulfill the input dimensions of the re-id module. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 5.2 Hyperparameter Selection. LR stands for learning rate, and BS stands for batch size, and EG stands for exponential gamma. . . . . . . . . . . . . . . . . . . . 56 5.3 Loss and accuracy of the ResNet-50 and ViT-B models. . . . . . . . . . . . . . 60 5.4 Representation of the bright augmentation. . . . . . . . . . . . . . . . . . . . 60 5.5 Representation of the contrast augmentation. . . . . . . . . . . . . . . . . . . 61 5.6 Representation of the noise augmentation. . . . . . . . . . . . . . . . . . . . 62 5.7 Representation of the rotation augmentation. . . . . . . . . . . . . . . . . . . 62 5.8 Representation of the translation augmentation. . . . . . . . . . . . . . . . . . 63 5.9 Representation of the crop augmentation. . . . . . . . . . . . . . . . . . . . . 64 5.10Confusion matrix of the best re-identification model. . . . . . . . . . . . . . . . 67 5.11Hard voting criteria. The sliding window pass through each SORT track and performs a hard voting with the re-identification predictions. . . . . . . . . . . . 70 5.12Maximum confidence voting criteria. The sliding window pass through each SORT track and performs a weighted voting with the confidences of the reidentification predictions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 5.13Comparison of each voting criteria at different sliding window sizes. The green line represents the accuracy after applying any of the voting schemes with a SORT tracker. The red and blue lines represents the results of each voting scheme for an ideal (or perfect) tracker. . . . . . . . . . . . . . . . . . . . . . 74 5.14Frames of the first tracking video. . . . . . . . . . . . . . . . . . . . . . . . . . 74 5.15Frames of the second tracking video. . . . . . . . . . . . . . . . . . . . . . . . 76 5.16Frames of the third tracking video. . . . . . . . . . . . . . . . . . . . . . . . . 76 5.17Representation of the identity tracks after applying a sliding window of size 3. . 78 5.18Key frames of the first tracking video using a sliding window with size 3. . . . . 79 5.19Representation of the identity tracks after applying a sliding window of size 501. 80 5.20Key frames of the first tracking video using a sliding window with size 501. . . . 81
A.1 MoCo architecture for contrastive self-supervised learning. The first block represents the pretext learning method, while the second block represents the downstream task. In the pretext task, the sample is augmented into two different branches (query and key), and these branches create their own feature representation of the sample. Then, the model compares both sample embeddings and tries to minimize their contrastive loss. The key branch stores the samples from previous iterations in order to use them as negative pairs for the contrastive loss comparison. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 A.2 Filtering of the three datasets. . . . . . . . . . . . . . . . . . . . . . . . . . . 99 A.3 Pretext and Downstream metrics after applying a data augmentation on the query branch. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 A.4 Pretext task loss after applying one transformation on each branch. . . . . . . . 102 A.5 Pretext and Downstream metrics after applying all the augmentations in both branches. The probability value determines the probability of applying each transformation individually. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
LIST OF TABLES 2.1 Closed-World set vs Open-world set comparison . . . . . . . . . . . . . . . . 8 2.2 Summary of the available public datasets compared against our dataset. . . . . 10 2.3 Summary of Multi-Object Tracking (MOT) methods for pig farming. . . . . . . . 24 3.1 Summary of the statistics of each recording. . . . . . . . . . . . . . . . . . . . 39 3.2 Statistics of the final dataset. . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 4.1 Comparison of all yolov8 segmentation models . . . . . . . . . . . . . . . . . 48 5.1 Train and Validation accuracies of pretrained ResNet-50 and ViT-B after 10 epochs (Learning rate test). The default batch size is set to 16, while the learning rate decays 1/2 after 10 epochs. . . . . . . . . . . . . . . . . . . . . . . . 57 5.2 Train and Validation accuracies of pretrained ResNet-50 and ViT-B after 10 epochs (Batch size test). The default learning rate is set to 1·10−5, while the learning rate decays 1/2 after 10 epochs. . . . . . . . . . . . . . . . . . . . . 57 5.3 Train and Validation accuracies of pretrained ResNet-50 and ViT-B after 10 epochs (Exponential gamma test). The default learning rate is set to 1·10−5, while the learning rate decays 1/2 after 10 epochs. . . . . . . . . . . . . . . . 57 5.4 Comparison of a balanced and unbalanced dataset with different number of samples per identity. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 5.5 Different spatial distributions for a dataset with 500 samples per ID. . . . . . . . 59 5.6 Backbone comparison on the re-identification task. . . . . . . . . . . . . . . . 60 5.7 Data Augmentation Test: Brightness . . . . . . . . . . . . . . . . . . . . . . . 61 5.8 Data Augmentation Test: Contrast . . . . . . . . . . . . . . . . . . . . . . . . 61 5.9 Data Augmentation Test: Noise . . . . . . . . . . . . . . . . . . . . . . . . . . 62 5.10Data Augmentation Test: Rotation . . . . . . . . . . . . . . . . . . . . . . . . 63 5.11Data Augmentation Test: Translation . . . . . . . . . . . . . . . . . . . . . . . 63 5.12Data Augmentation Test: Cropping. The crop size is the size of the bounding box used to crop the gallery image. . . . . . . . . . . . . . . . . . . . . . . . 64 5.13Data Augmentation Test: Rotation + Translation . . . . . . . . . . . . . . . . . 65 5.14Final Comparison of the re-identification model. . . . . . . . . . . . . . . . . . 65 5.15Final Comparison (F1-score) of the re-identification model (First Dataset). . . . 66 5.16Final Comparison (F1-score) of the re-identification model (Second Dataset). . 66 5.17Final Comparison (F1-score) of the re-identification model (Third Dataset). . . . 66 5.18Statistics of the SORT Tracks for the first tracking video. ID Sw. stands for ID Switches. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 5.19Statistics per identity. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 5.20Tracking Test (F1 score): Hard Voting Criteria (SORT Tracker). W is the window size (in number of samples). . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 5.21Tracking Test (F1 score): Maximum Confidence Voting (SORT Tracker). W is the window size (in number of samples). . . . . . . . . . . . . . . . . . . . . . 72 5.22Comparison of tracking methods. Disp. stands for Displacement, Re-ID stands for re-identification prediction, and Max. Conf. Voting stands for Maximum confidence voting. W is the window size of the voting scheme. . . . . . . . . . . . 73
5.23Description of each pig’s behavior at each fold (First Tracking Video). . . . . . . 75 5.24Description of each pig’s behavior at each fold (Second Tracking Video). . . . . 76 5.25Description of each pig’s behavior at each fold (Third Tracking Video). . . . . . 77 A.1 Self-Supervised Test: Single Augmentation. sstands for scale, while std stands for standard deviation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 A.2 Self-Supervised Test: 1vs1 Augmentation . . . . . . . . . . . . . . . . . . . . 101 A.3 Self-Supervised Test: All Augmentations . . . . . . . . . . . . . . . . . . . . . 104 A.4 Comparison of the training methods applied on the ResNet-50 backbone. . . . 104
CHAPTER 1. INTRODUCTION 1.1. Statement of purpose As the demand for affordable animal products continues to rise and concerns regarding animal welfare intensify, the imperative for efficient production practices becomes ever more desirable. Consequently, there has been a heightened demand for comprehensive monitoring of livestock. Such monitoring serves multiple crucial purposes: it enables farmers to optimize the balance between animal productivity and resource utilization, mitigate negative interactions to alleviate stress and anxiety among the animals, curtail the spread of diseases within herds, and facilitate the provision of personalized medication, thereby diminishing the risk of medical resistance. Amidst the increasing challenges of livestock management, the role of pigs as a vital component of the agricultural sector cannot be overstated. Pigs are among the most extensively farmed animals worldwide, significantly contributing to the economy and fulfilling the growing consumer demand for pork products. This prominence underscores the necessity for specialized monitoring systems tailored to their unique behaviors and physiological needs. Efficient pig farming not only enhances productivity but also ensures that ethical standards are met, reflecting a commitment to animal welfare and sustainable practices. As such, the development of advanced monitoring technologies for pigs not only addresses the practical aspects of animal husbandry but also aligns with broader economic and ethical considerations. Taking this into account, the main focus of this work is on this specific type of livestock farming. Traditional methods of monitoring encompass marking the animals with paint, the introduction of paper tags at the ear or the leg of the animal, or the application of radio frequency identification device (RFID) sensor tags and the installation of RFID antennas on the desired spots of the housing environment [6][7]. These methods, although they could be effective in certain cases, present a large set of inconveniences. First, all these methods are time-consuming tasks since the farmer must mark or tag each pig individually, which prompts human error and could be economically expensive for large-size farms. The identification of these animals could be also complicated as the farmer must approach each pig to read the tag and identify them, or move the pig to a specific area. Besides, owing to the active behavior of the animals, the RFID sensors have the risk of being destroyed, and the animals could lose their tags. Due to these challenges, in recent years, various non-invasive methods have been developed for livestock monitoring. One such approach involves installing 3-dimensional Kinect depth cameras on predefined positions of the farm (e.g., top-view), which detect animals using a generated point cloud [8] [9]. However, the limited range of these cameras makes it difficult to cover the entire pen of a farm, and the installation of Kinect cameras on a large scale can be prohibitively expensive. As a result, the most prevalent method for animal monitoring relies on two-dimensional RGB cameras, often complemented with computer vision techniques like multi-object tracking or animal identification[10]. 1
2 Animal tracking and identification in smart farms As part of a collaboration between the research group at HuPBA and Faromatics (AGCO), this project aims to design a monitoring system for pig farming that combines animal identification techniques with multi-object tracking, applying a special focus on the identification part. Animal identification, also called animal re-identification, is a process in the field of computer vision where the model classifies a set of identities from the same class. It is harder than a classical classification problem as the degree of similarity of the appearance of different identities (inter-class similarity) is usually closer than the same identity at different poses (intra-class similarity). For instance, Figure 1.1 compares two different identities at different poses. The first two images have more features in common than the others. However, they are different identities. On the other side, the first and fifth images have the same identity, but they have fewer features in common than their neighbor images. (a) A (b) G (c) A (d) G (e) A (f) G Figure 1.1: Examples of pig identities. This problem is usually assessed by applying special techniques to enrich the feature representation, like attention mechanisms or some augmentations on the data (it will be further explained on Chapter 2. However, if the contextual data is preserved, it can be corrected with some tracking techniques. In our case, we combined re-identification techniques with tracking-by-detection Multi-Object Tracking (MOT) methods. Multi-Object Tracking (MOT) ([11], [12], [13]) is a process in the field of computer vision that involves detecting and monitoring multiple objects over a sequence of images or videos. The goal of MOT is to maintain continuous identification and association of individual objects across frames, addressing changes in the environment such as illumination or weather conditions, occlusions, clutter, and pose changes. In animal tracking, this problem can be assessed in two different ways, by combining both detection and tracking parts in the same network (one-stage method), or by splitting the detector and tracker into two different blocks (two-stage or tracking-by-detection method). Our work will rely on this second architecture. However, we will only focus on the tracker block, although the detector module will be commented on as part of future work as a real scenario application. Our contributions to this project are as follows: •We developed and tested a data annotation pipeline based on SAM-PT [14] to simplify and accelerate the data annotation process and prevent some human error, employing the Co-Tracker point tracking algorithm, as detailed in Chapter 3. This includes a dedicated framework known as the SAM Annotation Tool to aggregate all the pipeline steps in a unique place.
Introduction 3 •We curated an identification dataset comprising recordings of over 30 pigs captured by a mobile robot across various pens on a pig farm in the United States. This dataset includes galleries of pigs recorded in three separate videos, with durations of 9, 60, and 20 minutes, respectively, featuring varying numbers of pigs. •We designed and implemented a ResNet-50 (re-)identification model, refined among different training setups. This model can be used as a baseline for the proposed dataset in future research. •We designed and implemented a tracker for a tracking-by-detection Multi-Object Tracking (MOT) algorithm which combines the (re-)identification model with the SORT tracker [15] to keep the consistency of the predicted results in a video setup. •Our work involved implementing confidence-based voting criteria to refine the tracking capabilities of the re-identification model. In Chapter 2, we provide a literature review of related works using a set of computer vision problem taxonomies. Following that,Chapter 3will detail the procedures for data collection and annotation, including the data annotation pipelines, the resulting dataset, and the preprocessing transformations applied during training. Subsequently, Chapter 4will delve into our final project model, while Chapter 5will elucidate all the experiments conducted to develop this model. 1.2. Incidences and deviations from initial plan During the development of the master thesis, we encountered several setbacks concerning data collection. Initially, this project was planned to be designed for a multi-modal dataset. However, the module integrated into the mobile robot, which was responsible for providing multimodal data of the pig farm (including RGB, Infra-Red (IR), and depth modalities), experienced a malfunction. Consequently, we were compelled to proceed with the project in a single-modal setting. Additionally, various incidents typical of farm operations, such as the natural pig cycles, camera dirtiness, and occasional malfunctions of the robot, limited the data collection process. These challenges had an indirect impact on the project’s progress.
CHAPTER 2. RELATED WORK In the field of computer vision, there is not so much information related to animal identification and tracking. Usually, most papers related to identification or re-identification are based on people datasets, while works related to pig or animal tracking are not usually based on re-identification techniques. Owing to the lack of papers related to pig tracking and identification, we described our related work based on different person and animal reidentification, making special emphasis on the animal re-identification part. Besides, we also included some information related to pig tracking techniques, and we described some instance segmentation methods for the tracking-by-detection Multi-Object Tracking (MOT) algorithm. The first section (Section 2.1.) of this chapter describes some re-identification techniques and some issues that we may encounter on the re-identification task. The second section (Section 2.2.) describes in more detail what is a Multi-Object Tracking algorithm and demonstrates some examples of MOT techniques in pig farming. Finally, the third section (Section 2.3.) explains some instance segmentation techniques that will be applied for the detector block of the MOT task and the data annotation procedure (this procedure will be explained in much more detail in Chapter 3). 2.1. Re-Identification The re-identification (Re-Id) task is a common process applied in surveillance, monitoring systems, and crowd analysis where a computer vision model identifies and matches individuals across different camera views and images. The aim is to recognize the same individual across different locations, angles, and poses, even when the appearance of the individual may vary due to light conditions, occlusions, stains, camera differences, or other factors. Most of the existing re-identification models are oriented to person or vehicle re-identification. However, we can also find some papers related to animal re-identification ([16], [17], [18], [19], [20], [21], [22], [23] and [24]). Based on different survey papers on person re-identification ([2] and [1]) and some papers on animal re-identification, we designed a re-identification taxonomy (Figure 2.1). There, we defined the main components of a machine learning model, such as the feature extraction block and the loss function, and we described some of their particularities. Additionally, we also explored certain problems we can find in a re-identification dataset. 2.1.1. Re-identification Datasets A dataset serves as the foundation of any machine learning model, playing an indispensable role in tasks such as animal re-identification, where data collection proves challenging and public datasets are notably scarce, especially for specific species. Consequently, many researchers opt to construct their own datasets. However, the limited number of identities and images per identity hinders generalizability across diverse contexts. 5
12 Animal tracking and identification in smart farms focus on a re-identification task, it is crucial to enhance intra-modality discrepancies while simultaneously mitigating inter-modality differences. Examples of dual-stream networks utilized in person re-identification include: Zhihan et al. [61], who employ dual-channel attention mechanisms in infrared-visible person re-identification; Miao et al. [62], incorporating pose estimation as an auxiliary task in visible-IR person re-identification; and Hafner et al. [63], focusing on distilling the modality-specific branch from the depth channel to the RGB channel. –GAN-based Network: Within the dual-stream network, a GAN architecture is employed to discern between both modalities, enforcing alignment at the feature level and disentangling modality-related features from identity classes. Dai et al. [64], Hu et al. [65], and Fu et al. [66] explored this approach in their respective cross-modal person re-identification task. (a) Single-Stream Network (b) Dual-Stream Network (c) GAN-based Network Figure 2.2: Representation of the Shared-Feature-Mapping approaches. Taken from [1] Some visual modalities are RGB, infrared (IR), thermal, and depth cameras. Nonetheless, other modalities can be also combined, like sketches [30], or textual descriptions [32]. 2.1.2.2. Architecture The architecture dictates how the machine learning model distinguishes between various identities. While most re-identification models employ deep learning methods to learn identity features, some studies still explore the application of traditional machine learning methods. Kuncheva et al. [16] conducted a comparative analysis between various traditional machine learning approaches and a subset of deep learning methods. They examined multiple feature extraction techniques, including color-related features (mean and standard deviation of color channels), histogram-of-gradients (HOG), local binary patterns (LBP), au-
Related Work 13 toencoders (AE), and MobileNetV2 features. Furthermore, the authors evaluated a diverse array of 25 classifiers, encompassing linear classifiers (Na¨ ıve Bayes, Linear Discriminant Analysis, Logistic Regression, etc.), non-linear classifiers (Decision Trees, K-NN, SVMs, etc.), ensemble classifiers (AdaBoost, Bagging, Random Forest, etc.), and deep learning methods (CNN and MobileNetV2). Their findings indicated that Linear Discriminant Analysis (LDA) achieved the highest accuracy on 3 out of 5 datasets, particularly in scenarios with limited data and without employing re-ranking methods. But nowadays, most re-identification methods are based on deep learning, most probably due to its high capacity of automatically learning, discover and extract the hierarchical representation that is needed to solve different kinds of problem, as detailed next. Deep Learning methods dominate the landscape of person and animal re-identification tasks, constituting the bulk of research efforts. Within this domain, convolutional neural networks (CNNs) represent the predominant approach. However, there are also emerging transformer-based approaches. •Convolutional Neural Networks (CNNs): Deep neural networks designed specifically for analyzing structured grid data, like images. They typically consist of convolutional, pooling, and fully connected layers. However, the pivotal layer within CNNs is the convolutional layer, where convolutional operations are applied through a set of kernel filters to extract pattern representations such as edges, textures, and shapes from the input data. The extensive research on this kind of network and the imperative need to reduce its computational cost provided us with a wide range of CNN backbone architectures, such as ResNet-50 [67], MobilenNet [68], GoogleNet [69], ConvNeXt [70], or EfficientNet [71]. Some examples of CNN applied to animal re-identification are [19], [20] and [21]. •Graph Neural Networks (GNN): These are deep neural networks specifically crafted to process graph-structured data, comprising nodes (representing entities) and edges (depicting relationships between these entities). GNNs are typically trained using an iterative approach that involves aggregating information from neighboring nodes through a message-passing algorithm. These kinds of networks are extremely rare for re-identification, and they are normally used as an auxiliary block for identity ranking. Shen et al. [72] proposed the integration of a similarity-guided GNN after a samiese CNN to update the relationship of each probe-gallery pair in a person re-identification task. •Transformers [73]: These deep neural networks exclusively rely on self-attention mechanisms. Initially developed for Natural Language Processing (NLP) tasks, they have also been applied to computer vision problems, such as Visual Transformers (ViT) [74] or Swin Transformers [75]. A transformer typically comprises an encoder and/or decoder, housing multi-head self-attention mechanisms and position-wise fully connected layers. The self-attention mechanisms enable the model to assess the relationships between a set of tokens by assigning attention scores to each token pair. These tokens, usually words in NLP or visual patches in computer vision, are paired with positional encodings to denote their position within the sequence. Related to the animal re-identification task, Zheng et al. [18] proposed a locallyaware transformer with a cross-attention mechanism by extracting both global and local features from the image patches.
14 Animal tracking and identification in smart farms •Other Attention Mechanisms: Some other approaches introduced other kinds of attention mechanisms in their architecture without employing explicitly a transformer architecture. Zhihan et al. [61], for instance, apply channel and spatial attention mechanisms on the RGB branch of their visible-IR person re-identification model. In [48] and [17], the authors proposed the implementation of a temporal self-attention mechanism to extract temporal-dependent behavioral data of person and polar bear identities respectively. 2.1.2.3. Features The paramount goal of the feature extractor is to generate sufficiently representative features that encapsulate the essence of individual identities. This task is particularly critical in animal re-identification scenarios, where many features among identities overlap. Consequently, a significant portion of research contributions in person or animal re-identification focuses on developing appropriate feature representations, often utilizing one or multiple types of feature representations. In this context, three distinct types of features can be considered: global features, local features, and auxiliary features. Both global and local features are geared towards capturing spatial information about the identities: •Local features: These features depict isolated regions within the image or the bounding box of the identity, often in the form of patches or descriptors. Most papers usually combine them with global features. For instance, Zheng et al. [18] combined local features derived from transformer patches using an Inner-Patch Self-Attention mechanism (IPSA), while simultaneously integrating global features obtained from inter-patch interactions through a Cross-Patch Self-Attention (CPSA) mechanism. Other methodologies entail segmenting the image into larger patches, considering factors such as entity shape and pose, and subsequently classifying each patch individually, as demonstrated in works by Li et al. [20] and He et al. [22]. Additionally, Nepovinnykh et al. ([23]; [24]) proposed leveraging HessAffNet descriptors for Saimaa ringed seals, enabling extraction of both geometric and aggregated local appearance similarities. •Global features: These features encapsulate information about the entire image or the interrelationships among patches. Most re-identification model approaches work with global features indirectly by operating directly on the entire image of the instance. However, there are alternative methods that seek to establish connections between patches or descriptors by applying some attention or correlation techniques. For instance, Zheng et al. [18] introduced attention mechanisms applied to a set of patches, while Nepovinnykh et al. [24] utilized RANSAC to extract geometric information from descriptors. On the other hand, auxiliary features introduce additional information about the identities by incorporating auxiliary tasks or temporal information: •High-Order Relationships: Within re-identification frameworks, auxiliary data can significantly boost model accuracy. High-order data, including inter-identity relation-
Related Work 15 ships, body poses, or specific body part locations, can markedly enhance identity re-identification. Authors have explored auxiliary classification tasks or even incorporated skeletal representations of the entities’ bodies to leverage this category of data. For instance, He et al. [22] split image features into three different pose branches (sitting, lying, and standing) and fused them using a pose discriminator module for a dog re-identification task. Conversely, Li et al. [20] introduced a regionvisibility predictor to determine which patches were suppressed during the training procedure. Additionally, Miao et al. [62] implemented a pose estimation task to extract local-level features. •Temporal Information: Video-based re-identification models offer a unique advantage over their image-based counterparts by introducing behavioral data absent in static images. This temporal dimension enriches the understanding of identity dynamics and can yield superior performance in re-identification tasks. Some examples of video-based re-identification models were Li et al. [48] and Zuerl et al. [17], which combine dilated temporal pyramid (DTP) convolutions with temporal selfattention (TSA). These features are represented in Figure 2.3. (a) Local feature (b) Global feature (c) Auxiliary feature (d) Video feature Figure 2.3: Representation of the possible feature representations. Taken from [2] 2.1.3. Loss Function The loss function of a machine learning model is a mathematical measure to quantify the degree of disparity between the predicted outputs and the actual ground truth targets. Throughout the training process, the optimization algorithm endeavors to minimize this function by iteratively adjusting the model’s parameters to align the predicted outcomes to the ground truth. Deep-learning methods usually update the parameters of their network through gradient descent: θt+1=θt−α1 N N ∑ n=1 ∂L(y(n),f(x(n);θ) ∂θ (2.1) As it varies according to the training task, we can define different re-identification problems by modifying the classification layer and the loss function. These re-identification problems can be classified into two different learning methods: metric learning, which measures the distance between the embeddings generated by the feature extractor, and representation
16 Animal tracking and identification in smart farms learning, which predicts a set of classes from the appearance features by adding a classification layer. These techniques are represented in Figure 2.4. A ranking process can enhance some of these learning methods. Figure 2.4: Representation of the different loss functions. Taken from [1] 2.1.3.1. Metric Learning In the realm of metric learning, the primary objective is to determine the optimal metric that effectively discriminates between instances belonging to different identities while simultaneously grouping together instances from the same identity within a vectorial space. Unlike traditional classification approaches, metric learning operates without the need for a classification layer, typically emphasizing the clustering of every identity. Classification of individual instances is achieved by assessing their proximity to known instances, often through the application of algorithms like K-Nearest Neighbors (K-NN), as in [76]. Consequently, the model necessitates both a set of gallery images and query images to ascertain whether a query corresponds to any of the known identities. In scenarios characterized by an open-world setting, researchers have the flexibility to establish thresholds for each identity cluster to classify unknown identities. Among the most commonly employed distance metrics are: •Minkowski Distances: Set of metric distances based on the difference between two points at each axis. Depending on the value of p, we can define different metrics. D(X,Y) = ( n ∑ i=1 |xi−yi|p)1 p(2.2) The most common ones are: – Euclidean Distance (L2 Distance, p=2): Linear distance between two points
Related Work 17 in a n-dimensional space. It is the shortest line that connects both points. De(X,Y) = sn ∑ i=1 (xi−yi)2(2.3) – Manhattan Distance (L1 Distance, p=1): Sum of the axial distance between two points in each dimension. It can be also called rectilinear distance. Dm(X,Y) = n ∑ i=1 |xi−yi|(2.4) – Chebyshev Distance (p=∞): Value of the largest axial distance between two points for all the dimensions. Dc(X,Y) = max(|x1−y1|,...,|xn−yn|) = lim p→∞( n ∑ i=1 |xi−yi|p)1 p(2.5) •Cosine Similarity: Metric distance that measures the difference between two vector directions rather than the distance module between two coordinates. It is computed as the cosine of the angle between both vectors. cos(θ) = X·Y |X||Y|=∑n i=1xiyi q∑n i=1x2 iq∑n i=1x2 i (2.6) These metrics are typically employed in conjunction with a metric learning loss: •Contrastive Loss: Computes the distance loss between two samples. If both samples belong to the same identity, δi j =1; conversely, if they belong to different identities, δi j =0.ρrepresents a threshold value to indicate a fixed margin between two different identities. As it only considers the distance between a pair of samples, it is hard to ensure that the distance between two features from the same identity is smaller than the distance between two features from different identities. LCon = (1−δi j){max(0,ρ−di j)}2+δi jd2 i j (2.7) •Triplet Loss: Computes the distance loss between an anchor sample a, a positive pair of that sample pthat belongs to the same identity, and a negative sample pair n that belongs to a different identity. In this approach, ρis a distance threshold, dap is the distance between the anchor-positive pair, and dan is the distance between the anchor-negative pair. The triplet loss is smaller when the anchor sample ais closer to the positive sample p, and farther to the negative sample n. It tends to overfit with the given samples, not extracting enough discriminative features from unseen samples [77]. LTri =max(0,ρ+dap −dan)(2.8) •Hard-Sample-Based Triplet Loss: To improve the generalization of the triplet loss, it computes the triplet loss between the closest negative sample and farthest positive sample of a batch, instead of doing it for all the samples. As both methods compute loss as the relative loss between two different distances, they cannot prevent the increment of dap or the decrement of dan individually, which could affect negatively the training process. LH−Tri =max(0,ρ+maxdap −mindan)(2.9)
18 Animal tracking and identification in smart farms •Quadruplet Loss: The quadruplet loss adds another negative sample to solve the relative loss problem. The second term prevents a possible shared bias between dap and dan1, by using the absolute distance between positive and negative samples. LQ=max(0,ρ1+dap −dan1)+max(0,ρ2+dap −dn1n2)(2.10) •InfoNCE Loss: InfoNCE is a kind of contrastive loss function that computes the loss of a positive pair against a set of K negative samples. It normally uses the samples from a batch or a memory bank. τis called the temperature parameter and controls the similarity space of the samples. LIn f oNCE =−log exp(sim(a,p)/τ) ∑K i=0exp(sim(a,ki)/τ)(2.11) There is another version of this loss called Online Instance Matching (OIM) loss, which uses the following equation: LOIM =−1 n n ∑ i=0 log exp(sim(vi,fi)/τ) ∑c k=0exp(sim(vk,fi)/τ)(2.12) There, vkrepresents a sample from the memory bank, while firepresents the anchor sample. 2.1.3.2. Representation Learning In representation learning implementation, a fully connected (FC) layer is typically added after the feature extractor. This FC layer serves to classify the extracted features into different categories, thereby obviating the need for using metric distances. Representation learning can be applied through two primary methods: •Verification Problem: The verification problem can be applied with both metric learning and representation learning approaches. The metric learning approach uses the contrastive loss (Equation 2.7) or other equivalent methods to improve the relative pairwise distance and determine its similarity. The representation learning approach, on the other side, uses the fully connected (FC) layer to classify a pair of samples as positive or negative pairs in a Siamese Neural Network architecture [78]. The loss function is called Verification Loss, and normally employs the Binary Cross Entropy Loss function: Lveri(i,j) = −δi j log(p(δi j|fi j))−(1−δi j)log(1−p(δi j|fi j)) (2.13) Where fi j = ( fi−fj)2represents the differential feature of the embedding features of the samples xiand xj,p(δi j|fi j)represents the probability of the input pair to be recognized as δi j, and δi j the similar or dissimilar class.
Related Work 19 •Classification Problem: The fully connected (FC) layer serves to classify the sample into one of the existing identities. As it considers the whole set of identities, it is more stable than other metric learning approaches. However, it is computationally more expensive. The loss function employed is called Identity Loss or Classification Loss and consists of the application of a softmax function and the cross-entropy loss. The crossentropy loss can be represented as: LCE =− N ∑ i=1 qilog(p(fi)) (2.14) Where qiis the one-hot vector of the i-th sample, and p(fi)is the prediction probability of fi, computed from the softmax function of one of the identities. As all the classes are already defined, this approach cannot be generalized to unknown identities in an open-set problem. 2.1.3.3. Ranking Optimization In methods relying on query-to-gallery similarity, such as metric learning approaches or the verification problem, we can integrate a ranking optimization step to refine the classification of identities within the samples. Two common methods for this optimization are re-ranking and rank fusion: •Re-Ranking: Re-ranking leverages gallery-to-gallery similarity to refine the initial ranking list. Positive samples ranked at the top pull other positive samples upwards in the ranking, while negative samples push other samples downwards. Some methods adapt to the query or allow user interaction to adjust the gallery list. Ye et al. [79] proposed a top-ranked similarity-pulling and bottom-ranked dissimilaritypushing rank optimization method, while Liu et al. [80] proposed a human feedback optimization method. •Rank Fusion: Rank fusion involves combining multiple ranking lists generated by different methods to produce an enhanced ranked list. Graph methods, ensemble learning, or other fusion algorithms may be utilized to improve the overall ranking. Zheng et al. [81] proposed a query adaptive late fusion method, while Barman et al. [82] proposed a graph theoretic algorithm for consensus-based decisions. Finally, Paisitkriangkrai et al. [83] proposed an ensemble learning method. 2.2. Multi-Object Tracking (MOT) Multi-Object Tracking (MOT) is a task in computer vision where a model must localize several objects in the scene, maintain their identities, and yield their trajectories from an input video. This challenging task received so much attention due to its academic and commercial applications, being applicable in surveillance, robotics, autonomous vehicles, or, in
20 Animal tracking and identification in smart farms our particular case, livestock management. These systems should deal with environmental changes such as illumination or weather conditions, occlusions, cluttering, and pose changes. There is no global consensus about how to classify MOT techniques ([11], [12], [13]). Most of these approaches ([11], [13]) classify MOT techniques by their processing mode, having an online processing if the MOT technique runs frame-per-frame or an offline or batch processing if the MOT technique has to store a set of frames before extracting the results. Luo et al. [11], on the other side, proposes another classification method based on the output type, having a deterministic tracking if the tracking model returns an output invariant with the model’s initialization, or a stochastic tracking if the output changes in different initialization. However, the most widely extended classification method in animal tracking is based on the presence of a detector block ([84], [10], [85], [86], [87]), classifying MOT models in one-stage and two-stage methods. 2.2.1. One-Stage Method One-stage methods do not require a distinct detection block to track the objects. That is because the model merges the detection and tracking steps on a single network, or it does not require any detection process to track the trajectories of the identities. In this category, we can discern two different one-stage methods: •Detection-free Tracking: Detection-free trackers ([88], [89], [90], [91]) require a manual or semi-automatic initialization in the first frame to track the identities from the video. Then, it propagates the localization of the tracks in the subsequent frames. It is not commonly applied in animal tracking due to the limitation of the initialization process. However, there is also an example of detection-free tracking applying depth cameras [92]. Other tasks that could be considered detection-free tracking methods, despite not being directly related to the MOT task, are point trackers and Video-Object Segmentation (VOS) models, as they normally require a manual initialization step. Some examples of point trackers are PIPS [93], CoTracker [94], and Point Odyssey [95], while some examples of VOS models are DeAOT [96] and XMem [93]. Some VOS models were also based on SAM [4], such as Segment and Track Anything (SAM- Track) [97], Track Anything (TAM) [98] and Segment Anything meets Point Tracking (SAM-PT) [14]. •Joint Tracking and Detection: This method combines the detection and tracking components in a single network, improving the computation time in most cases. The model usually predicts the detections of the objects and their embeddings. Some examples applied to animals are Joint Detection and Embedding (JDE) [84] [10], FairMOT [84] [10], and STARFORMER [99], being FairMOT and STARFORMER the most prominent ones. FairMOT [84] is an encoder-decoder anchor-free network that fuses multi-layer features of a ResNet-50 backbone by a version of Deep Layer Aggregation (DLA [100]).
Related Work 21 Its base model predicts the center heatmap, box size, center offset, and reidentifi- cation features of the identities detected on the videos. The authors usually combine it with a three-step association algorithm, highly similar to the DeepSORT algorithm [15], to enhance the re-identification capabilities of the model. On the other side, STARFORMER [99] extends Detection Transformers (DETR) [101] with a ResNet-101 backbone and four different heads to extract the Segmentation, Tracking, Actions, and Re-identification IDs (STAR) of each individual. In this approach, each head has its own design and metric loss, having a multi-head attention layer and a feature pyramid network (FPN) on the detection head, a feed-forward network (FFN) on the detection and action heads, and a spatiotemporal contrastive training approach on the tracking head. 2.2.2. Two-Stage Method Two-stage methods, also called tracking-by-detection or Detection-Based Tracking (DBT), is a tracking method that combines a detector block with an association or tracker block. The effectiveness of this approach hinges significantly on the choice of detector, typically limiting its ability to track only those objects for which the detector model was specifically trained. However, it is the most popular method for animal tracking ([86], [85], [10], [87], [102] ). The detector block is normally based on an object detector model, but other methods like instance segmentation can be applied as the detector block. They normally return the bounding boxes or the masks of the instances detected. The most popular detectors for Multi-Object Tracking (MOT) vary between one-stage detectors, such as YOLO [3], or twostage detectors, such as Mask R-CNN [103]. Our system uses an instance segmentation model based on YOLO, described in more detail in Section 2.3. The tracker or association block is the main block for most two-stage methods, as it describes how the model will be able to track the instances detected by the detector at each frame. According to Ciaparrone et al. [13], it could contain one or some of these stages: •Feature Extraction/Motion prediction Stage: One or several feature extraction algorithms extract appearance, motion, or interaction features from the detections or tracklets the detector produces. It could include a motion predictor that predicts the next position of each tracklet target, like Kalman filters [104]. Some common feature extraction methods in MOT are CNN [105][106], Samiese CNN [107][108], or LSTM [109][110]. •Affinity Stage: Uses the features and motion predictions produced by the feature extraction stage to compute a similarity or distance score between a pair of detections. Some deep learning methods in affinity computation use LSTMs [111][112], Samiese LSTMs [113][114], Bidirectional LSTMs [115], CNNs [116], and Samiese CNNs [117].
CHAPTER 3. DATASET As discussed in Section 2.1.1.3., One of the most important concerns in animal tracking is the lack of available public datasets for pig re-identification. The expenses associated with installing cameras, the inaccessible nature of certain farms, and the profitability of these datasets pose significant challenges for computer vision researchers in terms of data collection and public dissemination. That restricts the capability of researchers to compare their re-identification results, as each research group uses its own dataset. For this reason, as part of this project, we have developed a data collection study on a farm in the United States, which includes the installation of a mobile robot, multiple phases of data collection, the development of an annotation process, and the annotation of the data. LehmanPigBoy-33 Dataset includes a gallery set of more than 90,000 images from 33 distinct identities, containing not only the separate images from each identity, but their respective masks, bounding box information, and contextual information of the recordings. All these data were collected thanks to the development and optimization of several annotation pipelines. Next, we describe the data collection process in Section 3.1., then in Section 3.2. we explain the data annotation pipeline employed to annotate the data, and finally in Section 3.3. we present the LehmanPigBoy-33 Dataset. 3.1. Data Collection 3.1.1. Farm Information The test farm that we collaborate with is Lehman Pork LLC in Dana, IA, US. It is a swine wean-to-finish facility built in 2007 for JBS, and then it was further improved by AP (Automated Production System) by adding more automation systems. The dimensions of the barn are 22 by 82 meters and 2.5 meters high, and it consists of 12 pens which have around 25 pigs inside for each as shown in Figure 3.1. Additionally, there are windows on both sides of the building to ensure that there is enough natural light in the area. 3.1.2. Camera Information There are four cameras in total that we used in the project, which are ELP 2MP USB Camera Module, Thermal & Optical Bi-Spectrum Network Turret Camera, and Astra+. ELP USB Camera Module with Sony IMX323 is the capable of taking RGB images up to 1920x1080 pixel at 30 fps and can keep the purity and high color saturation of images thanks to high sensitivity 1/2.9” Sony IMX323 Image Sensor. Thermal&Optical Bi- Spectrum Network Turret Camera produced by Hikvision has both RGB channel and thermal channel, and it can provide us with the RGB and thermal videos at the same time. Astra+ is the successor to Orbbec’s Astra series, which is based on structured light technology with Orbbec’s ASIC for high quality depth processing. It can provide us with the 29
30 Animal tracking and identification in smart farms Figure 3.1: Barn Layout RGB videos up to 1920x1080 pixel at 30fps and high quality depth data output from 0.6-8 meters. Here are the image samples captured by every camera in the following Figure 3.2. (a) ELP USB Camera (b) Hikvision Turret Camera (c) Orbbec Astra+ Camera Figure 3.2: Image Samples ELP 2MP USB Camera is the cameras that we used initially for the project as it is the camera integrated in the robot that we implemented for data collection. After recording several videos and more analysis of the project, we decided to add thermal camera and depth camera into the project to not only increase the precision of the identification task, but also the pig welfare. Thermal cameras are useful for monitoring body temperature and changes related to hypo- or hyperthermia, inflammation[137]. And depth camera can be useful for weight estimation, which was considered as a time-consuming and relatively stressful work[138]. 3.1.3. Robot Setup Data acquisition was conducted by the robot SCOUT developed by Faromatics. Scout is a ceiling-suspended robot which patrols the farm every day along its rail system as shown in the following Figure 3.3. The robot has four sets of cameras located on its left, right, front, and bottom with which it can cover the whole barn and take videos while moving.
Dataset 31 Figure 3.3: Robot Scout The robot moves along its trajectory as shown in the Figure3.4. The thin solid lines represent farm walls and fences which divide the entire barn into 12 pens. The thick solid line represents the rail circuit of the robot, which is in the middle of the barn and allows the robot go over all the pens. The white circle represents the robot, and the dotted line is the coverage area of the cameras. The robot takes around 18 minutes to finish one round,and then it stays in the charger for 1 hour. Figure 3.4: Rail circuit of the robot This configuration significantly reduces the need for additional farm cameras, thereby cutting down on installation costs. However, it also introduces limitations and challenges, particularly in data annotation. As there is no single camera covering an entire pen, pigs may leave the coverage of one camera and enter the coverage of another camera. Therefore, a manual annotation process is required to determine the identity while creating the dataset. When we label the IDs of the pigs, we need to check the videos from different cameras to ensure identity consistency.
32 Animal tracking and identification in smart farms 3.1.4. Collected data In data collection, we need collect data for both instance segmentation task and Re-ID task. Since these two tasks have different requirements for data, we must conduct data collection separately. For instance segmentation task, we hope that the data collected is more diverse. It needs to cover the all the stages of pig growth and has as many individuals as possible. Based on these requirements, we formulated a data collection plan. Collect one round video per day, and extract 1 frame every 2 seconds from the video for annotation. For Re-ID task, initially what we wanted to accomplish was the individual identification of pigs while the robot is moving above the pens. But after more research and investigation, we realized the following issues: Firstly, We cannot ensure that we collect information on all pigs on the farm as the coverage of the robot is limited and pigs walk freely in their pen everyday; Secondly, we have no way to manually identify the pigs without any additional paint or tags. So we decided to keep the robot over a certain area and make sure it could basically cover the entire area, and then record the video. Every time we record an hour of video, and then extract the clips where the pigs are more active for annotation. It is worth noting that we only recorded videos of adult pigs at this time, because piglets have relatively few identifiable characteristics. It should be mentioned that due to some objective reasons, sometimes we are unable to collect valuable data or the collected data is invalid. This mainly depends on the cleanliness of the camera, the operating status of the robot and the farm production cycle, etc. In the end, we collected approximately 65 18-minute videos for instance segmentation task and 50 one-hour videos for Re-ID task. 3.2. Data Annotation For training our re-identification model, it is mandatory to have a gallery set of pig images with their respective IDs properly labeled. These gallery images must be extracted from raw video images where several identities appear in the scene and each identity only covers a small fraction of the image. Therefore, the desired dataset requires the bounding boxes of each identity to crop them from the video and store them in the image gallery. Besides, since each cropped image could contain information from other identities due to identity occlusion or cluttering, we included a masking pre-processing procedure during the model’s training to remove any presence of external identities. Owing to that, we require an annotation pipeline that extracts the segmentation masks, bounding boxes, and identities of our dataset. During the annotation process, we improved the annotation protocol by modifying several components of our annotation pipeline. In this section, we describe the different annotation pipelines employed to annotate the data of our created dataset.
Dataset 33 3.2.1. First Pipeline Figure 3.5: First Annotation Pipeline. The YOLO-based Annotation tool changes the video format to a set of frames and proposes a set of bounding boxes per instance. The user uses this tool to correct the provided bounding boxes. Then, in the SAM mask extractor + Tracker block, SAM[4] uses these bounding boxes to generate the masks, and the SORT [5] tracker proposes a set of raw IDs by tracking the bounding boxes of the video. Finally, a manual correction is performed to correct all the errors from the previous steps. The initial pipeline, as illustrated in Figure 3.5, utilizes the YOLO v8 detector model to delineate the bounding boxes of the pig identities, while employing the Segment Anything Model to derive masks corresponding to these bounding boxes. Since the YOLO v8 model wasn’t specifically tailored for our target classes, it was integrated with a manual correction framework known as the YOLO Annotation Tool. The first stage of this pipeline uses the YOLO-based Annotation Tool (Section 3.2.1.1.) to extract the frames from the raw video and produce the bounding boxes of the instances. The second stage (Section 3.2.1.2.) employs SAM to generate the masks from the bounding boxes and applies a SORT tracker to achieve a primary estimation of the instance IDs. Finally, the third stage (Section 3.2.1.3.) uses the Computer Vision Annotation Tool (CVAT) and other human correction techniques to correct both masks and identities. In this final stage, other pre-processing steps are performed to construct the gallery dataset. 3.2.1.1. YOLO-based Annotation Tool The YOLO-based annotation tool presents an annotation framework designed specifically for annotating bounding boxes and classes through integration with the YOLO v8 detector model. An enhanced version of this framework incorporates additional functionalities such as a video frame extractor, allowing users to specify parameters including the initial frame, final frame, and desired frame rate. Furthermore, an Intersection over Union (IoU) filter has been integrated to effectively eliminate false detections occurring between frames, enhancing the accuracy and reliability of the annotation process.
34 Animal tracking and identification in smart farms In this stage, a raw video is inputted, and the frame extractor step outputs a collection of frames based on the user-specified frame rate. These frames are then processed by the YOLO v8 detector model to generate a set of bounding boxes, which are subsequently manually refined by the user during the human correction step. The entire process yields a list of frames along with bounding boxes generated by the framework. Figure 3.6 shows all the steps of this stage. Figure 3.6: YOLO-based Annotation Tool. The frame extractor generates the frames of the dataset, and the YOLO v8 detector model produces the first approach of the bounding boxes. These bounding boxes are then corrected manually. 3.2.1.2. SAM Mask Extractor + Tracking The ”SAM Extractor + Tracking” stage is in charge of producing a first estimation of the masks and IDs of the instances. In this stage, the bounding boxes are processed by the SAM mask extractor [4] to provide their corresponding masks, then the SORT tracker [5] also uses the bounding boxes and the frames to estimate the tracks of the instances and provides the IDs from each track, and finally, a LabelMe format generator organizes the results from SAM and SORT in the LabelMe format to be compatible with the modules from the subsequent stages. The Segment Anything Model (SAM) [4] is responsible for extracting masks based on the bounding boxes generated by the YOLO-based annotation tool. While SAM yields satisfactory results, it occasionally introduces segmentation errors such as the omission of certain body parts or the erroneous inclusion of unrelated identities. To address these discrepancies, we employed an online framework tool known as the Computer Vision Annotation Tool (CVAT) 1. This framework provides us with the means to fine-tune instance segmentation by refining intricate details, eliminating irrelevant areas from the mask, and restoring 1Computer Vision Annotation Tool (CVAT) [139]: online framework for data annotation. It contains a wide range of tools for image segmentation, pose estimation, and label annotation for computer vision tasks. Although it is a very useful tool, we decided to create our framework to automatize the process in our desired format. Nonetheless, we used this tool to correct segmentation errors.
Dataset 35 missing body parts. The LabelMe format generator block step from this stage formats the data produced by SAM and SORT to a compatible format for CVAT to reduce the data transference effort between frameworks (from our framework to CVAT or vice versa). For identity annotation, a semi-automatic approach was adopted, leveraging the SORT algorithm[5] to track the bounding boxes of each pig. However, due to the reliance on intersection-over-union (IoU) metrics via Kalman Filters, this tracking model may encounter challenges such as identity switches, misclassifications, and ID losses, particularly in scenarios involving occlusions, departure from camera visibility, or non-perpendicular camera positioning relative to the pig’s movement axis. To mitigate these issues, an ID mapper step was incorporated to rectify any missing tracks (described in more detail in Section 3.2.1.3.). Figure 3.7 shows the steps performed in this stage. Figure 3.7: SAM Mask Extractor + Tracking. The SAM mask extractor provides a set of masks per bounding box, and the SORT tracker returns a tracking ID per instance. 3.2.1.3. Computer Vision Annotation Tool (CVAT) and other pre-processing steps As all the previous stages could contain certain errors in their predictions, the final stages of this pipeline provide additional human correction steps. These steps can use: •CVAT correction: we used the Computer Vision Annotation Tool (CVAT) to fix some segmentation errors such as the omission of some body parts or the inclusion of erroneous identities. IDs can be also corrected through CVAT, but it is not practical. The LabelMe format generator from the previous stage was developed to have a data format compatible with this framework. This format contains all the information related to the frame images, masks, bounding boxes, and identity labels. •Track visualizer: processes the bounding box and mask information of the instances and shows the track path produced by each identity. It can be used to check if each identity is tracked properly. •ID mapper: maps the ID predicted to new IDs taking into consideration the window of frames we want to map. It is used to correct ID switches, re-entering identities, or lost tracks.
36 Animal tracking and identification in smart farms To determine if an identity is properly tracked, we normally use the track visualizer and the recordings from multiple camera views to ensure that the identity tracked is the same for the entire video. The identities that appear and disappear multiple times within the camera’s field of view are manually re-identified by observing their skin patterns or tracking their trajectory across other cameras mounted on the robot. Another pre-processing step is the gallery generator, which produces a folder with the cropped images and masks of each identity. Figure 3.8: Pre-Processing steps. In this stage, we manually correct the masks and IDs generated by the previous stages. The final result is a gallery of images and masks per identity. 3.2.2. Second Pipeline One of our objectives in designing the pipelines is the capability of automatizing the annotation process. However, the first pipeline had some issues that prevented this protocol from being automatizable. Firstly, owing to the lack of data, the YOLO v8 detector model was not capable of providing proper bounding boxes. Secondly, as the SAM mask extractor only depends on the bounding boxes, we cannot correct the masks directly from our framework. The second pipeline addresses these problems by substituting the YOLOv8 detector model and the SAM mask extractor based on bounding boxes on a SAM mask extractor based on markers. To automatize this process we included a point tracker to propagate the markers of our annotations. The second pipeline (Figure 3.9) adopts the methodology outlined in the SAM meets Point Tracking model [14], with a substitution of the Co-Tracker algorithm in place of PIPS. This adaptation aims to streamline the annotation process while affording greater flexibility in mask annotation. Recognizing the YOLOv8 model’s insufficient training for full automation, an alternative algorithm was chosen to achieve this goal. In this configuration, the SAM Annotation Tool functions as a SAM marker editor for data annotation, leveraging most of the components found in the YOLO annotation tool. This innovative approach not only simplifies the annotation procedure but also empowers users with significant control over the regions segmented by SAM. Apart from that, the IDs can
Dataset 37 Figure 3.9: Second Annotation Pipeline. Most of the annotation was performed on the SAM-based Annotation Tool. It includes the masks, bounding boxes, and IDs. be defined directly by the SAM Annotation Tool and propagated through the automatization process, preventing most of the possible tracking errors produced by SORT. The automation process utilized the Co-Tracker point tracker to track all SAM point prompts. Given the gradual degradation in track quality over time, we adopted a strategy of annotating a frame every 20-40 frames and configured the annotation process to generate the remaining frames. While alternative propagation techniques were explored, such as displacing markers within the mask area and employing SAM for computing subsequent masks, these methods proved impractical for identities with significant displacements. The reason why we implemented the Co-Tracker point tracker as our preferred automation method. Similar to the previous method, additional pre-processing steps are necessary to rectify segmentation errors, format IDs, and construct the gallery. Additionally, a morphological opening operation is conducted to eliminate spurious pixels generated by the Segment Anything model. 3.2.2.1. SAM-based Annotation Tool The SAM-based Annotation Tool is an evolved framework derived from the YOLO-based Annotation Tool, tailored specifically for annotating masks and IDs using SAM directly. While some elements of the previous framework, such as the video frame extractor, were retained, others were introduced to fulfill our annotation requirements. Within this framework, each mask instance must be established before its markers are added. SAM then generates the corresponding masks from these markers, enabling users to interactively modify masks by adding or removing markers. Recognizing the computational intensity of SAM’s image encoder, we incorporated a ”View Mode” option in the application, allowing users to bypass the image encoding process when marker adjustments are unnecessary.
44 Animal tracking and identification in smart farms such as their steins, or the pregnancy of certain pigs. Figure 3.16,Figure 3.17 and Figure 3.18 show an image per each identity of the final dataset. Given our project’s objective of designing a re-identification model capable of capturing both global and local features of identities, we conducted a 10-fold study by temporally splitting the dataset into 10 folds per identity. In this setup, one fold serves as the test set, while the remaining folds are allocated to the training and validation sets. The training set comprises 85% of the data from the remaining folds, while the validation set contains 15% of that data. Figure 3.19,Figure 3.20 and Figure 3.21 illustrates the temporal distribution of each fold per tracking dataset respectively. Figure 3.16: First dataset IDs. Figure 3.17: Second dataset IDs. Figure 3.18: Third dataset IDs.
Dataset 45 Figure 3.19: 10-fold distribution of the first dataset. Figure 3.20: 10-fold distribution of the second dataset. Figure 3.21: 10-fold distribution of the third dataset.
46 Animal tracking and identification in smart farms Considering the potential redundancy in gallery images and the unbalanced nature of the dataset, we conducted various tests with the objective of evaluating how the size and distribution of the dataset affect the accuracy of the model. These included experiments with different sets of frames per identity and balancing the dataset with the data loader by defining a probability of appearance per each sample. Additionally, we explored modifications to sample distribution based on the spatial displacement of identities, although no significant improvements were observed. Further details on these Ablation Experiments are provided in (Section 5.2.). Figure 3.22 illustrates the number of frames per identity and some of the reduced approaches tested. (a) 500 samples/ID (b) 4000 samples/ID (c) The entire dataset Figure 3.22: Number of samples per ID.
CHAPTER 4. THE PROPOSED MODEL In this chapter, we present a new framework for the identification and tracking of pigs based on several tracking-by-detection MOT models reviewed in the related work ([85], [10], [86], [122]). The chapter is divided into different parts that describe in detail each of the modules that make up our model. 4.1. Overall Architecture The proposed model comprises a tracking-by-detection four-stage multi-object tracking (MOT) algorithm, consisting of the following components: •Detector Module: This module utilizes a YOLOv8 segmentation model fine-tuned specifically for segmenting pigs within the smart farm environment. •Re-id Module: The re-identification module utilizes a ResNet-50 backbone classifier to identify the instances provided by the detector module in a closed-world setting. It is the principal component of our architecture and the only module that could work solely to identify and track identities. •Tracker Module: The tracker module employs a SORT tracker to extract initial track predictions of the bounding boxes provided by the detector module. This module cannot identify the identities, nor track re-entering instances. •Voting Module: The voting module leverages the results from the re-id and tracker modules by applying a voting criterion in a temporal filter. It aids in predicting track identities and rectifying possible identity switches. The voting criterion employed was the maximum voting criterion. Throughout this thesis, our primary focus lies on the re-identification module, assuming the optimal functionality of the detector module. The trainable components of the model (The detector and re-identification modules) were trained in a semi-supervised way, applying the annotations generated in Chapter 3.Figure 4.1 exhibits the overall architecture of our model. 4.2. Detector Module The detector module of the proposed model requires the implementation of a detector module that extracts the masks and bounding boxes of the instances from the video. Most specifically, we will need the implementation of an instance segmentation model that produces the masks of the instances required for the preprocessing step of the reidentification model to isolate the pigs from the background and mitigate re-id problems associated with the background (cluttering, extraction of non-related features, etc.). It also should provide the bounding boxes for the SORT tracker. 47
48 Animal tracking and identification in smart farms Figure 4.1: Overall Architecture of the proposed model. The detector module predicts the bounding boxes and masks of the instances detected, the re-identification module performs a first assessment of the instances IDs, and the tracker and voting modules provides ID correction to the re-id module. There are several instance segmentation models capable of extracting the masks of the instances like Mask-RCNN [103]. However, our instance segmentation model should be efficient enough for real-time applications, the reason why we decided to use YOLOv8 as the baseline model for instance segmentation. YOLOv8 (described in Section 2.3.)[3] is a cutting-edge one-stage detector model that gained popularity during the past years due to its efficiency and precision in detecting objects. During the latest versions of this model, the authors added newer functionalities to make the model compatible with a wide range of tasks such as classification, detection, segmentation, tracking, and pose estimation. Yolov8 has 5 segmentation models for us to choose from, namely yolov8n-seg, yolov8s- seg, yolov8m-seg, yolov8l-seg, yolov8x-seg, and they are all pre-trained on COCO’s segmentation dataset. We retrained and validated them respectively on 662 sample images, and obtained the following training results and running time as shown in Table 4.1. The three numbers in the Running Time column correspond to pre-process, inference, and post-process. Additionally, the tests are run on the NVIDIA Jetson Orin NX without TensorRT. Models mAP50-95 Running Time(ms) yolov8n-seg 0.8699 7.3+30.6+7.8 yolov8s-seg 0.88376 7.3+60.1+7.7 yolov8m-seg 0.89205 7.3+119.7+7.7 yolov8l-seg 0.89248 7.2+176.1+7.7 yolov8x-seg 0.8987 7.3+195.6+7.9 Table 4.1: Comparison of all yolov8 segmentation models From the test we found that only yolov8n-seg and yolov8s-seg can achieve real-time detection as the FPS of the camera is 9. Considering the accuracy of the yolov8s-seg is higher, we chose it as the model for segmentation part. Yolov8s-seg model has 261 layers, 11.7M parameters and 42.7 GFLOPs. During the training, we set imagesize=640, batch=8, epochs=500, and the others we use the default value.
The Proposed Model 49 4.3. Re-ID Module The re-identification module predicts the identities of the instances extracted by the detector module. The data used to perform the predictions consists of a cropped image of the instance taken from the bounding boxes and masked with the segments produced by the YOLOv8 segmentation model. Some preprocessing steps, detailed in Section 5.2.1., are required to adapt the produced instances to the input format of the re-identification model. For instance, our model processes images in grayscale, so the images need to be converted to grayscale. To prevent any deviation or clutter from the background, the images are masked. Besides, the images are normalized to eliminate any color deviation in the predictions. The Re-ID module is based on a Convolutional Neural Network (CNN) utilizing the ResNet- 50 architecture, which categorizes cropped identities into predefined classes within the classifier. The ResNet-50 backbone incorporates residual connections among its layers within a series of residual blocks. This architectural choice mitigates the vanishing gradient problem by facilitating gradient flow through the network via the residual connections, thus aiding in efficient training. The model architecture was tailored to process grayscale images of size 256x256 and classify them into 33 distinct identities. These identities are the ones present in the LehmanPigBoy-33 dataset, as detailed in Section 3.Figure 4.2 illustrates the architecture of the re-id module. Pretraining of the model was conducted on the Imagenet dataset, followed by fine-tuning with our dataset. Data preprocessing steps were implemented as described in Chapter 3. Augmentation techniques were applied to augment the dataset. The adopted transformations will be detailed later in Section 5.2.. Evaluation of the model’s performance was carried out using the cross-entropy loss function: LCE =− N ∑ i=1 qilog(p(fi)) (4.1) Where qiis the one-hot vector of the i-th sample, and p(fi)is the prediction probability of fi, computed from the softmax function of one of the identities. The model returns the confidence of each identity class, which can be converted to a label class by selecting the prediction with the greatest confidence. 4.4. Tracker Module The tracker module is the module in charge of giving temporal consistency to the predictions of the model. It employs a SORT tracker [15] to extract the initial trajectories of the bounding boxes provided by the detector module.
50 Animal tracking and identification in smart farms Figure 4.2: Re-identification model Architecture based on ResNet-50. The model contains a residual connection in each residual block to facilitate gradient flow through the network. The SORT tracker leverages image information and bounding box data from each frame of the video to establish instance trajectories. It achieves this by tracking the positions of instances across consecutive frames and employing an Intersection-over-Union (IoU) correlation metric between their bounding boxes. This metric is defined by the equation: IoU =Area of overlap Area of union (4.2) To prevent erroneous associations between distinct instances in subsequent frames, a combinatorial optimization technique called Hungarian algorithm is utilized to determine the optimal combination of associations. This algorithm prioritizes associations with the highest IoUs, reassigning instances with lower IoUs accordingly. For predicting future bounding boxes, the SORT tracker employs a Kalman filter and compares the projected bounding boxes with actual future bounding boxes. The same association metrics are then utilized to associate these predicted bounding boxes. The SORT tracker provides a set of predicted bounding boxes along with their respective track identifications. As we are interested in associating each track ID with the bounding box predicted by the detector module, we applied a secondary application of the Hungarian algorithm. That enables us to associate the predicted IDs from the Re-ID module with the trajectory IDs predicted by the tracker module, as required in the voting module. 4.5. Voting Module The voting module uses a sliding window technique to enhance the proposed model’s predictions. The sliding window is a post-processing step that applies a voting criterion between the re-identification predictions and tracks produced by the tracker module to correct the prediction error of the re-identification module. This block takes the predictions of the adjacent frames of each track to determine if the current prediction was properly classified. If there was a sporadic false prediction on one of the instances of a track, the sliding window would be capable of correcting it. As this window uses predictions from future instances, the post-processing step cannot be performed in real time.
The Proposed Model 51 To further improve the performance of the re-identification module, we combine its outputs with the trajectories obtained by the tracker module using a voting scheme, as detailed next. This technique utilizes the tracker IDs to identify adjacent instances relative to the current one and employs a voting protocol among the re-identification IDs of these neighboring instances. The outcome is a new re-identification ID assigned to the current instance, serving as the output of the proposed model. The employed voting protocol follows a maximum confidence approach. This method aggregates the confidence (given by the Re-ID module) of all predictions within the window and selects the prediction with the highest confidence level. This process is illustrated in Figure 4.3. Mathematically, this operation can be expressed as follows: Being Wthe sliding window, and Cfi={c1,c2,...,cm}the set of confidences of one sample from the window, sum each set of confidences: CW= n ∑ i=1 Cfi(4.3) And extract the prediction with the greatest confidence from the window’s confidences CW: Pred =arg max cj∈CW cj(4.4) Figure 4.3: Maximum confidence voting criteria. The sliding window pass through each SORT track and performs a weighted voting with the confidences of the re-identification predictions.
CHAPTER 5. EXPERIMENTS This chapter presents the experiments required to reach the desired results described in Chapter 4as well as the settings established during the training process. As our main focus was the re-identification model, we split the ablation study into two differential phases: the re-identification module, and the tracking module of the MOT architecture, which includes the voting scheme. Additionally, we performed a qualitative study to understand how the model is behaving, and why it could commit false detections. In Section 5.1. we detail how the preprocessing of the data was performed. Then, in Section 5.2. we describe the steps performed to obtain the re-identification model. Section 5.3. describes the steps performed to set the tracker and voting modules. Finally, in Section 5.4. a qualitative analysis is presented. 5.1. Pre-Processing Figure 5.1: Data pre-processing performed by the re-identification module. The bounding boxes from the gallery are converted to grayscale and normalized with a database normalization. Then, they are masked with the mask predicted by the detector module, and the result is resized and padded to fulfill the input dimensions of the re-id module. Before starting the processing of each image within the dataset during the training phase, the model undertakes a pre-processing step (see Figure 5.1). This crucial step serves to mitigate any dimensionality discrepancies between the model and the gallery images, rectify certain illumination biases, and alleviate interference from other identities. It is applied in all the phases of the re-identification module training and testing. The pre-processing comprises the following sequential steps: 1. Grayscale: This step involves converting an RGB image to a grayscale image, thereby reducing the number of neurons in the network’s initial layer. While this process mitigates illumination biases, it comes at the cost of losing some color features of the pigs. That makes the model more compact and computationally efficient. 2. Standardize: Utilizing the mean and standard deviation computed from all valid images in the dataset at the channel level, this process normalizes the grayscale 53
60 Animal tracking and identification in smart farms (a) Loss (b) Accuracy Figure 5.3: Loss and accuracy of the ResNet-50 and ViT-B models. Table 5.6: Backbone comparison on the re-identification task. ResNet-50 ViT-B Scratch Pretrained Scratch Pretrained No Flip Val 93% 97% 81% 93% Test 73% 82% 56% 69% Flip Val 41% 51% 24% 33% Test 32% 41% 19% 24% 5.2.5. Data Augmentation The ResNet-50 model pretrained on Imagenet was also tested with different data augmentations to enhance its generalization capacity. The augmentations used for this setup are random brightness, random contrast, random noise, random rotation, random translation, and random crop. Through the subsequent sections we performed different experiments to evaluate the different transformations individually, and combined. The data augmentation was performed after the pre-processing step described in Section 5.1. 5.2.5.1. Random Brightness Figure 5.4: Representation of the bright augmentation. Bright augmentation involves introducing a (random) offset to the illumination of the image, which can be represented by the following equation:
Experiments 61 y=x+scale (5.7) Here, xrepresents the input grayscale image, and yrepresents the transformed image. Upon testing this transformation at various scales (see Table 5.7), we observed that the bright transformation did not enhance the model’s generalization capability. Table 5.7: Data Augmentation Test: Brightness Bright Scale No Flip Flip 0 0.1 0.3 0.5 0 0.1 0.3 0.5 Val 97.0% 86.0% 89.0% 93.0% 51.0% 37.0% 37.0% 38.0% Test 82.0% 70.0% 74.0% 76.0% 41.0% 32.0% 31.0% 32.0% 5.2.5.2. Random Contrast Figure 5.5: Representation of the contrast augmentation. Contrast augmentation involves applying a (random) scale factor to the image illumination, which enlarges or reduces the difference between the illumination of pixels. It is represented as follows: y=x·scale (5.8) Here, xrepresents the input grayscale image, and yrepresents the transformed image. However, this transformation did not provide any improvement in the model’s generalization capability. Table 5.8 displays the accuracy of the model at different contrast scales. Table 5.8: Data Augmentation Test: Contrast Contrast Scale No Flip Flip 0 0.1 0.3 0.5 0 0.1 0.3 0.5 Val 97.0% 88.0% 88.0% 86.0% 51.0% 37.0% 36.0% 33.0% Test 82.0% 70.0% 72.0% 68.0% 41.0% 33.0% 31.0% 28.0% 5.2.5.3. Random Noise Noise augmentation involves introducing a random offset through all the pixels, using the following equation:
62 Animal tracking and identification in smart farms Figure 5.6: Representation of the noise augmentation. y=x+(n·stdn+meann)(5.9) Here, xrepresents the input image, yrepresents the transformed image, nrepresents a noisy image, stdnstands for its standard deviation, and meannstands for the mean of the noise. Similarly to the other methods, noise augmentation does not provide any improvement in the model’s generalization capability. Table 5.9: Data Augmentation Test: Noise Noise (Std) No Flip Flip 0 0.3 0.6 1 0 0.3 0.6 1 Val 97.0% 96.0% 95.0% 95.0% 51.0% 44.0% 39.0% 37.0% Test 82.0% 79.0% 77.0% 75.0% 41.0% 36.0% 31.0% 29.0% 5.2.5.4. Random Rotation Figure 5.7: Representation of the rotation augmentation. Rotation augmentation randomly rotates the images until a certain angle in both directions. This transformation was the most useful for achieving good generalization capabilities, minimizing any potential bias provided by the flip transformation. Table 5.10 compares the accuracy of this transformation at different maximum angles. Comparing the results at different maximum angles, we can appreciate that the accuracy of the flipped images improves linearly until 90◦, then the improvement is not so significant and at 180◦it reaches the same accuracy than the non-flip version. As stated in Section 5.2.1., it is possible that the model relied too much on the shape of the instances masks on
Experiments 63 the previous experiments, losing the capability of generalizing after the application of a geometric transformation. The rotation transformation forces the model to generalize among several masks shapes, not being capable of using the identity shape as a bypass to solve the problem. That forces the model to extract more representative features from the animal patterns, instead of relying on its shape, surpassing other geometric transformations such as the flip transformation. Table 5.10: Data Augmentation Test: Rotation Rotation No Flip Flip 0◦45◦90◦180◦0◦45◦90◦180◦ Val 97.0% 98.0% 97.0% 97.0% 51.0% 78.0% 94.0% 97.0% Test 82.0% 85.0% 85.0% 84.0% 41.0% 64.0% 79.0% 84.0% 5.2.5.5. Random Translation Figure 5.8: Representation of the translation augmentation. Translation augmentation involves displacing the image along the vertical and horizontal axes and adding padding to the ”empty” pixels. While this transformation slightly enhanced the model’s generalization capability, the improvement was not significant. This modest enhancement is demonstrated in Table 5.11. Table 5.11: Data Augmentation Test: Translation Translation No Flip Flip 0.0% 10.0% 30.0% 50.0% 0.0% 10.0% 30.0% 50.0% Val 97.0% 97.0% 97.0% 98.0% 51.0% 50.0% 48.0% 51.0% Test 82.0% 84.0% 84.0% 85.0% 41.0% 41.0% 41.0% 42.0% 5.2.5.6. Random Crop Crop augmentation was devised to select one of the existing pixels in the mask and utilize it as the cropping center to prevent empty crops. The resulting cropped images are then resized to maintain the same shape as the input image. Table 5.12 illustrates that cropped images did not improve the model’s generalization capability. Conversely, if cropping is constrained to solely detect local features, it may perform worse, likely due to the absence of contextual information.
64 Animal tracking and identification in smart farms Figure 5.9: Representation of the crop augmentation. Table 5.12: Data Augmentation Test: Cropping. The crop size is the size of the bounding box used to crop the gallery image. Min Crop Size 100% 30% 10% 10% 50% Max Crop Size 100% 90% 90% 50% 90% No Flip Val 97.0% 97.0% 97.0% 76.0% 97.0% Test 82.0% 83.0% 83.0% 62.0% 83.0% Flip Val 51.0% 44.0% 46.0% 29.0% 45.0% Test 41.0% 38.0% 37.0% 26.0% 37.0% 5.2.5.7. Rotation + Translation An additional test was conducted, combining both rotation and translation augmentations. Interestingly, we observed in Table 5.13 that the translation augmentation did not contribute to any improvement when used alongside rotation augmentation. This suggests that the slight improvement in generalization provided by translation augmentation was already achieved by rotation augmentation alone. Consequently, the best-performing model was ResNet-50 pretrained on ImageNet, augmented with rotation only. Based on these experiments and results, we decided to use rotation only as data augmentation. The next experiments follow this configuration in the data augmentation.
Experiments 65 Table 5.13: Data Augmentation Test: Rotation + Translation Rotation 0.0◦45.0◦90.0◦180.0◦ Trans. No Flip Val 0.0% 97.0% 98.0% 97.0% 97.0% 10.0% 97.0% 98.0% 98.0% 97.0% 30.0% 97.0% 98.0% 97.0% 97.0% 50.0% 98.0% 98.0% 97.0% 96.0% Test 0.0% 82.0% 85.0% 85.0% 84.0% 10.0% 84.0% 86.0% 85.0% 84.0% 30.0% 84.0% 86.0% 85.0% 84.0% 50.0% 85.0% 86.0% 85.0% 83.0% Flip Val 0.0% 51.0% 78.0% 94.0% 97.0% 10.0% 50.0% 80.0% 94.0% 97.0% 30.0% 48.0% 80.0% 94.0% 97.0% 50.0% 51.0% 80.0% 94.0% 96.0% Test 0.0% 41.0% 64.0% 79.0% 84.0% 10.0% 41.0% 66.0% 80.0% 83.0% 30.0% 41.0% 68.0% 79.0% 84.0% 50.0% 42.0% 67.0% 81.0% 83.0% 5.2.6. Final Results A final evaluation was conducted by expanding the dataset size to include 4000 samples per identity. Table 5.14 presents the conclusive scores for both pretraining methods. Both the scratch and Imagenet models were trained on identical ResNet-50 architectures, each with the same number of layers. Both models were augmented with the rotation augmentation. Upon comparing the outcomes of the two models, it’s evident that the Imagenetpretrained model performed the best, achieving a test accuracy of 85%. Table 5.14: Final Comparison of the re-identification model. Video ID Validation Test Scratch Imagenet Scratch Imagenet Accuracy 98.0% 99.0% 77.0% 85.0% Parameters 23.57 M 23.57 M 23.57 M 23.57 M To perform more exhaustive analysis of the qualitative results, we presented the F1-score of the identities from all datasets along with the displacement of each identity. Table 5.15 presents the F1-scores of all the identities from the first dataset, while Table 5.16 and Table 5.17 present the F1-scores of the identities from the second and third datasets respectively. All these tables show the mean displacement magnitude of each identity individually, to determine if an identity was inactive, low displacement, or active, high displacement. Across all videos, satisfactory results were observed, with no single video dominating the representation. All the datasets had a micro average F1 score of 89%, except for the second dataset, which had a slightly lower F1 score (83%). This reduction in the microaverage F1-score could be produced by the higher pose diversity in the second dataset,
66 Animal tracking and identification in smart farms Table 5.15: Final Comparison (F1-score) of the re-identification model (First Dataset). Video ID Disp. (Mag.) Validation Test Mean Std Scratch Imagenet Scratch Imagenet 1st A 9.84 20.52 95.0% 98.0% 76.0% 81.0% B 5.51 13.23 93.0% 95.0% 63.0% 74.0% C 3.63 4.58 99.0% 99.0% 96.0% 94.0% D 1.78 3.71 98.0% 99.0% 85.0% 87.0% E 10.03 19.89 95.0% 97.0% 68.0% 76.0% F 1.40 4.47 99.0% 100.0% 95.0% 97.0% G 3.21 4.22 99.0% 99.0% 86.0% 91.0% H 0.95 2.29 100.0% 100.0% 99.0% 99.0% I 2.15 4.24 99.0% 100.0% 87.0% 87.0% Micro Avg. - - 98.0% 99.0% 86.0% 89.0% Table 5.16: Final Comparison (F1-score) of the re-identification model (Second Dataset). Video ID Disp. (Mag.) Validation Test Mean Std Scratch Imagenet Scratch Imagenet 2nd J 2.94 12.35 97.0% 99.0% 64.0% 78.0% K 4.05 11.30 97.0% 99.0% 76.0% 81.0% L 3.90 11.33 97.0% 98.0% 71.0% 82.0% M 2.88 13.58 98.0% 99.0% 66.0% 80.0% N 1.74 3.81 98.0% 99.0% 77.0% 86.0% O 2.63 12.87 98.0% 99.0% 69.0% 85.0% P 2.19 7.87 98.0% 99.0% 74.0% 84.0% Q 1.79 4.57 99.0% 99.0% 70.0% 82.0% R 2.05 8.25 99.0% 99.0% 82.0% 89.0% Micro Avg. - - 98.0% 99.0% 72.0% 83.0% Table 5.17: Final Comparison (F1-score) of the re-identification model (Third Dataset). Video ID Disp. (Mag.) Validation Test Mean Std Scratch Imagenet Scratch Imagenet 3rd AA 3.11 5.94 98.0% 99.0% 76.0% 88.0% AC 3.15 7.15 99.0% 100.0% 82.0% 87.0% AD 1.36 2.15 100.0% 100.0% 95.0% 96.0% AF 2.55 6.86 99.0% 100.0% 78.0% 87.0% AG 4.84 11.93 96.0% 99.0% 53.0% 84.0% AH 4.29 5.04 95.0% 99.0% 65.0% 78.0% AI 1.25 2.04 100.0% 100.0% 93.0% 93.0% AJ 3.32 8.69 98.0% 99.0% 70.0% 81.0% AK 1.13 3.26 100.0% 100.0% 91.0% 90.0% AM 1.73 3.55 100.0% 100.0% 94.0% 92.0% AN 3.71 5.32 99.0% 100.0% 84.0% 88.0% AS 2.53 3.44 99.0% 99.0% 84.0% 89.0% AT 3.99 8.29 97.0% 99.0% 63.0% 84.0% AU 3.80 4.58 98.0% 99.0% 82.0% 88.0% AW 3.02 3.49 99.0% 100.0% 84.0% 90.0% Micro Avg. - - 99.0% 100.0% 82.0% 89.0%
Experiments 67 since their samples were taken from a longer video (as detailed in Section 3.3.). That reduces the possibility of having easy cases (inactive pigs whose samples are almost identical). Generally, F1-scores for all identities exceeded 74%, with the most accurately detected identity being Pig H, boasting an F1-score of 99%. This possibly arises from the relative inactivity of Pig H (as observed on its mean displacement), resulting in a lack of diversity within its samples. Among the identities, pigs B, E, J, and AH displayed the lowest F1 scores (<80%), while pigs C, F, H, AD, AI, AK, AM, and AW exhibited the highest F1 scores (>90%). Interestingly, these scores don’t appear directly correlated with the animals’ behavior when comparing mean displacement and the model’s results. That suggests that further analysis by individual folds, performed in Section 5.4. as part of the qualitative analysis, could reveal insightful detail of the identities. Figure 5.10: Confusion matrix of the best re-identification model. Figure 5.10 illustrates the confusion matrix derived from the top-performing re-identification
68 Animal tracking and identification in smart farms model (i.e., ResNet-50, pretrained). Due to dataset unbalance, notably with significantly more samples from the second dataset compared to the others, the sample count varies for each identity along the diagonal of the matrix. Consequently, identities from J to R are over-represented. The majority of samples are correctly classified, resulting in a predominantly diagonal layout in the confusion matrix. However, an environmental bias is discernible in misclassified samples. The model exhibits a tendency to misclassify identities from one recording as identities captured in the same video, particularly over-representing false detections between identities from J to R compared to those from A to I or AA to AW. This bias could stem from factors such as scene illumination, camera dirtiness, or the proximity of identities to the camera. Despite the considerable effort invested in collecting and constructing the dataset, several challenges remain to be addressed in future work. Firstly, despite implementing various normalization and masking techniques to mitigate the impact of environmental illumination and clutter, the experimental outcomes still indicate the presence of environmental biases. Secondly, while attaining satisfactory experimental results overall, we also observed deviations for certain identities, such as pig H, indicating potential limitations in the diversity of data associated with certain IDs. These challenges are associated to the data collection, protocols, and preparation, which could imply a complex task to be done. 5.3. Tracker and Voting Modules 5.3.1. Implementation Details and Testing Strategy In this section, we will analyze the performance of our Multi-Object Tracking (MOT) model in a real-case scenario, using the recording from the first dataset as our test set. In this test, we do not apply any filtering step to the dataset, although we maintain all the preprocessing phases of the re-identification module. As explained in Section 4, our architecture consists of four distinct components: the detector module, the re-identification module, the tracker module and the voting module. In this experiment we will evaluate the conjunction of the re-identification, tracker and voting modules. The re-identification module employs the best model obtained in Section 5.2.6. As described there, it is a ResNet-50 classifier pretrained on Imagenet, and fine-tuned with the LehmanPigBoy-33 dataset. During the fine-tuning process, the data was augmented with the rotation augmentation. In this experiment, as the re-identification module was trained on a 10-fold setup, we will predict the results by assigning each model on their respective test set. The tracker module uses the frame information and the bounding boxes of the identities, stored in the dataset, to connect the identities of each consecutive frame. It cannot determine which identity is being tracked as it doesn’t have re-identification capabilities, or access to identity labels. Nonetheless, it could offer some alternative IDs to identify each
Experiments 69 track. It uses a SORT tracker configured to wait for 5 non-detected consecutive frames to end a track and create a new track without waiting for consecutive hits. The IoU threshold was set to 10%. Finally, two different voting criteria were tested in a sliding window, detailed in Section 5.3.3. and Section 5.3.4. One performs hard voting, where the most represented identity in the window is the one assigned at that specific frame, and the other performs maximum confidence voting, where the confidence of all the predictions is summed up to get the most represented identity. Six different sliding window sizes were tested in the ablation study. 5.3.2. Tracker Module: SORT Tracker Prior to testing the voting module, we studied the results of the tracker module. The first recording was processed with the SORT tracker configured as detailed in Section 5.3.1. From that video, we extracted 41 distinct tracks with a mean length of 204.68 frames and a standard deviation of 376.97 frames. Table 5.18 shows the statistics per track. In order to evaluate the quality of the tracks provided by the SORT tracker, we compared the tracking IDs with the identity IDs of the first dataset. From this comparison, we computed the number of times the tracker changes its expected ID, as the identity switching metric. In Table 5.18, we can observe that only the tracks 5, 8, 15, 17 and 19 switched their expected ID, while all the other tracks always tracked the same identity. These identity switches could be produced by cluttering, occlusions, or re-assignment of pigs that left the scene. The mean number of identity switches was 0.39, demonstrating that most of the tracks are tracking their instances properly. Table 5.18: Statistics of the SORT Tracks for the first tracking video. ID Sw. stands for ID Switches. Tracks Frames ID Sw. Tracks Frames ID Sw. Tracks Frames ID Sw. 1 893 0 15 515 1 29 22 0 2 888 0 16 3 0 30 4 0 3 1590 0 17 76 1 31 12 0 4 779 0 18 2 0 32 1 0 5 1113 4 19 18 1 33 7 0 6 33 0 20 1 0 34 2 0 7 1 0 21 8 0 35 6 0 8 780 9 22 1 0 36 11 0 9 5 0 23 4 0 37 195 0 10 4 0 24 71 0 38 15 0 11 718 0 25 2 0 39 1 0 12 34 0 26 5 0 40 292 0 13 20 0 27 5 0 41 238 0 14 4 0 28 13 0 Mean 204.68 0.39 Std 376.97 1.51 In Table 5.19, we assigned each track to their expected IDs to determine which identities
76 Animal tracking and identification in smart farms (a) 1/3 (b) 2/3 (c) 3/3 Figure 5.15: Frames of the second tracking video. Table 5.24: Description of each pig’s behavior at each fold (Second Tracking Video). Fold 0 1 2 3 4 5 6 7 8 9 J65% 69% 78% 85% 85% 61% 91% 77% 94% 78% Pig J walks around the pen, quitting and entering the pen several times, and interacting with the other pigs. After fold 6, it rests at the back of the pen. N53% 95% 83% 93% 95% 87% 87% 85% 95% 80% Pig N rests during folds 1 and 2. Then, it walks around and rests at another location after fold 3. It stays at the same location until fold 9. O85% 67% 74% 82% 85% 88% 99% 96% 96% 74% Pig O walks around the pen and after fold 2, it rests behind Pig R. After fold 3, it walks around and lays after fold 4. It stands up after fold 9. 5.4.0.3. Third Tracking Video In contrast to the previous videos, the third tracking video features a higher number of pigs, resulting in more occlusions and reduced visibility of each pig on the screen. The little presence of some identities makes this video less rich in pose features but more representative of a real-case scenario. Figure 5.16 represents the activity of each identity. (a) 1/3 (b) 2/3 (c) 3/3 Figure 5.16: Frames of the third tracking video. Similar to the first tracking video, deviations are evident in Table 5.25 for both sedentary and active pigs, especially when their visibility is limited. Pigs AD, AI, AK, and AT, known for their sedentary behavior, exhibit nearly flawless predictions in some folds. However, their F1 scores deteriorate notably when they alter their poses, as observed in fold 9 for
Experiments 77 pigs AI, AK, and AT. Additionally, due to the limited number of samples and the constraints imposed on the pigs’ movements (resulting from occlusions), some active pigs also exhibit diminished F1 scores in certain folds, such as fold 0 for pigs AC, AG, or AH. Table 5.25: Description of each pig’s behavior at each fold (Third Tracking Video). Fold 0 1 2 3 4 5 6 7 8 9 AC 27% 95% 93% 95% 99% 99% 74% 98% 100% 91% Pig AC stands up after fold 0 and walks around the pen. It leaves the scene after fold 5. It stays on the left side of the scene during the following folds. AD 74% 99% 100% 100% 100% 100% 98% 100% 95% 98% It rests at the same location during the whole video. AG 67% 55% 93% 95% 79% 95% 82% 96% 81% 89% Pig AG is sitting down at the pen’s back, stands up, and walks around. At fold 4, it leaves the scene. During the following fold, it walks around the left side of the scene. AH 27% 49% 90% 81% 97% 96% 97% 86% 94% 48% Pig AH walks around occluded by other pigs, and leaves. It is pregnant. AI 81% 99% 99% 100% 100% 99% 98% 99% 98% 22% Pig AI rests at the left corner of the pen during the whole video. AK 100% 98% 99% 100% 100% 92% 82% 100% 88% 9% Pig AK stays at the same location at the bottom border of the camera, and leaves during fold 9. AT 45% 79% 96% 96% 100% 98% 97% 99% 83% 14% Pig AT moves around the pen, stays at the same location after fold 3, and leaves.
78 Animal tracking and identification in smart farms 5.4.1. Tracking In this section, we analyzed the qualitative results of the re-identification module with the maximum confidence voting scheme. It leverages a SORT tracker to maintain consistency across consecutive frames and employs a voting criterion to rectify errors from both the SORT tracker and the re-identification model. This section compared the results with a sliding window of size 3 and 501 samples. Figure 5.17 shows the detection of each individual across time using a SORT tracker and a sliding window of size 3. This plot demonstrates a good detection of the instances, although it still has several false detections. Pig I, for example, demonstrated poor results at the end of the recording, while Pig H had errors at both the start and end. To explain the reason for these errors, we exhibited some keyframes of the video in Figure 5.18. In these keyframes, we can see particular cases where the algorithm failed to assign the proper ID to a certain pig or group of pigs, some alternative predictions, and the confidence of the model’s prediction per pig. Figure 5.17: Representation of the identity tracks after applying a sliding window of size 3. At the beginning of the video, both Pig A and H were not accurately detected. For Pig A, the correct prediction ranked second with a confidence of 34%, indicating that the model wasn’t significantly confident. However, for Pig H, none of the top three predictions were correct, highlighting a complete misclassification. Interestingly, the model seemed to detect certain correlations among pigs on the left side of the scene, as all three pigs were identified as Pig D, despite preprocessing the identities before passing them through the re-identification model.
Experiments 79 (a) Frame 2190 (b) Frame 4770 (c) Frame 5460 (d) Frame 6900 Figure 5.18: Key frames of the first tracking video using a sliding window with size 3. Some false detections occurred due to sudden increases in the identity’s activity, such as leaving the scene or interacting with other pigs. For instance, Pig D in frame 4770 and Pig A and F in frame 5460 were all instances of pigs leaving the scene. Furthermore, the occlusion of Pig G and the interaction between Pig I and H resulted in false detections of both identities in frame 6900. Some of these errors may stem from a lack of data diversity, indirectly caused by data filtering, as Pig H was mostly occluded in frame 6900. Overall, as the sliding window is relatively small, most errors observed were caused by the re-identification model. Consequently, some tracks may lose consistency with the predictions, leading to sporadic false detections for each identity. Figure 5.19 shows the case with a sliding window of 501 samples. As the sliding window is larger than most tracks produced by the SORT tracker, we can assume that there is only a unique prediction per track, removing any sporadic false detection within the tracks. This approach cannot address some tracking errors such as identity-switching or the prediction error of some lost samples. The first issue arises due to the size of the sliding window, as one of the identities within the track will dominate against the other. The second is because there are not enough samples in the track to correct the prediction error of that lost sample. This suggests that the sliding window depends on a trade-off between the sporadic false detections of the re-identification model and the identity-switching error of
80 Animal tracking and identification in smart farms the SORT tracker. However, in our testing, we appreciated a dominance in the prediction error of the re-identification model, achieving better results with a large sliding window size. Figure 5.19: Representation of the identity tracks after applying a sliding window of size 501. As depicted in Figure Figure 5.20, most identities were accurately tracked and re-identified in the video. However, there were instances where the model failed to track the correct identity. For example, in frames 4920 and 5100, Pig F was misclassified as Pig I. This discrepancy wasn’t observed with a sliding window of 3 samples, indicating that it likely resulted from an identity-switching error. Similarly, Pig B was misclassified in frame 4920 in both window configurations, suggesting that these samples belong to a separate track. Additionally, an identity-switching error occurred in frame 5280 between Pig A and I. Overall, the tracker exhibited strong performance in many scenarios. However, it is not yet entirely immune to unusual behaviors exhibited by the identities. The configuration with a window size of 501 samples proved to be more robust than the configuration with a window size of 3 samples. Nonetheless, this larger window configuration was more susceptible to SORT errors, resulting in some new misclassifications not present in the smaller window size configuration.
Experiments 81 (a) Frame 4920 (b) Frame 5100 (c) Frame 5280 Figure 5.20: Key frames of the first tracking video using a sliding window with size 501.
82 Animal tracking and identification in smart farms
CHAPTER 6. CONCLUSIONS AND FINAL REMARKS 6.1. Conclusions The objective of this project was to develop, test, and deploy a re-identification model to enhance a tracking-by-detection MOT (Multiple Object Tracking) algorithm specifically tailored for pig farming. The project unfolded in two primary phases: first, the creation of a customized dataset for tracking within pig farming environments, called LehmanPigBoy-33 Dataset, followed by the development of the pig identifier and tracker itself. To generate the dataset, we implemented a specialized annotation pipeline designed to create masks of the pigs while preserving their unique identity IDs. This pipeline was based on the SAM meets point tracking (SAM-PT) approach [14]. The final dataset was compiled from three distinct recordings captured at various times and locations on the farm, comprising over 94,000 images and encompassing 33 different identities. Each identity included gallery images, corresponding masks, and relevant metadata such as label IDs and bounding boxes. The dataset was partitioned using a 10-fold approach, with one fold allocated for testing and the remainder for training and validation. The best re-identification model employed a ResNet-50 backbone pre-trained with Imagenet and fine-tuned using our dataset. Rotation transformation was applied during the training process for data augmentation. Several alternative approaches were explored, including visual transformers (ViT-B), the implementation of a MoCo architecture for pretraining, and training the model from scratch. Various data augmentation techniques such as translation, cropping, and brightness adjustment were also evaluated. The final model achieved a mean validation accuracy of 99% and a test accuracy of 85%, with F1 scores exceeding 74% per identity. Our tracking-by-detection MOT architecture comprises a detector module, a re-identification module, a tracker module, and voting module. The detector module was based on a YOLOv8 instance segmentation model to extract bounding boxes and masks of the identities. The re-identification module was based on a ResNet-50 classifier, while the tracker module was based on the SORT tracker algorithm. Finally, the voting module integrates both re-identification and tracker modules results using a sliding window approach. Our focus was primarily on the re-identification module, assuming an ideal instance segmenter from the detector module. In testing, two different voting criteria were applied to the sliding window: hard voting and maximum confidence voting. Both criteria yielded similar results, achieving a test accuracy of 98% on the first recording with a sliding window size of 501 samples. Overall, the proposed model demonstrated strong performance, effectively tracking most identities throughout the video sequences. However, there were instances where the reidentification model failed to correctly identify pigs, and the sliding window approach was 83
84 Animal tracking and identification in smart farms unable to rectify these errors. The model also exhibited sensitivity to identity-switching errors within the SORT tracker, indicating room for further refinement and improvement. Besides, some environmental bias was observed on the re-identification results. In the realm of future enhancements for the re-identification model, several avenues could be explored. This might involve integrating alternative re-identification methods, such as gallery retrieval or a verification loss, as well as incorporating attention mechanisms. Additionally, expanding the dataset by including more identities and increasing the number of samples per identity could bolster the model’s robustness and overall performance. To further refine the tracker block, additional measures could be taken. This could entail integrating projection mechanisms to augment the SORT tracker’s capabilities. Moreover, integrating the Hungarian algorithm at the conclusion of the tracker could mitigate instances of repeated identities, thereby enhancing the overall tracking accuracy. 6.2. Ethical Concerns This project aimed to design a model capable of identifying and tracking pigs in a smart farm for monitoring purposes. As it involves individuals’ identification, an improper use of this model could affect people’s privacy. This model was solely intended to identify pigs in closed-world conditions. The use of this model for other purposes is not recommended. 6.3. Data Availability This dataset was created for industrial purposes. The authors do not have the authorization to share the content of this data.
BIBLIOGRAPHY [1] Minghui Liu, Yafei Zhang, and Huafeng Li. Survey of cross-modal person reidentification from a mathematical perspective. Mathematics, 11(3), 2023. xv,5, 12,16 [2] Mang Ye, Jianbing Shen, Gaojie Lin, Tao Xiang, Ling Shao, and Steven C. H. Hoi. Deep learning for person re-identification: A survey and outlook, 2021. xv,5,15 [3] Glenn Jocher, Ayush Chaurasia, and Jing Qiu. Ultralytics YOLO, January 2023. xv, 21,25,26,48 [4] Alexander Kirillov, Eric Mintun, Nikhila Ravi, Hanzi Mao, Chloe Rolland, Laura Gustafson, Tete Xiao, Spencer Whitehead, Alexander C. Berg, Wan-Yen Lo, Piotr Doll´ ar, and Ross Girshick. Segment anything, 2023. xv,20,25,27,33,34 [5] Alex Bewley, Zongyuan Ge, Lionel Ott, Fabio Ramos, and Ben Upcroft. Simple online and realtime tracking. In 2016 IEEE International Conference on Image Processing (ICIP). IEEE, September 2016. xv,22,33,34,35 [6] J. Maselyne, I. Adriaens, T. Huybrechts, B. De Ketelaere, S. Millet, J. Vangeyte, A. Van Nuffel, and W. Saeys. Measuring the drinking behaviour of individual pigs housed in group using radio frequency identification (rfid). animal, 10(9):1557–1566, 2016. 1 [7] Janice M. Siegford, John Berezowski, Subir K. Biswas, Courtney L. Daigle, Sabine G. Gebhardt-Henrich, Carlos E. Hernandez, Stefan Thurner, and Michael J. Toscano. Assessing activity and location of individual laying hens in large groups using modern technology. Animals, 6(2), 2016. 1 [8] Jinseong Kim, Yeonwoo Chung, Younchang Choi, Jaewon Sa, Heegon Kim, Yongwha Chung, Daihee Park, and Hakjae Kim. Depth-based detection of standing-pigs in moving noise environments. Sensors, 17(12), 2017. 1 [9] Tanwi Mallick, Partha Pratim Das, and Arun Kumar Majumdar. Characterizations of noise in kinect depth images: A review. IEEE Sensors Journal, 14:1731–1740, 2014. 1 [10] Qinghua Guo, Yue Sun, Cl´ emence Orsini, J. Elizabeth Bolhuis, Jakob de Vlieg, Piter Bijma, and Peter H.N. de With. Enhanced camera-based individual pig detection and tracking for smart pig farms. Computers and Electronics in Agriculture, 211:108009, 2023. 1,20,21,22,23,24,47 [11] Wenhan Luo, Junliang Xing, Anton Milan, Xiaoqin Zhang, Wei Liu, and Tae-Kyun Kim. Multiple object tracking: A literature review. Artificial Intelligence, 293:103448, April 2021. 2,20 [12] Shengyong Chen, Yingkun Xu, Xiaolong Zhou, and Fenfen Li. Deep learning for multiple object tracking: A survey. IET Computer Vision, 13, 01 2019. 2,20 85
92 Animal tracking and identification in smart farms [91] L Zhang and LJP van der Maaten. Structure preserving object tracking. In G Medioni, R Zabih, and M Herbert et al, editors, Proceedings 2013 IEEE Conference on Computer Vision and Pattern Recognition, pages 1838–1845, United States, 2013. IEEE. 2013 IEEE CVPR, Portland, OR, USA ; Conference date: 23- 06-2013 Through 28-06-2013. 20 [92] Mateusz Mittek, Eric Psota, Jay Carlson, Lance P´ erez, Ty Schmidt, and Benny Mote. Tracking of group-housed pigs using multi-ellipsoid expectation maximization. IET Computer Vision, 12, 11 2017. 20,23,24 [93] Adam W. Harley, Zhaoyuan Fang, and Katerina Fragkiadaki. Particle video revisited: Tracking through occlusions using point trajectories. In ECCV, 2022. 20 [94] Nikita Karaev, Ignacio Rocco, Benjamin Graham, Natalia Neverova, Andrea Vedaldi, and Christian Rupprecht. Cotracker: It is better to track together, 2023. 20 [95] Yang Zheng, Adam W. Harley, Bokui Shen, Gordon Wetzstein, and Leonidas J. Guibas. Pointodyssey: A large-scale synthetic dataset for long-term point tracking, 2023. 20 [96] Zongxin Yang and Yi Yang. Decoupling features in hierarchical propagation for video object segmentation. In Advances in Neural Information Processing Systems (NeurIPS), 2022. 20 [97] Yangming Cheng, Liulei Li, Yuanyou Xu, Xiaodi Li, Zongxin Yang, Wenguan Wang, and Yi Yang. Segment and track anything. arXiv preprint arXiv:2305.06558, 2023. 20 [98] Jinyu Yang, Mingqi Gao, Zhe Li, Shang Gao, Fangjing Wang, and Feng Zheng. Track anything: Segment anything meets videos, 2023. 20 [99] Bhavesh Tangirala, Ishan Bhandari, Daniel Laszlo, Deepak K. Gupta, Rajat M. Thomas, and Devanshu Arya. Livestock monitoring with transformer, 2021. 20, 21,23,24 [100] Fisher Yu, Dequan Wang, Evan Shelhamer, and Trevor Darrell. Deep layer aggregation, 2019. 20,24 [101] Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, and Sergey Zagoruyko. End-to-end object detection with transformers, 2020. 21,24 [102] Andrea Parmiggiani, Dong Liu, Eric Psota, Robert Fitzgerald, and Tomas Norton. Don’t get lost in the crowd: Graph convolutional network for online animal tracking in dense groups. Computers and Electronics in Agriculture, 212:108038, 2023. 21, 22,23,24 [103] Kaiming He, Georgia Gkioxari, Piotr Doll´ ar, and Ross Girshick. Mask r-cnn, 2018. 21,25,48 [104] Qiang Li, Ranyang Li, Kaifan Ji, and Wei Dai. Kalman filter and its application. In 2015 8th International Conference on Intelligent Networks and Intelligent Systems (ICINIS), pages 74–77, 2015. 21
BIBLIOGRAPHY 93 [105] Chanho Kim, Fuxin Li, Arridhana Ciptadi, and James Rehg. Multiple hypothesis tracking revisited. pages 4696–4704, 12 2015. 21 [106] Jiahui Chen, Hao Sheng, Yang Zhang, and Zhang Xiong. Enhancing detection model for multiple hypothesis tracking. pages 2143–2152, 07 2017. 21 [107] Minyoung Kim, Stefano Alletto, and Luca Rigazio. Similarity mapping with enhanced siamese network for multi-object tracking, 2017. 21 [108] Bing Wang, Li Wang, Bing Shuai, Zhen Zuo, Ting Liu, Kap Chan, and Gang Wang. Joint learning of convolutional neural networks and temporally constrained metrics for tracklet association. pages 386–393, 06 2016. 21 [109] Yongyi Lu, Cewu Lu, and Chi-Keung Tang. Online video object detection using association lstm. pages 2363–2371, 10 2017. 21 [110] Amir Sadeghian, Alexandre Alahi, and Silvio Savarese. Tracking the untrackable: Learning to track multiple cues with long-term dependencies, 2017. 21 [111] Anton Milan, Hamid Rezatofighi, Anthony Dick, and Ian Reid. Online multi-target tracking using recurrent neural networks. Proceedings of the AAAI Conference on Artificial Intelligence, 31, 04 2016. 21 [112] Nan Ran, Longteng Kong, Yunhong Wang, and Qingjie Liu. A Robust Multi-Athlete Tracking Algorithm by Exploiting Discriminant Features and Long-Term Dependencies: 25th International Conference, MMM 2019, Thessaloniki, Greece, January 8–11, 2019, Proceedings, Part I, pages 411–423. 01 2019. 21 [113] Yiming Liang and Zhou Yue. Lstm multiple object tracker combining multiple cues. pages 2351–2355, 10 2018. 21 [114] Xingyu Wan, Jinjun Wang, and Sanping Zhou. An online and flexible multi-object tracking framework using long short-term memory. pages 1311–13118, 06 2018. 21 [115] Ji Zhu, Hua Yang, Nian Liu, Minyoung Kim, Wenjun Zhang, and Ming-Hsuan Yang. Online multi-object tracking with dual matching attention networks, 2019. 21 [116] Siyu Tang, Mykhaylo Andriluka, Bjoern Andres, and Bernt Schiele. Multiple people tracking by lifted multicut and person re-identification. pages 3701–3710, 07 2017. 21 [117] Liqian Ma, Siyu Tang, Michael Black, and Luc Van Gool. Customized Multi-person Tracker, pages 612–628. 06 2019. 21 [118] Cong Ma, Changshui Yang, Fan Yang, Yueqing Zhuang, Ziwei Zhang, Huizhu Jia, and Xiaodong Xie. Trajectory factory: Tracklet cleaving and re-connection by deep siamese bi-gru for multiple object tracking, 2018. 22 [119] Hilke Kieritz, Wolfgang H¨ ubner, and Michael Arens. Joint detection and online multi-object tracking. 2018 IEEE/CVF Conference on Computer Vision and Pattern Recognition Workshops (CVPRW), pages 1540–15408, 2018. 22
94 Animal tracking and identification in smart farms [120] Mingxin Jiang, Chao Deng, Yinshan Yu, and Jingsong Shan. Multi-agent deep reinforcement learning for multi-object tracker. IEEE Access, PP:1–1, 02 2019. 22 [121] Liangliang Ren, Jiwen Lu, Zifeng Wang, Qi Tian, and Jie Zhou. Collaborative deep reinforcement learning for multi-object tracking. In European Conference on Computer Vision, 2018. 22 [122] Aniket Shirke, Aziz Saifuddin, Achleshwar Luthra, Jiangong Li, Tawni Williams, Xiaodan Hu, Aneesh Kotnana, Okan Kocabalkanli, Narendra Ahuja, Angela Green-Miller, Isabella Condotta, Ryan N. Dilger, and Matthew Caesar. Tracking grow-finish pigs across large pens using multiple cameras, 2021. 22,23,24,47 [123] C. B. Dev Narayan, Fayaz Rahman, Mohib Ullah, Faouzi Alaya Cheikh, Ali Shariq Imran, Christopher Coello, Øyvind Nordbø, G. Santhosh Kumar, and Madhu S. Nair. Tracking-by-self detection: A self-supervised framework for multiple animal tracking. In Ilias Maglogiannis, Lazaros Iliadis, John MacIntyre, and Manuel Dominguez, editors, Artificial Intelligence Applications and Innovations, pages 561–572, Cham, 2023. Springer Nature Switzerland. 22,23,24 [124] Zhenyao Wang and Tonghai Liu. Two-stage method based on triplet margin loss for pig face recognition. Computers and Electronics in Agriculture, 194:106737, 2022. 22,23,24 [125] Meiqing Wang, Mona L.V. Larsen, Dong Liu, Jeanet F.M. Winters, Jean-Loup Rault, and Tomas Norton. Towards re-identification for long-term tracking of group housed pigs. Biosystems Engineering, 222:71–81, 2022. 24 [126] Abdul Mueed Hafiz and Ghulam Mohiuddin Bhat. A survey on instance segmentation: state of the art. International Journal of Multimedia Information Retrieval, 9(3):171–189, July 2020. 23 [127] Ross Girshick, Jeff Donahue, Trevor Darrell, and Jitendra Malik. Rich feature hierarchies for accurate object detection and semantic segmentation, 2014. 25 [128] Ross Girshick. Fast r-cnn, 2015. 25 [129] Shaoqing Ren, Kaiming He, Ross Girshick, and Jian Sun. Faster r-cnn: Towards real-time object detection with region proposal networks, 2016. 25 [130] Joseph Redmon, Santosh Divvala, Ross Girshick, and Ali Farhadi. You only look once: Unified, real-time object detection, 2016. 25 [131] Joseph Redmon and Ali Farhadi. Yolov3: An incremental improvement, 2018. 25 [132] Alexey Bochkovskiy, Chien-Yao Wang, and Hong-Yuan Mark Liao. Yolov4: Optimal speed and accuracy of object detection, 2020. 25 [133] Glenn Jocher. YOLOv5 by Ultralytics, May 2020. 25 [134] Chien-Yao Wang, Alexey Bochkovskiy, and Hong-Yuan Mark Liao. Yolov7: Trainable bag-of-freebies sets new state-of-the-art for real-time object detectors, 2022. 25
[135] Chien-Yao Wang, Hong-Yuan Mark Liao, I-Hau Yeh, Yueh-Hua Wu, Ping-Yang Chen, and Jun-Wei Hsieh. Cspnet: A new backbone that can enhance learning capability of cnn, 2019. 25 [136] Jan Hosang, Rodrigo Benenson, and Bernt Schiele. Learning non-maximum suppression, 2017. 25 [137] Oleksiy Guzhva, Janice M. Siegford, and Christina Lunner Kolstrup. The hitchhiker’s guide to integration of social and ethical awareness in precision livestock farming research. Frontiers in Animal Science, 2, 2021. Cited by: 6; All Open Access, Gold Open Access, Green Open Access. 30 [138] S. Bellini. 7. The pig sector in the European Union, pages 183 – 195. Wageningen Academic, Leiden, The Netherlands, 2021. 30 [139] CVAT.ai Corporation. Computer Vision Annotation Tool (CVAT), November 2023. 34 [140] Kaiming He, Haoqi Fan, Yuxin Wu, Saining Xie, and Ross Girshick. Momentum contrast for unsupervised visual representation learning, 2020. 97
APPENDIX A. SELF-SUPERVISED LEARNING Self-supervised learning is a machine learning paradigm where a model learns the data representation without any kind of supervision. To do so, it is initially trained with a ”dummy” task, called pretext task, where the model attempts to correct or predict some transformations provided by the AI engineer. Then, the model is fine-tuned in a supervised way to perform the desired task, called downstream task. There are several types of self-supervised techniques, but the one we used in this context is called contrastive self-supervised learning, where a sample, called anchor sample, is compared with samples from the same class (positive samples), and samples from other classes (negative samples). The model is then trained to pull together the positive samples and push away the negative samples. This appendix provides a detailed explanation of the entire process involved in the ”semisupervised” self-supervised training of the re-identification model, an implementation that ultimately proved unsuccessful. In Section A.1. we described the architecture and implementation details of the self-supervised model, in Section A.2. we described how the data was prepared for the pretext task, in Section A.3. we defined the steps of the ablation study, and finally in Section A.4. we compared the self-supervised model with the models exhibited in Section 5.2.6. A.1. Implementation Details During the training process of the re-identification model, we tested a contrastive selfsupervised model based on MoCo’s (Momentum Contrastive) [140] architecture (Represented in Figure A.1). In this setup, the same sample is transformed and encoded by two different ResNet-50 encoders during the pretraining phase. The second encoder contains a queue of keys which are used as negative samples for the contrastive self-supervised task. These encoders generate a set of 1x128 embeddings, which are compared using an InfoNCE contrastive loss. This metric loss pulls together the transformations from the same sample (positive sample), while pushes all the other samples from the same batch (negative samples): LIn f oNCE =−log exp(sim(a,p)/τ) ∑K i=0exp(sim(a,ki)/τ)(A.1) Where the similarity metric sim(a,ki)used was the cosine distance. τstands for the temperature parameter. This is an instance classification task as the model only considers the transformations from the same sample as positive samples, while considers all the other samples as negative samples, even if these samples belong to the same class in the downstream task. For training the encoders, the first encoder is trained through the gradient propagation from the InfoNCE loss, while the second encoder is trained by applying momentum propagation of the weights from the first encoder. This momentum propagation is described on the following equation: 97
Figure A.1: MoCo architecture for contrastive self-supervised learning. The first block represents the pretext learning method, while the second block represents the downstream task. In the pretext task, the sample is augmented into two different branches (query and key), and these branches create their own feature representation of the sample. Then, the model compares both sample embeddings and tries to minimize their contrastive loss. The key branch stores the samples from previous iterations in order to use them as negative pairs for the contrastive loss comparison. θk←mθk+(1−m)θq(A.2) Where mstands for the momentum parameter, θqstands for the weights of the encoder from the query branch, and θkstands for the weights of the momentum encoder from the key branch. This momentum learning forces the second encoder to extract similar representations than previous iterations, keeping the consistency between the queue embeddings. A shuffle BN was applied on the key queue at each iteration to prevent any bias between batches. The MoCo architecture uses a ResNet-50 model trained from scratch, with a batch size of 64, a learning rate of 1·10−5, and an exponential gamma of 0.8755. The maximum number of epochs for the pretext task was set to 80, with checkpoints of the backbone saved every 20 epochs. The momentum was set to 0.999, and the temperature of the InfoNCE was set to 0.7. The downstream task was trained similarly to the previous model, employing a linear layer at the end of the first encoder, and evaluating the model with the cross-entropy loss. The other components of the training setup (optimizer, scheduler, GPUs, etc) were configurated as specified in Section 5.2.1..
A.2. Data Preparation As the pretext task could be more sensible to non-representative data, we decided to apply a more aggressive filtering step than the one proposed in Section 3.3. only for the pretext training. This technique could help the model to converge by avoiding cases that could not contain any representative information of the instances. In Figure A.2, we exhibit the number of samples discarded per identity. As performed in Figure 3.15, we also removed the identities AB, AE, AL, AO, AP, AQ, AR, AV, AX and AY. Similarly to Section 5.2.1., we selected the dataset size of 500 samples per identity for most of the ablation steps, while we selected a dataset size of 4000 samples per identity in the final results. (a) First Dataset (b) Second Dataset (c) Third Dataset Figure A.2: Filtering of the three datasets. A.3. Ablation Study The training consisted of three tests: a single data augmentation on the query branch (Section A.3.1.), an augmentation to each branch of the MoCo architecture (Section A.3.2.), and the application of all the possible augmentation in both branches (Section A.3.3.). The first tests were performed without performing any augmentation in the fine-tuning step (or downstream task) to see if the pre-trained model was capable of generalizing the geometry of the identities.
A.3.1. Single data augmentation An initial test was conducted by introducing a single augmentation to the query branch within MoCo’s architecture. In Figure A.3, we exhibits the training loss of the pretext and the validation loss and accuracy of the downstream tasks per data augmentation, while in Table A.1 we show the accuracy of the downstream task. The preprocessing procedure remained consistent with the one outlined in Chapter 3. However, the results depicted in Figure A.3 show that the pretext task was not sufficiently challenging for the model. Consequently, we endeavored to enhance the complexity of the task in subsequent iterations. Despite the efficacy of rotation transformations in promoting model geometry generalization in Section 5.2.5., its application to the pretext task did not yield improved generalization capabilities, as shown in Table A.1. (a) Pretext Task (b) Downstream Loss (c) Downstream Accuracy Figure A.3: Pretext and Downstream metrics after applying a data augmentation on the query branch.
Table A.1: Self-Supervised Test: Single Augmentation. sstands for scale, while std stands for standard deviation. Aug. Config. No Flip Flip Val Test Val Test Bright s=0.5 92.0% 71.0% 37.0% 29.0% Contrast s=0.3 92.0% 71.0% 36.0% 30.0% Noise std=0.3 91.0% 70.0% 35.0% 28.0% Translate 50% 92.0% 71.0% 37.0% 30.0% Rotate 180º92.0% 71.0% 37.0% 29.0% Crop 1 10-90% 92.0% 71.0% 36.0% 29.0% Crop 2 10-50% 91.0% 70.0% 36.0% 29.0% Crop 3 50-90% 92.0% 71.0% 36.0% 29.0% A.3.2. 1v1 Data Augmentations In this iteration, we performed a single data augmentation on each branch to compare the performance of two combined transformations. Figure A.4 shows the training loss of the pretext task per all the transformation combinations. As depicted in Figure A.4, neither of these combination of transformations was complicated enough for the model. Table A.2 compares the downstream accuracies of all the transformation combinations. As observed in the Table A.2 , neither of these transformations was significant, which suggests that the pretext is not learning any useful representation of the data. Table A.2: Self-Supervised Test: 1vs1 Augmentation Query Key Noise Translate Rotate Crop 1 Crop 2 No Flip Val Noise - 92.0% 76.0% 92.0% 92.0% Translate 92.0% - 92.0% 91.0% 62.0% Rotate 91.0% 92.0% - 91.0% 91.0% Crop 1 92.0% 92.0% 91.0% - 91.0% Crop 2 91.0% 91.0% 91.0% 91.0% - Test Noise - 71.0% 60.0% 71.0% 70.0% Translate 71.0% - 71.0% 70.0% 49.0% Rotate 71.0% 72.0% - 71.0% 70.0% Crop 1 71.0% 72.0% 70.0% - 70.0% Crop 2 70.0% 70.0% 71.0% 71.0% - Flip Val Noise - 37.0% 37.0% 36.0% 38.0% Translate 36.0% - 37.0% 36.0% 29.0% Rotate 37.0% 36.0% - 35.0% 36.0% Crop 1 38.0% 36.0% 36.0% - 37.0% Crop 2 35.0% 37.0% 36.0% 36.0% - Test Noise - 30.0% 30.0% 30.0% 31.0% Translate 28.0% - 29.0% 28.0% 30.0% Rotate 29.0% 29.0% - 29.0% 30.0% Crop 1 31.0% 30.0% 28.0% - 29.0% Crop 2 28.0% 30.0% 29.0% 29.0% -