scieee AI-readable full text Open interactive document viewer

Deep learning based computer vision for aerial-view street object detection and classification

Coll Josifov, Richard

Abstract

This project consists of the training of a convolutional neural network based on the YOLO approach for the systematic detection and classification of objects in a street as seen from a drone flying over them, to then be used for an algorithm to predict these objects’ paths and consider possible accidents between them. In the first part, a graphic user interface for dataset creation and validation has been created, with the goal of allowing the creation and validation of other datasets in order to have a custom-made dataset for the goal. The dataset based on is the VisDrone dataset, which consists only of drone-view imagery of streets. After this, using the Darknet framework, several YOLO and tiny-YOLO models have been trained through Google Colab cloud computing services, and then all these have been tested in front of other data and compared to other pre-existing models in the field. Finally, the outputs of the YOLO network is then used in an algorithm to predict possible accidents on streets. This is based on logic-based algorithms for object tracking, linear regression for path prediction, and solver of linear system of equations for the detection of possible collisions, followed by filtering of these. Overall, a YOLO model with a mean average precision of 75% on the development set and 62% on the test set has been trained, and preliminary positive results have come from the accident prediction algorithm

Full text

Deep learning based computer vision for aerial-view street object detection and classification Document: Report Author: Richard Coll Josifov Director/Co-director: David Lavèrnia-Ferrer/ Albert Masip-Álvarez Degree: Bachelor in Industrial Electronics and Automatic Control Engineering Examination session: Spring, 2022 BACHELOR FINAL THESIS Acknowledgement I would like to express my sincere gratitude to: •My professors David and Albert for all their help throughout the project. •My family and friends for all their support throughout the degree and during this last stage. Resum Aquest projecte consisteix en l’entrenament d’una xarxa neuronal convolucional basada en l’arquitectura You Only Look Once (YOLO) per a la detecció sistemàtica i classificació d’objectes en un carrer vist des d’un drone sobrevolant-ho, per ser després utilitzat per un algoritme per tal de predir les trajectòries i considerar possibles accidents entre els objectes. En la primera part, una interfície gràfica d’usuari per a la generació i validació de datasets ha sigut creada, amb l’objectiu de permetre la creació i validació d’altres dataset per tal de tenir un dataset personalitzat per a l’objectiu. El dataset estarà basat en el dataset VisDrone, que consisteix només d’imatges preses des de drones de carrers. Seguidament, usant el marc Darknet, diversos models YOLO i tiny-YOLO han sigut entrenats a través dels serveis de computació en núvol Google Colab, i després tots aquests models han sigut testejats davant d’altres dades i comparats amb models previs preexistents en l’àmbit. Finalment, els resultats dels models de les xarxes YOLO és usat en un algoritme per preveure possibles accidents al carrer. Es basa en un algoritme basat en lògica per a seguiment d’objectes, una regressió lineal per a la predicció de trajectòries i un solucionador de sistemes d’equacions lineals per a la detecció de possibles col·lisions entre objectes, tots seguits de filtres per reduir falses prediccions. En conjunt, un model YOLO amb una precisió del 75% en el conjunt de desenvolupament, i un 62% en el conjunt de test ha sigut entrenat, amb resultats preliminars positius provinents de l’algoritme de predicció d’accidents. Paraules clau: visió per computador; detecció i classificació d’objectes; aprenentatge profund; xarxa neuronal convolucional; YOLO; darknet; predicció d’accidents; interfície gràfica d’usuari; generació de datasets Abstract This project consists of the training of a convolutional neural network based on the YOLO approach for the systematic detection and classification of objects in a street as seen from a drone flying over them, to then be used for an algorithm to predict these objects’ paths and consider possible accidents between them. In the first part, a graphic user interface for dataset creation and validation has been created, with the goal of allowing the creation and validation of other datasets in order to have a custom-made dataset for the goal. The dataset based on is the VisDrone dataset, which consists only of drone-view imagery of streets. After this, using the Darknet framework, several YOLO and tiny-YOLO models have been trained through Google Colab cloud computing services, and then all these have been tested in front of other data and compared to other pre-existing models in the field. Finally, the outputs of the YOLO network is then used in an algorithm to predict possible accidents on streets. This is based on logic-based algorithms for object tracking, linear regression for path prediction, and solver of linear system of equations for the detection of possible collisions, followed by filtering of these. Overall, a YOLO model with a mean average precision of 75% on the development set and 62% on the test set has been trained, and preliminary positive results have come from the accident prediction algorithm. Keywords: computer vision; object detection and classification; deep learning; convolutional neural network; YOLO; darknet; accident prediction; graphic user interface; dataset generation Contents List of Figures List of Tables List of Algorithms 1 Introduction 1 1.1 Object........................................ 1 1.2 Scope ........................................ 2 1.3 Requirements.................................... 2 1.4 Justification..................................... 3 1.5 Schedule....................................... 3 2 Background and State of the Art 5 2.1 Image Processing and Computer Vision . . . . . . . . . . . . . . . . . . . . . 5 2.1.1 RBGandYCbCr.............................. 5 2.1.2 ImageFiltering............................... 6 2.2 DeepLearning ................................... 9 2.3 Object Detection and Classification . . . . . . . . . . . . . . . . . . . . . . . . 12 2.4 YouOnlyLookOnce................................ 15 2.5 Object Detection and Classification Metrics . . . . . . . . . . . . . . . . . . . 18 3 Graphical User Interface for dataset generation 20 3.1 GUIinMatlab ................................... 20 3.2 DevelopedGUI................................... 21 3.2.1 Automatic object detection . . . . . . . . . . . . . . . . . . . . . . . . 21 3.2.2 Manual object detection . . . . . . . . . . . . . . . . . . . . . . . . . . 25 3.2.3 Appearence................................. 26 3.2.4 Annotations generation . . . . . . . . . . . . . . . . . . . . . . . . . . 28 3.2.5 Dataset validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 3.3 TestingofGUI ................................... 33 3.3.1 Test of GUI for dataset generation . . . . . . . . . . . . . . . . . . . . 33 3.3.2 Test of GUI for dataset validation . . . . . . . . . . . . . . . . . . . . 34 4 Dataset generation 35 4.1 Datasetvalidation ................................. 35 4.2 Datasetsplit .................................... 37 4.3 Dataset model adaptation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 5 Neural network training 43 5.1 DarknetandYOLO ................................ 43 5.2 Previous models testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 5.3 Training....................................... 50 5.3.1 Cloudcomputing.............................. 50 5.3.2 Google Colab configuration . . . . . . . . . . . . . . . . . . . . . . . . 51 5.3.3 Cloudtraining ............................... 53 5.4 Validation...................................... 57 6 Models comparisons 59 6.1 Datasetscomparison................................ 59 6.2 Imagesize...................................... 62 6.3 Contrast....................................... 63 6.4 Dataset view orientation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 7 Street footage detection 69 7.1 Transit cameras footage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 7.2 Dronefootage.................................... 71 8 Application area: accident prediction 75 8.1 Object tracking and path prediction . . . . . . . . . . . . . . . . . . . . . . . 76 8.2 Collisionprediction................................. 77 9 Results 83 9.1 Model performance on test set . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 9.2 Environmental, economic and social impact . . . . . . . . . . . . . . . . . . . 85 10 Conclusions 88 10.1Conclusions..................................... 88 10.2 Possible application areas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 10.3Futureresearch................................... 91 Bibliography 96 Appendices 96 A Graphic User Interface Code 97 B Video selection 109 C Dataset generation 111 D Datasets comparison 117 E Collision prediction 119 List of Figures 1 Ganttchart..................................... 4 2 Example image and kernel. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 3 Convolution. .................................... 8 4 Singleneuron..................................... 10 5 Simpleneuralnetwork................................ 11 6 Convolutional neural network architecture.Source . . . . . . . . . . . . . . . . 13 7 YOLO grid and predictions.Source . . . . . . . . . . . . . . . . . . . . . . . . 16 8 YOLO architecture.Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 9 YOLOv3 architecture.Source . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 10 ButtonsGUI..................................... 25 11 AppearanceoftheGUI. .............................. 26 12 Configurationwindow................................ 27 13 GUI processing a frame. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 14 GUIproceeding. .................................. 33 15 GUI validating a frame. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 16 GUIframeannotation................................ 34 17 GUI for testing, showing a frame with a mistake at the bottom center of it. . 35 18 MovedROIerror................................... 36 19 Graph of change in dataset after validation. . . . . . . . . . . . . . . . . . . . 37 20 Results of YOLO network evaluation over test set. . . . . . . . . . . . . . . . 47 21 Outputwhiletraining................................ 54 22 Graphaverageloss.................................. 54 23 Graph of evolution of mAP of the yolov4 models. . . . . . . . . . . . . . . . . 58 24 SampleSDDframe.................................. 60 25 Sample VisDrone frame. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 26 OutputRosetmodel5................................ 60 27 Output trained yolov4 480. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 28 OutputRosetmodel5................................ 61 29 Output trained yolov4 480. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 30 OutputRosetmodel5................................ 61 31 Output trained yolov4 480. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 32 Results of YOLOv4 model 6 in original images. . . . . . . . . . . . . . . . . . 62 33 Results of YOLOv4 model 6 in 480x480 images. . . . . . . . . . . . . . . . . . 62 34 Results of YOLOv4 model 6 in 320x320 images. . . . . . . . . . . . . . . . . . 62 35 Results of YOLOv4 model 6 in framed images. . . . . . . . . . . . . . . . . . 62 36 Colour histograms from SDD samples. . . . . . . . . . . . . . . . . . . . . . . 63 37 Overall colour histogram sample SDD. . . . . . . . . . . . . . . . . . . . . . . 64 38 Overall colour histogram sample VisDrone. . . . . . . . . . . . . . . . . . . . 64 39 Change in performance trained model. . . . . . . . . . . . . . . . . . . . . . . 65 40 Change in performance Roset model 5. . . . . . . . . . . . . . . . . . . . . . . 65 41 Change in performance Roset model 5 in SDD. . . . . . . . . . . . . . . . . . 66 42 Change in performance in relation to the amount of images. . . . . . . . . . . 68 43 Examples from Barcelona camera traffic.Source . . . . . . . . . . . . . . . . . 69 44 Case with accurate detections. . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 45 Cases accurate detection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 46 Cases with few detections (left) or none (right). . . . . . . . . . . . . . . . . . 71 47 Sample from Tello drone. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 48 SamplefromDJIdrone. .............................. 71 49 Frameswithbicycle. ................................ 72 50 FrameresultDJIdrone. .............................. 73 51 Frameswithperson. ................................ 73 52 Frames with multiple people. . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 53 Frame from VisDrone dataset. . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 54 Outputzenithalview. ............................... 74 55 GUI for collision predictions. . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 56 GUI with a collision predicted. . . . . . . . . . . . . . . . . . . . . . . . . . . 80 57 GUI with a collision predicted. . . . . . . . . . . . . . . . . . . . . . . . . . . 81 58 Histogram computing time collision prediction. . . . . . . . . . . . . . . . . . 81 1.5. Schedule 4 After this initial planning of tasks, during the course of the project, newer tasks and different lengths of the tasks happened, and all of these can be seen in Figure 1, where the green tasks are new tasks that were not considered in the planning phase but ended up being necessary or interesting approaches, as well as in blue being the original planning and yellow the real time of the at first considered tasks. Figure 1: Gantt chart Chapter 2 Background and State of the Art 2.1 Image Processing and Computer Vision Due to the nature of this project, it is important to first revise the basic concepts in the field of image processing (which will be useful for the generation of the dataset) as well as traditional and modern computer vision techniques. 2.1.1 RBG and YCbCr Computers are digital machines and as such, images treated through these must either be digital in nature or digitized. Currently, most cameras available are digital as well. That means that an image is characterized by a discrete amount of information. What this means is that each image is subdivided into discrete regions, which are called pixels, each described by a discrete value [24]. These values can represent different things depending on the convention being used, but will usually represent the intensity of a certain colour. The two main colour spaces of interest to us are the RGB and YCbCr formats[45]. In RGB format, each image is represented as a set of 3 matrices of dimensions NxM, where N and M represent the amount of pixels in the y and x axis respectively. Each pixel is a combination of red, green and blue (RGB). And each of the three matrices represents one of the three colours in the said order. So every pixel in the image i,j is a combination of the values of the matrices in positions i,j. The values of the matrix range from 0 to 255, where the number indicates the brightness of that colour in that particular pixel, with 255 being the maximum brightness and 0 representing the absence of that colour in that pixel. So in the RGB format, each image J is represented as a dimensional matrix of dimensions NxMx3 and 5 2.1. Image Processing and Computer Vision 6 where all J(i, j, k)∈[0,255] ∀i, j, k | {0≤i≤N−1; 0 ≤j≤M−1; 0 ≤k≤3}. In the YCbCr format, the dimensions of the matrices are the same, but the values represent different but related characteristics. The first component, Y, is the luminance. This is computed as a weighted sum between the red, green and blue layers, with about half the weight to green (as the human eye is much more sensible to green colours) and the rest divided between blue and red. The second component, Cb, is the blue component computed as the difference between the blue layer in RGB and the Y layer from YCbCr. Finally, the Cr layer is the difference between the red layer and the luminance. The YCbCr format is directly convertible from the RGB format through a simple linear matrix operation. 2.1.2 Image Filtering Given that digital images are simply represented as matrices, any sort of linear and nonlinear operation can be performed on them. Some of these operations are useful as they deform an image in ways that are of interest. Point Operations First and foremost, there are what are called point operations, which are simply going point by point in the matrix and realizing an operation: g(i, j) = f(h(i, j)). The function f(x) can be anything from a simple linear operation to any sort of nonlinear operation. Binarization A subtype of point operation where for each pixel the resulting one is either white or black (which is usually represented as 1 and 0 respectively, instead of 255 and 0 that would be thought of in RGB), depending upon it being above or below a threshold(th) respectively, with f(x) having the following form: f(x) =      1 if x≥th 0 if x < th Colour histogram based transformation For any image a colour histogram can be made, in which on the x axis the possible values are displayed (in RGB would be from 0 to 255) and on the y axis are the repetitions. This can be useful to see if an image has the full spectrum of colours and intensities or not. And based from this histogram, linear transformations can be applied to, for example, either expand the histogram to cover all possible values or bound it to a set region of values. In these cases, the 2.1. Image Processing and Computer Vision 7 operation to be done would be the following: f(x) = offset +highest −offset max −min (x−min) Where the offset will be the lowest value wanted in the resulting image’s histogram (for example, 0 if all the range is wanted). The highest will be the highest value wanted, and the max and min will be the highest and lowest values of intensity in the original image. Filtering and Convolution Filtering and convolution consist on passing a mask (also called kernel) on the image and computing for each pixel the result. The mask is a matrix of any size wanted, usually filled with binary values 0 or 1 but can be filled with other values, and for each pixel the superposition of the kernel with the image is computed by multiplying each overlapping value of the matrices, and summing up the result. Considering the original image to be f(x, y), a kernel (which is a matrix with values with dimensions bxa), to be ω, and the resulting image to be g(x, y), the following expression holds: g(x, y) = a X i=−a b X j=−b ω(i, j)f(x−i, y −j)(2.1) To show a simple example, consider an image as represented by a single 4x4 matrix, and a decided upon kernel of 3x3 as shown in Figure 2. Figure 2: Example image and kernel. Then, to compute the convolution the following would be done: the kernel is centred around a pixel, then for each overlapping element of the kernel matrix with the image matrix, the elements are multiplied and summed, and the result is the value of the centre pixel of the overlapping on the output image, as can be seen being performed in Figure 3. Dilatation and Erosion Dilatation and erosion are very similar to convolution, but the difference is that the output, 2.1. Image Processing and Computer Vision 8 Figure 3: Convolution. instead of being the sum of the interposition of the mask and the image is rather the highest value of this element-wise multiplication, in the case of dilatation, or the lowest value in the case of the erosion. 2.2. Deep Learning 9 2.2 Deep Learning The techniques described so far are very useful in many applications, and will be used throughout this project, but they are not enough for what the goal of this project is: object detection and classification. Nowadays, the most used technique and the one with the highest performance rates is deep learning[21]. Deep learning stems from Machine Learning, which is a field that tries to program machines in order for them to be able to do tasks usually performed by humans. And to do so these systems are fed up with data and with that they should be able to perform the task. The advantage of deep learning in front of traditional machine learning is in what is called "representation learning". Representation learning is about the learning, out of all the possible features of the data (for example in an image, brightness, colour, contrast, shapes...), of the most useful ones for the given task[2]. And deep learning is a set of representation learning methods with several layers, allowing it to represent complex functions that can highlight important regards of the data. These layers that extract the features are not programmed by a human but are learned by the computer, which is what makes these techniques so powerful. Deep learning is centred around these layers that allow it to learn the representations from the data. The layers are made up of a basic structure which is called a neuron. It is nothing more than a singular function unit that has one or more inputs and produces one output as a nonlinear combination of these. It has to be a nonlinear function because if it were linear, it would be restricted in its capacity of performing as a simple change in position of an object would cause a change in the output of the function (which should not occur)[8]. In Figure 4 you may see the usual representation of a neuron (as it is inspired by biological neurons it is drawn this way, although it is just a mathematical function). On the left-hand side, you can see x1, x2..., xnwhich represent the inputs to the neuron. Each of these inputs has an associated "weight", which is the value that is multiplied to that input (for example, some inputs may be more relevant than others, in which case the weights associated to this would be higher). Then a summation of the weighted inputs is done, with an additional element called bias (which is just a singular scalar parameter for each neuron), and finally the output is the result of, usually, doing a nonlinear operation to this summation (although a linear operation is sometimes also performed). The most common nonlinear operations performed are rectified linear unit, sigmoid and the step functions. These are a set of nonlinear function that, in the case of the sigmoid and the 2.2. Deep Learning 10 Figure 4: Single neuron. step function, are bounded in the range [0,1], and the ReLU function is f(x) = max(0,x). Out of these single neurons, layers are built. A layer is a group of these that all have the same inputs and output to the same neurons, and are not connected among them, as can be seen in Figure 5. On the left, the input layer, represents the neurons that would be the input data (which, in our case, would be an image described in RGB pixel by pixel). On the right-hand side, the output layer is the neuron or neurons whose output is directly the output of the network (in our case, these would be the predictions of where objects are located and what class of objects they are). All the layers in between the input layer and the output layer are called hidden layers, as neither their input nor output are known to us. In addition to this, in the shown example the hidden layers are also what is known as fully-connected layers, as each neuron of every layer is connected to every preceding neuron of the previous layer as well as it is connected to every neuron of the next layer (through inputs and outputs respectively), but is not connected to any of the other neurons of the same layer. The represented structure is just an example, as there can be many more neurons per layer, as well as many more hidden layers. The dimensions of the input and output layer are set by the problem at hand, as the input data has a certain size given by the data (in images, it will be the width times the height in pixels times 3 for the three colour layers) and the output will also have the size corresponding to what the network is expected to predict. Regarding the network and layers architecture, it is part of what is called hyperparameters, which are different settings of a network which cannot be optimized mathematically but rather have to be set up by the programmer. In order then to test which network configuration is better, the dataset is usually split into two parts, one which is called train set that is used to optimize the weights and parameters of the network and another called test set which is the 2.2. Deep Learning 11 Figure 5: Simple neural network. one used to compare different configurations, as the precision of each is compared in front of this new data. At first, once an architecture is decided upon, all the weights and bias have to be selected. In order to do so, a process called "gradient descent" is used. It consists upon giving the network the data to be trained on, computing the output of the network in each case and comparing that to the real results. It is a calculation of the error of the network for each data point. With that error, a gradient of it (the derivative) is computed for each weight (either analytically or numerically), and that indicates in which direction, either increasing or decreasing, each particular weight has to be changed. Once that change occurs, again the output and error of the network is computed and the weights are again updated. This process is called backpropagation, as it goes from the output back layer by layer, updating the weights by the computation of the gradient. 2.3. Object Detection and Classification 12 2.3 Object Detection and Classification With deep learning, great advances have been made in the field of object detection and classification, with several network architectures being used for this particular area. The main goal of the project is that of the programming of an algorithm capable of, in real-time, detect objects from an image and then classify these objects into a predefined set of classes. To do so, there would be several architectures which could suffice. All of these, though, are base upon a particular configuration: Convolutional Neural Networks (CNN)[41]. This is due to the fact that above-mentioned neural networks struggle with the high computational complexity of dealing with image data, as the first hidden layer will need to have width times height times three weights to compute (these become large numbers say for an image of 480x480 pixels, as all in all it would need to compute 480x480x3=691.200 weights just for one neuron of the first hidden layer). This could also have negative impacts, as it could easily lead to overfitting, which means that the model’s parameters would be too much adjusted to the train data and would lead to bad results in front of other data. All of these problems can be solved through convolutional neural networks[30]. Their basic architecture is based around three types of layers: convolutional layers, pooling layers and fully-connected layers. Convolutional layer The input layer will be the image, which will then be processed by the convolutional layer. These layers perform a convolution to the image. And what each neuron will learn will be the size and shape of the kernels to be used on the image. This ends up meaning that some neurons will specialize in detecting certain shapes and will be activated when these appear in the image. Pooling layer The pooling layer serves as a way to reduce the dimensionality of the data and thus reduce the amount of weights and neurons necessary for the network to work properly. It is a non-linear function, and the most commonly used one is max pooling. It consists of taking the input matrix and dividing it into smaller matrices, and of each one choosing as the output the highest value. The most common one used are with kernels of dimensions 2x2 and a stride of 2. These means that the matrix is subdivided into regions of 2x2 (and each element only belongs to one subdivision), and for each of these 2x2 squares the highest value is chosen as the output. Thus, the overall size of the matrix is reduced to just 25% of the original size (as 2.3. Object Detection and Classification 13 out of every 4 elements, only one remains). Fully-connected layer The fully-connected layer works in the same manner as in other deep learning architectures, by having neurons completely connected to preceding layers. Taken all together, the overall architecture looks like that in Figure 6. As it can be seen, the first part shows the image, which is firstly processed through a convolution layer followed by a pooling layer. After this, the pre-processed image then goes through the fully-connected layers. The example represents a simple case where the network is set to evaluate what number from 0 to 9 the image is showing. Figure 6: Convolutional neural network architecture.Source All that said, there are multiple possible configurations of convolutional neural networks, depending on the amount of networks used, what the network does, how many layers there are, the depth of the layers and what type of layers there are. There are two main approaches [4], the ones based around one-stage detection and the ones based on two-stage detection. Two-stage detection As the basic task of these algorithms is that of object detection and classification, in the two-stage detection algorithms these two tasks, detection and classification, are separated. So there will be a first stage, either based in image processing or deep learning, that proposes regions where objects might be located, and then these proposals are sent to a second deep learning network which classifies the objects. These are slow to train and to run, but have high accuracy. The main approaches are based around Region - Convolutional Neural Network Chapter 3 Graphical User Interface for dataset generation One of the main problems identified by previous studies [5] is that available open source datasets have a high amount of misclassified data. For this reason, it was believed that the best way to move forward was through the creation of a dataset upon which the convolutional neural network would be able to learn. To facilitate the generation of this (which must amount to around 10,000 classified images) a graphic user interface was proposed and created. A graphical user interface(GUI) is an interface that allows a user to interact with a program in certain predefined ways. For our purposes, the GUI will be a screen that will show the current image and the automatic predictions made of the objects, as well as containing a set of buttons to allow the user to add more regions of interest, and buttons to go forward or backward one image as well as a configuration panel to change some values that will affect the performance of the automatic detection. 3.1 GUI in Matlab The selected programming environment has been Matlab, due to it being the language most used by the research group and by the previous study this thesis is based upon. Matlab is a programming language and programming environment that has an environment, called "App Designer" for the creation of graphic user interfaces, which is what has been used in this project. In the YOLO framework, each frame of a video is represented as a .txt file with the following structure: < class >< xcenter >< ycenter >< width >< height > where class: number 20 3.2. Developed GUI 21 representing the class of object x centre: defined as the x coordinate divided by The goal of the GUI is that of automating part of this process as well as enabling a fast way to generate these files. 3.2 Developed GUI The idea behind the developed GUI has been that of firstly an automatic motion detection that will sweep through the image suggesting possible objects and allowing the user to either eliminate these or classify them by pressing a number on the keyboard, and once the automatic phase has finished, allow the user to input more regions in the image. 3.2.1 Automatic object detection The automatic detection works by subtracting from the current image a frame n samples before. But to do so, as the image is given as an RGB, it is first transformed to YCbCr, and then each of these two images is smoothed through a median filter (which is filtering with a kernel of size nxn and values of 1/n). For the automatic object detection, a simple algorithm has been used. Given the high availability of images, the program works by generating a new image doing the following operation (through the Y, light intensity layer): ˆpi,j(k) = pi,j(k)−pi,j(k−n)(3.1) where: ˆpi,j(k)= pixel i,j of the new image at instant k pi,j(k)= pixel i,j of the original image at instant k n= constant representing the offset, which can be modified In this way, we get a new image that is the direct result of subtracting from the current image an n frames image before. By this means, having a static camera wields a result of mostly moving objects (as well as noise due to change in lighting as well as possible camera movements) due to the background not changing positions. The image is then firstly binarized (above a certain threshold) to remove the negative results from the subtraction process. The selection of the threshold upon which to binarize is a value that has been tuned through trial and error, until it has been found that at a value of 0.1 it is when the best results for the automatic detection are achieved (although depending on the scenery it could be changed to improve detection). After that it is filtered (to remove background noise always present 3.2. Developed GUI 22 in digital images), by applying an erosion followed by dilatation. It is then dilated again to reduce the possibility of the same object being detected twice, as some objects will end up getting divided into multiple regions. And then the same average filter as before is also applied to remove more noise. The pseudocode of the image processing algorithm that describes the procedure is the following: Algorithm 1 Image Processing Ik−n←RGBY CbCr ∗image(k−n) Ik−n←correlation(Ik−n,′average′) Ik←RGBY CbCr ∗image(k) Ik←correlation(Ik,′average′) G←Ik−Ik−n for i, j < size do if G(i, j)<0.1then G(i, j) = 0 else G(i, j)=1 end if end for With all of this, a black and white image has been generated, with the white regions indicating that a moving object is found there. Now, it is necessary to go one by one through each of these aggregations of white pixels in order to ask the user to label (or disregard) these regions of interest. This is done by going pixel by pixel and testing whether it is a 1 (white) or a 0 (black). When a white pixel is found, the system automatically tries to find the edges of the region, by moving in the x direction and y direction until there are no longer white pixels, thus delimiting a rectangle that contains the white region. All the pixels within that rectangle are annotated in a memory vector so that the system may continue the pixel by pixel search without repeating the same white region twice. 3.2. Developed GUI 23 Taken all together, the pseudocode of the program is the following, with the first algorithm being the function to delimit a region of interest and the second algorithm being the combination of all the functions (you may find the Matlab programmed solution in the appendix): Algorithm 2 Region Delimitation while notDelimitedX do if G(:, jn+1) == 0 then x=jn+1 notDelimitedX = False else n = n + 1 end if end while while notDelimitedY do if G(in+1,:) == 0 then y=in+1 notDelimitedY = False else n = n + 1 end if end while Algorithm 3 Automatic Detection G←ImageProcessing() for i= 1..lengthX do for j= 1..lengthY do if Mem(i, j)= 1 then if G(i, j) = 1 then RegionDelimitation(G,i,j) end if end if end for end for Originally, the planned algorithm tried to be more efficient by reducing part of the region to look up to after detecting an object, but due to how it was programmed it ended up missing objects when they are placed closely together (as it worked by skipping the columns where the object has been found). Given that the algorithm stops to ask the user if there is a ROI, and that the computational costs are low due to the relatively small size of the matrices being dealt with, this version, although much more computationally costly, avoids missing out on any object, which is why it has been the implemented version. In Matlab, there is a data type which is a ROI, that is very useful for generating, modifying and storing information about regions of interest. For this particular application, out of several shapes possible, a rectangular one will be used. To create one, the following function has to be called: 3.2. Developed GUI 24 1images.roi.Rectangle('Parent', app.UIAxes,'Position',[x,y,w,h],... 2'EdgeColor','g','LineWidth',app.lineWidth,'UserData','n'); With images.roi.Rectangle the ROI is created, and the parameters refer to several regards relevant. Firstly, the ’Parent’ is the parameter to indicate in which image of the GUI to add the ROI. Secondly, the position described by x,y,w,h refers to the x and y positions of the upper left corner of the ROI as well as the width, w and the height, h. The EdgeColor and the LineWidth are simply aesthetic regards, to ease the differentiation of classes of ROI, and the UserData is used as a way to store the index, n, of the class being added. For every region of interest that is added, it is stored into a Matlab structure array. As stated in the Matlab Help Center, "A structure array is a data type that groups related data using data containers called fields. Each field can contain any type of data. Access data in a field using dot notation of the form structName.fieldName."1. This allows for a very flexible way to store the multiple regions of interest. In the structure array, which is defined as a global variable and accessible through app.roi 2, a field called roi has been generated where each new ROI can be stored, and through the following command every new one can be appended at the end of the structure array: 1app.roi(length(app.roi)+1).roi = images.roi.Rectangle(...) After every image, the latest index of the structure array is saved up in another variable to start accessing the data from there (as deleting the previous data of the structure array ended up causing problems with the basic data structure and was thus dismissed as an option). When trying to access any of the regions of interest saved up, it has to be done through a try catch function, which is just a function that tries to execute a code and if it encounters an error executes another code. This is due to the fact that, for the user to be able to delete a ROI, it has to be done manually through the screen by right-clicking over it and then selecting delete, and thus some of the previously added regions might no longer exist once the program tries to access them to save them up. 1https://www.mathworks.com/help/matlab/ref/struct.html 2To access global variables the syntax is app.globalVariableName 3.2. Developed GUI 25 3.2.2 Manual object detection The manual object detection will be allowed after the program has shown all the computed possible regions of interest, and consists of a set of buttons, as seen in Figure 10, that will allow the user to select the class of the object to add. Figure 10: Buttons GUI. Once any of these have been pressed, they generate a function callback, which is a call to a predetermined function. This function will just do one thing, add a ROI to the image as well as saving it up. For each category of object there is a different function, with just a colour change as well as the UserData to match the numbering of the classes. The following code is the callback function of the Add Pedestrian button: 1% Button pushed function: AddPedestrianButton 2function AddPedestrianButtonPushed(app, event) 3app.roi(length(app.roi)+1).roi = images.roi.Rectangle(...); 4end 3.2. Developed GUI 26 3.2.3 Appearence The overall appearance of the GUI is as seen in Figure 11. In the top right corner there is a "Start" button that must be pressed when beginning the execution of the GUI as it calls several configuration functions. Below it are the buttons commented previously that allow the user to add regions of interest. On the bottom right there is the "Next Image" button, which will generate the annotations for the current image and proceed to show the next image. There is also on the left-hand side a "Previous Image" button that allows the user to return back to an image (but when this is done, the previous annotations of that previous image will be deleted and new ones generated). The big blank space below "Image" is where the image will be shown, and below "Processed Image" the black and white processed image (after having gone through Algorithm 1) will be shown. Figure 11: Appearance of the GUI. In addition to these, when pressing over the UPC logo in the top left corner, a configuration windows, as seen in Figure 12, is opened that allows for some changes relating to the operation mainly of implementation of Algorithm 1 as well as some other generic issues. The "Nºof images offset" allows changing with which image the algorithm compares the current one. If set to 1 for example, the processing (mainly the subtraction of the current image from the previous one) will compare the current image with the previous one, but if set to 2 it would compare it to the picture before the previous one. This is useful to be changed 3.2. Developed GUI 27 Figure 12: Configuration window. in cases where the frames per second are very high and there might be little change between the current and preceding image. The "Margin" refers to a margin that has been added to the delimited region (as found by the implementation of Algorithm 2) to increase the overall overlapping area between the ROI and the real object, and it is set in pixels. It is an increase in both the x and y directions, and in both sides of the rectangle. The "Nºof erosions" refers to the erosions performed in the processing algorithm after having binarized the image resulting of the subtraction of the current with k preceding one. This is useful to be increased when there might be a lot of noise that the algorithm will confuse with regions of interest. In the same way, the "Nºof dilatations" refers to the amount of dilatations performed after the erosions. It’s useful to be increased when with all the image processing the overall region that corresponds to a real object is small. On the bottom part, the "Save on close" relates to whether, when pressing the close tab of the window the user wants the last image to be saved up or not. And the "Moving camera" one relates to a yet not fully developed modification of the algorithms that would allow the GUI to work better in a condition of the camera being non-static. Below these, an "Apply" button is present which must be pressed to store the values. The modifications of the configuration must be done before pressing the "Start" button in the main window, as that is the only case where the modifications would be looked at. 3.2. Developed GUI 28 3.2.4 Annotations generation Once all the regions of interest have been marked for a particular image, either through the automatic or manual object detection, these have to be saved up in a .txt file to match the formatting of the YOLO network. The annotation generation occurs as a callback function to either when the "Next Image" button is pushed or when the close tab is pressed and the "Save on close" configuration is selected. 1%Function for saving and exiting 2function [] = saveExit(app) 3% Create the annotation file for the current frame 4fileID = fopen(img+app.currentImage+.txt,'w'); 5%Saves up the ROIs of the image 6for i=app.offROI:length(app.roi) 7try 8%Get the class number of the ROI 9s=append(app.roi(i).roi.UserData,' '); 10 % Transform x position to YOLO format 11 s=append(s,mat2str((app.roi(i).roi.Position(1)+... 12 (app.roi(i).roi.Position(3)/2))/app.imageWidth),' '); 13 % Transform y position to YOLO format 14 s=append(s,mat2str((app.roi(i).roi.Position(2)+... 15 (app.roi(i).roi.Position(4)/2))/app.imageHeight),' '); 16 % Transform width to YOLO format 17 s=append(s,mat2str(app.roi(i).roi.Position(3)/app.imageWidth),' '); 18 % Transform height to YOLO format 19 s=append(s,mat2str(app.roi(i).roi.Position(4)/app.imageHeight)); 20 % Write the values to the file 21 fprintf(fileID,'%s',s); 22 % Change line in the file 23 fprintf(fileID,'\n'); 24 catch end 25 end 26 % Update the offROI to the last position of ROIs +1 3.2. Developed GUI 29 27 app.offROI = length(app.roi)+1; 28 % Close annotation file 29 fclose(fileID); 30 % Change last frame in the lastFrame .txt file, to be used next time 31 %the app is opened 32 fileID = fopen(lastFrame.txt,'w'); 33 fprintf(fileID,'%u',app.currentImage); 34 fclose(fileID); 35 end 3.2.5 Dataset validation To begin faster the training process, as the awaiting of a response of the permits for video recording took long, instead of creating an entirely new dataset it was decided to validate an open dataset. The dataset would need to have both zenital and angled views of streets. The VisDrone [48] dataset just happened to fulfil these criteria. But, as is acknowledged in the dataset’s FAQ page of their webpage: "We are aware of some deficiencies in the provided annotations and are still trying to improve these." 3. Thus, instead of using it blindly, or generating all the annotations from scratch using the GUI, some modifications were made to the app so that it could show how the current annotations were, allow for the modification, addition and subtraction of ROI, and the generation of a new validated annotation in the corresponding YOLO format. The VisDrone dataset used, out of the different ones, was the "Multi-Object Tracking", as it corresponded to street-views with multiple objects which are for the majority of cases classified in the annotations. The dataset is distributed in groups of between 200-600 frames, each group being a different scenario or video. For each of these groups, there is a unique .txt file with the corresponding annotations. These annotations are written down in the following format: <frame_index>, <target_id>,<bbox_left>,<bbox_top>,<bbox_width>,<bbox_height>,<score>, <object_category>,<truncation>,<occlusion> Out of all of these, not all are necessary to us. The relevant ones are: <frame_index>: number of frame within the group 3http://aiskyeye.com/faq/ 4.1. Dataset validation 36 Figure 18: Moved ROI error. This is why, one by one, all the images were validated through the GUI created before to this effect. Given that the cadence of the dataset is of 24fps, it was decided to have enough frames to generate around 7 minutes of a video. Thus 7min∗60s/min∗24frames/s = 10080frames are needed for the training. The VisDrone dataset is divided into 32 categories, the training set, the validation set and the test set. The training set contains 23654 frames, so to decide which to take for the training it was divided approximately into 60% of randomly selected frames plus the remaining 40% were selected taking into account the sort of object that appeared, the position of the drone camera as well as other relevant aspects such as it being a high contrast scenery, or a zenithal view, or night view. All of this was done in order to increase the spectrum of data so that the model can perform with high accuracy in a variety of scenarios and environmental conditions. After this validation, a simple Matlab script was written in order to evaluate which impact has been made in the dataset, by analysing the percentage of changes made from the original dataset. After having validated the 10.000 images needed (although later on, an additional 1.500 extra frames for training were added, validating them as well), an analysis was conducted upon the percentage change done to the dataset. In Figure 19 the results of the analysis are shown. One of the lower bounds is considering just the newly added ROI, whereas the other lower bound is considering only the removed ROI. The summation of both gives the upper bound, as some misclassified object would be counted twice in this case, as there would be one ROI removal and one ROI addition. Nonetheless, the rate of change stands in between 5,99% and 9,34%. This is a considerable enough amount to justify the need of the validation, as having between 1 in 20 and 1 in 10 objects being incorrect is a very high ratio that would very likely reduce by some amount the overall precision of the system, by both the combined effect of less training data for the classes as well as more erroneous data. 4.2. Dataset split 37 Figure 19: Graph of change in dataset after validation. 4.2 Dataset split It is considered best practice in the field of machine learning to divide a dataset of size up to 10.000 images in the following format: 60% for training, 20% for dev and 20% for test [28]. The training set is the one upon which the neural network is trained, and the dev set is the one used to select among a group of possible configurations of the model (for example, different size of input image). Then the test set is used mostly for publications in order to test the selected model (having used already the training and dev tests) in front of "new" unseen dataset. Given that the current dataset of 10.000 images is made up of a total of 31 videos (out of which they only represent 23 different settings), it would be counterproductive to randomly select the frames to go to the different sets, as we would end up having in the training set probably images from all the videos and as there is no much difference from one frame to the next the dev and test sets would become unreliable as the resulting precision would seem to be very high. Instead, out of these 23 different, each entire one will be allocated to one of train/dev/test in order to avoid this, and they will be selected taking into account the 60-20-20% rule as well as being representative enough. Given the small amount of different videos, only 23, and the fact that they have quite different lengths, randomly selecting among these would not yield any meaningful result as in the end it is unlikely that a distribution of 60-20-20 would arise, which is why the selection has been made by hand (see Appendix for a detailed explanation on the selection process) taking into 4.2. Dataset split 38 account that they should all represent the entirety of possible scenarios in order not to lose out on training or miss difference in testing. It is also necessary, besides the decision-making behind which frames to put into each category, to generate files containing this information, as that is the format needed for the Darknet framework (which is thoroughly explained in the following chapter). This code works by going through a specified range (which has been set to match the desired split), and creating for each number in the range a line in the corresponding file (be it "train.txt", "test.txt", "dev.txt") the directory of the corresponding image. Originally, the entire test, train and dev sets files were generated with the same code (the one now used only for dev and test). This meant that the training data was ordered by videos, and ended up meaning that the system kept "forgetting" about previous data and optimized for the current video. This caused the models to have very low performance, but when instead of making the file in this ordered way the frames were written randomly, the overall performance rose significantly, meaning that this was indeed the problem. The following is the Matlab code developed and used to divide the dataset into the three categories train, dev and test: 1% This file generates the train.txt . 2 3% These are the bounds of the videos to be used in the training 4arrayPositionsTrain = [1 269;270 327;328 445;446 946;947 1127;1128 1211; 51212 1428;1429 1525;1887 2247;2248 2763;2764 4018;4019 4416;4417 4828; 65866 6213;6893 7569;7900 8399;9204 9303; 10094 11464]; 7nameTrain = 'train.txt';%Name of file to be generated 8% Path where the images are to be found 9origin = '/content/gdrive/MyDrive/Q8/TFG/darknet−master−copy/data/images'; 10 limit = size(arrayPositionsTrain); 11 % Compute number of images to be used 12 totalNum = 0; 13 for i=1:limit(1) 14 totalNum = totalNum + (arrayPositionsTrain(i,2)−... 15 arrayPositionsTrain(i,1)+1); 16 end 17 % Saving up in a variable the numbers of the frames 4.2. Dataset split 39 18 n=1; 19 for i=1:limit(1) 20 for j=arrayPositionsTrain(i,1):arrayPositionsTrain(i,2) 21 numbers(n) = j; 22 n=n+1; 23 end 24 end 25 notAllWritten = true; 26 selected = []; 27 while notAllWritten 28 % Generation of random number for random index 29 x = round((totalNum−1)*rand(1)+1); 30 isnotAlready = true; 31 % Check if index already used 32 for i=1:length(selected) 33 if(selected(i)==x) 34 isnotAlready=false; 35 end 36 end 37 if(isnotAlready) 38 % Add frame of the random index not already included 39 writeFrame(append(origin,mat2str(numbers(x)),'.jpg'),nameTrain); 40 % Update memory to add the already used index 41 selected(length(selected)+1)=x; 42 if(length(selected)==totalNum−1) 43 notAllWriteen = false; 44 end 45 end 46 end 47 % Function to write to the .txt file 48 function [] = writeFrame(line,name) 49 fileID = fopen(name,'a'); 50 fprintf(fileID,'%s',line); %change \ or / depending on need 51 fprintf(fileID,'\n'); 4.2. Dataset split 40 52 fclose(fileID); 53 end 1% This generates test.txt, as there is no need for random order 2arrayPositionsTest = [5042 5297;5298 5558;5559 5865;7570 7899;... 38790 9203;9304 9672;]; 4arrayPositionsDev = [1526 1886; 4829 5041;6214 6892;8400 8609;... 58610 8789;9673 9762;9763 9912;9913 10093;]; 6nameTestSet ='testSetTest.txt'; 7origin = 'C:\Users\rcoll\Desktop\TFG\darknet−master\data\images'; 8for i=1:length(arrayPositionsTest) 9% Write frames ordered 10 writeFrames(arrayPositionsTest(i,1),arrayPositionsTest(i,2),... 11 nameTestSet,origin) 12 end 13 14 function [] = writeFrames(begin,ending,name,origin) 15 fileID = fopen(name,'a'); 16 for i=begin:ending 17 fprintf(fileID,'%s',append(origin,'/',string(i),'.jpg')); 18 %change \ or / depending on need 19 fprintf(fileID,'\n'); 20 end 21 fclose(fileID); 22 end After executing the corresponding programs for the train and test and dev, the following type of file is generated (for the ordered ones): 1C:\Users\rcoll\Desktop\TFG\darknet−master\data\images\1526.jpg 2C:\Users\rcoll\Desktop\TFG\darknet−master\data\images\1527.jpg 3C:\Users\rcoll\Desktop\TFG\darknet−master\data\images\1528.jpg 4C:\Users\rcoll\Desktop\TFG\darknet−master\data\images\1529.jpg 5C:\Users\rcoll\Desktop\TFG\darknet−master\data\images\1530.jpg 6C:\Users\rcoll\Desktop\TFG\darknet−master\data\images\1531.jpg 7C:\Users\rcoll\Desktop\TFG\darknet−master\data\images\1532.jpg 4.2. Dataset split 41 8C:\Users\rcoll\Desktop\TFG\darknet−master\data\images\1533.jpg 9... In the same folder where all the images are positioned it is also necessary to put the annotations in order for the darknet framework to work correctly. 4.3. Dataset model adaptation 42 4.3 Dataset model adaptation One of the goals of this thesis is to evaluate on the validated dataset previous pre-trained models. In order to do so though, it is necessary to adapt the dataset to the expected output of these models, as in order to evaluate them the Darknet framework will be used, which will do such evaluation comparing the ground truth with the prediction of the model. The problem comes at the classes number, as each model has a different numbering system for every class, and some models to be tested have more or less classes than the ones we are interested in. The different models that will be evaluated are those trained upon the COCO dataset [23] as well as the aforementioned Roset’s models. In the case of the models trained upon the COCO, this dataset includes 80 categories and so there are 80 possible different classes. Of interest to us though, there are the whole 6 categories that we have been considering, although they are labelled differently, as seen in Table 3: COCO-based Roset’s Developed dataset Car 2 4 0 Truck 7 - 1 Pedestrian 0 1 2 Bike 1 0 3 Motorbike 3 - 4 Bus 5 5 5 Table 3: Class numbering of different models. So for evaluation of each model the created dataset will have to be changed in order for the class numbering to match that of the output of the model. This can be easily done through a small Matlab script (see appendix B). The only thing to take into consideration is the fact that Roset’s models lack 2 of the 6 classes, and so these objects will be deleted from the dataset in order to avoid any potential problem, and when comparing the different models that will have to be taken into account. Chapter 5 Neural network training 5.1 Darknet and YOLO Darknet[33] is a framework for developing and testing YOLO neural networks. Developed by one of the authors of the original YOLO papers, it allows for the rapid implementation, training and evaluation of YOLO neural networks by just using some defined commands in the command window. For the installation process in a local Windows machine, this process was followed [42]. Once installed, the end result is a folder with a darknet.exe file which is the executable file to run, train and test YOLO neural networks. There are many commands and tests that can be run. To do so, in the Windows operating system, the command prompt must be opened. After this, the directory has to be changed to the folder where the installed Darknet has been set, through the following command: 1cd directory Once in the directory, to run any darknet commands first .\darknet.exe must be written out. After this, the specific task is spelled out. For seeing how a particular network performs in real-time in front of a video, the following syntax must be used: 1.\darknet.exe detector demo obj.data yolov4.cfg yolov4.weights <video_file> The meaning and content of the files that appear after demo are explained in the following section. For showing the network’s output in front of a single image: 43 5.1. Darknet and YOLO 44 1.\darknet.exe detect yolov4.cfg yolov4.weights <image> To compute the mean average precision, precision, recall and others in front of a dataset: 1.\darknet.exe detector map obj.data yolov4.cfg yolov4.weights To train the network with a particular configuration and a particular dataset: 1.\darknet.exe detector train obj.data yolov4.cfg yolov4.weights 5.2. Previous models testing 45 5.2 Previous models testing Before the undertaking of the training of a network, it is first useful to analyse publicly available pre-trained networks in order to see how they perform in front of the current dataset (to see if there is a need for a new training or any of the available ones already perform to the needed specifications). For the YOLO v4 there are several available pre-trained networks which are accessible from the GitHub of YOLO v4 author Alexey Bochkovskiy. The other models to be tested will be those trained by Javier Roset, who is the author of the previous bachelor thesis that this one is a continuation of. The following models will be taken into consideration: - 11 models from Alexey Bochkovskiy - 9 models from Javier Roset An initial analysis will be undertaken for all of these models to be tested in front of the dev set curated in the previous chapter. In order to evaluate the performance of each model in front of the dev dataset, the Darknet framework is used, as it has specific commands aimed at computing a model’s precision and other metrics in relation to a dataset. The following command achieves the testing of the network: 1(base) .\darknet.exe detector map cfg/model.data cfg/net.cfg train.weight The file model.data has the following format: 1classes= 80 2train = data/train.txt 3valid = data/test.txt 4names = data/coco.names 5backup = backup/ The train.txt and test.txt files are the ones that have been created in the dataset split, but just using so far the dev file as the test.txt file. The classes is the number of classes that the network outputs. The names file is one containing in each line the name for each of the n classes the model is capable to distinguish. For example, for our network, it will be the following: 5.3. Training 52 1!git clone https://github.com/pjreddie/darknet 2%cd darknet/ 3!git clone https://github.com/AlexeyAB/darknet 4%cd darknet Once this is done, the Makefile file must be configured to indicate the usage of GPU, cuDNN and OpenCV. 1GPU=0 2CUDNN=0 3CUDNN_HALF=0 4OPENCV=0 All these values must be set to 1. After saving this, darknet can be built, and the copied to the Google Drive darknet folder: 1!make 2!cp ./darknet content/gdrive/My \ Drive/darknet/ After all this, we have the executable file darknet.exe at the darknet folder in Google Drive, which means that the next times we need to execute the code the downloading and compilation of darknet are no longer necessary. To be able to execute it, first the directory must be changed to match that of the .exe file, and then permission must be given to the file to allow it to execute: 1%cd content/gdrive/MyDrive/darknet 2!chmod +x ./darknet Now Darknet can be executed in the same way as in a local computer but only taking into account the different directories. For example, to test the mAP of a model the following command will be used: 1!.darknet detector map content/gdrive/MyDrive/TFG/darknet/data/test.data ... 2content/gdrive/MyDrive/TFG/darknet/cfg/yolov4.cfg ... 3content/gdrive/MyDrive/TFG/darknet/yolov4.weights 5.3. Training 53 The train.txt has to be adapted to this different path, but the same function as before, just changing the local directory, can be used. 5.3.3 Cloud training To train the network on Google Colab firstly the above procedure (except the mentioned parts that only need to be run once) must be executed. Nonetheless, training with the files created before cannot take place as the training.txt and test.txt as well as obj.data all contain local directories that will not be recognized in the Colab environment. Thus all these must be changed to match the correct locations. Starting with the train.txt and test.txt, they both must be in the following format: 1/content/gdrive/MyDrive/Q8/TFG/darknet−master−copy/data/images/1.jpg 2/content/gdrive/MyDrive/Q8/TFG/darknet−master−copy/data/images/2.jpg 3/content/gdrive/MyDrive/Q8/TFG/darknet−master−copy/data/images/3.jpg 4/content/gdrive/MyDrive/Q8/TFG/darknet−master−copy/data/images/4.jpg 5/content/gdrive/MyDrive/Q8/TFG/darknet−master−copy/data/images/5.jpg For the .data file, the following will be used: 1classes=6 2train =/content/gdrive/MyDrive/Q8/TFG/darknet−master−copy/data/train.txt 3test = /content/gdrive/MyDrive/Q8/TFG/darknet/data/test.txt 4names = /content/gdrive/MyDrive/Q8/TFG/darknet/data/train.names 5backup = /content/gdrive/MyDrive/Q8/TFG/darknet/data/images/4.jpg 6/content/gdrive/MyDrive/Q8/TFG/darknet/backup In relation to the backup, a folder with the name backup has to be created manually at the darknet folder. In this folder is where every 100 frames Darknet will save the current weights values and where afterwards we can retrieve them in order to restart training from the last saved point. It is also necessary for training to configure a YOLO network. In order to do so, there are several regards that can be changed up, mainly the size of the input image. With all these training can be done, through the following command: 1!.darknet detector train content/gdrive/MyDrive/TFG/darknet/data/train.data ... 5.3. Training 54 2content/gdrive/MyDrive/TFG/darknet/cfg/yolov4.cfg ... 3content/gdrive/MyDrive/TFG/darknet/yolov4-initial.weights −dont_show The yolov4-initial.weights is a file provided by AlexeyAB necessary to be able to start training. The -dont_show was added due to the fact that when it was not present an error appeared: "Unable to init server: Could not connect: Connection refused". This is due to Google Colab not allowing to show the graph of the average loss, and can be solved by using the command -dont_show [44]. After training begins, the command window will keep on showing several things, as seen in Figure 21. Among those, it is interesting to focus on the first number, which indicates at which iteration it is at, as well as the average loss for that particular iteration and the seconds it took to evaluate and learn. At the end of the first line it also computes the approximate time remaining to finish, although it is not very reliable. Figure 21: Output while training. In addition to this, darknet also graphs the average loss, but as we are using Google Colab and have to stop and restart training several times there are several graphs each containing a part, as seen in Figure 22. As it can be seen, it is reduced as the iterations increase, with Figure 22: Graph average loss. 5.3. Training 55 some peaks due to a change from one video to the next. After training is finished, in the backup folder darknet saves up the last computed values of the weight. It can now be tested out by computing the mAP as has already been explained before. Nonetheless, there is an option to compute the mAP of the model every 1000 iterations of training, but when this was tried it used up too much GPU and Google Colab would immediately remove access to GPU so it was left to be tested after the training had been done. The remaining part is to decide which models to train and their configurations. Both tiny YOLO as well as YOLO models will be trained, all based on YOLO version 4. Two models of each will be trained, all with the same amount of data, the original selected 6000 images plus an additional 1500 extra images to increase the amount of zenithal view (meaning a view from top, where the direction of the camera is perpendicular to the ground, also called bird’s eye view). The tiny yolov4 will be of two different input sizes, one of 416x416 pixels as the input and the other with an input of 640x640 pixels. The yolov4 will be one with an input of 480x480 pixels and the other with 640x640 pixels. The base configuration files are those provided by Alexey Bochkovskiy, which correspond to tiny-yolov4 and yolov4 models. Some changes to these need to be made. Firstly, the batch needs to be set at 64 and the subdivisions at 16. Then the width and the height have to be changed to match our desired input size (which needs to be a multiple of 32). The max_batches parameter needs to be set to the number of classes (6) times 2000, which is equal to 12000. And the steps need to be 80% and 90% of the max_batches. 1batch=64 2subdivisions=16 3width=480 4height=480 5... 6max_batches = 12000 7... 8steps=9600,10800 Then, in the part of the configuration file that describes each of the layers, all the [yolo] layers 5.3. Training 56 need to be modified so that their class parameter is equal to the amount of classes. And then, the preceding [convolutional] layer needs to be modified as well so that the filers are equal to (classes + 5)x3, which in our case is 33. 1[convolutional] 2... 3filters=33 4activation=linear 5 6[yolo] 7mask = 3,4,5 8anchors = 12, 16, 19, 36, 40, 28, 36, 75, 76, 55, 72, 146, 142 ... 9classes=6 10 ... 5.4. Validation 57 5.4 Validation Firstly, the trained models are validated against the dev set to see which ones are the best ones. After this, in the results section, it will be evaluated against the test set. Model AP [email protected] Recall car truck pedestrian bike motorbike bus tiny-yolov4 416 58,95% 74,82% 4,85% 0,05% 25,67% 81,65% 41,00% 31% tiny-yolov4 640 81,68% 81,54% 17,20% 8,54% 44,35% 87,67% 53,50% 47% yolov4 480 81,64% 81,18% 52,25% 62,83% 59,37% 82,11% 69,73% 66% yolov4 640 86,08%83,78%62,39%78,47%61,02% 84,08% 75,97%70% Table 5: Trained models’ testing results on dev set. Overall the precision levels are the highest in all but one category in the yolov4 with input of 640. This was to be expected, as yolov4 have higher precision than tiny-yolov4 and the higher the complexity and the input size the higher the precision is expected to be. The yolov4 with input size of 480, though, has very similar precision levels, with a mAP of 69,73% in front of 75,97% of the one with 640. As well as having a recall of 66% in front of a recall of 70%. Both values are high, and comply with the requirements of the precision. The tiny-yolo have much lower precision levels, although in the case of the bus category the tiny-yolov4 640 is the model that performs the best of all. In the car and truck category it even performs better as well than the yolov4 480. But where the tiny-yolo models fail is in the pedestrian, bikes and motorbikes categories. That is due to the fact that the tiny yolo models tend to struggle with small objects, as even the more complex yolo models already struggle with these as well (the precision in these categories for the yolo models is substantially lower than in cars, trucks and buses). This means that for scenarios where high speed is required and only large objects appear, the tiny yolo could be a candidate, but in other situations, where speed might not be as critical as increased performance, or where pedestrians for example might be present, these models should not be used. In Figure 23 the evolution of the mAP of the two yolov4 models can be seen as training proceeded. At first the model’s performance increases rapidly, and although there is a period after which the performance drops slightly, the precision tends in both cases to a stable value. As has been pointed in the section dealing with the creation of the training files, originally a mistake was made regarding the order in which, in the train file, the frames appeared. As the order was not random, all the frames from the same video appeared one after the other, making the system optimize for those frames and unlearning the previous information from 5.4. Validation 58 Figure 23: Graph of evolution of mAP of the yolov4 models. preceding videos. Only one tiny yolov4 416 and a half yolov4 480 were trained before the error was realized and corrected. Nonetheless, it is interesting to look at the impact on performance that this mistake had, and this can be seen in Table 6. The effects on the precision are quite stark, with a reduction of about 25% for the tiny yolo and a reduction of 30% for the yolo as compared to the same configuration but with the correct train files. Model AP [email protected] Recall car truck pedestrian bike motorbike bus tiny-yolov4 416 58,95% 74,82% 4,85% 0,05% 25,67% 81,65% 41,00% 31% tiny-yolov4 416 not random 58,43% 14,40% 1,92% 0% 10,28% 10,21% 15,87% 29% yolov4 480* 82,23% 75,24% 35,14% 30,97% 46,17% 80,95% 58,45% 60% yolov4 480* not random 72,67% 17,69% 14,52% 1,16% 16,60% 35,66% 26,38% 38% Table 6: Trained models’ with errors performance. * in the case of the yolov4 480 models, the comparison relates to partial results after 4200 iterations, as after that point the error was realized and training of the erroneous model halted. Chapter 6 Models comparisons The results already mentioned previously of Roset’s models, which were trained in front of the Stanford Drone dataset [38], poor performance on the VisDrone dev test are reversed as well, meaning that the models trained on the VisDrone dataset are highly inaccurate against the Stanford Drone dataset. This begs the question as to why this happens, and what factors are in play that affect a model’s performance and that have not been considered previously. 6.1 Datasets comparison The Stanford Drone dataset(SDD) a priori does not seem to be particular in any way, though there are some differences as can be seen in Table 7. Stanford Drone Dataset VisDrone Dataset Angle Zenithal Zenithal and angled Light conditions Sunny, with shadows Cloudy with no shadows Dimensions >1000x1000 pixels >1000x1000 pixels Objects categories Car,bus,person,bike,skater,cart Car,bus,truck,person,bike,motorbike Size 10.000/40.000 frames 7.500 frames Most prominent objects people, bikes cars,trucks, motorbikes Setting university campus streets city streets Table 7: Datasets comparison. One appreciable difference is the lower quality of the SDD frame, as seen in Figure 24 as compared to Figure 25. Evidently, there are substantial differences in lighting, object size and image quality, as well as the most prominent and usual object categories in each dataset. As well as the fact that 59 6.1. Datasets comparison 60 Figure 24: Sample SDD frame. Figure 25: Sample VisDrone frame. models trained in one dataset are inaccurate in the other. There is also the fact that in the SDD, pedestrians and bikers combined represent from 68,24% to 100% of the objects in the videos, meaning that the cars usually only represent less than 1% of the objects. That is quite different from VisDrone, where cars, trucks and buses are the most prominent and usual object categories. Paired with the fact that the VisDrone models already fare badly in front of pedestrians and bikers in its own dataset (for example in the yolov4 480 model with a precision of 52,25% for the pedestrians and 62,83% for the bikes) it might be a significant reason for the lack of transversality of the models. Testing this in other videos [10], not belonging to either of these datasets, it seems that it is partly related to this problem. In Figure 26 and Figure 27 the output of Roset model compared to the trained model can be seen. There is a clear difference, with Roset’s model only predicting bike and pedestrians whereas the trained model predicts mainly motorbikes and cars, and some pedestrians. Both models though fare poorly in front of this image, given the small objects to be detected and the completely different light and setting. Figure 26: Output Roset model 5. Figure 27: Output trained yolov4 480. In Figure 28 and Figure 29 a further example of this can be seen. Again Roset’s model 6.1. Datasets comparison 61 detects only pedestrian while the trained model detects motorbikes and pedestrians. It is also interesting to see that Roset’s model mainly detects in the upper half of the image, which is more illuminated than the lower half. In comparison the trained model mainly detects in the lower half, in the area most covered by shadows. This points also to the different lighting conditions of the datasets, with the SDD having only sunny images and the VisDrone mainly having cloudy frames. Figure 28: Output Roset model 5. Figure 29: Output trained yolov4 480. In Figure 30 and 31 we can see a scenario where both networks are incapable of detecting any objects. In this case, it might be due to an abundance of cars and trucks, which Roset’s models are bad at detecting, as well as the objects being very small compared to the overall size of the picture, which seems to be something the trained model misses to identify. Figure 30: Output Roset model 5. Figure 31: Output trained yolov4 480. 6.4. Dataset view orientation 68 seeming to be pointing to a positive correlation. Figure 42: Change in performance in relation to the amount of images. Given the low p-value, below the 0.050 threshold, the null hypothesis of there being no correlation can be rejected, meaning that there seems to be a correlation between the overall amount of angled view images and the mAP, which is also high, of 0.9706, meaning almost complete positive correlation between the two variables tested. Although it has to be taken into account that the sample of just 4 data points is very small and much more data would need to be collected to be able to make meaningful conclusions about the correlation. In addition, this test should also be undertaken in other datasets and with other models to make sure that it is not dataset specific but rather a general property of YOLO or convolutional neural networks in general. All the models perform poorly, but nonetheless, the original model has the highest of all mean average precision as well as recall, due to its good precision in the detection of cars. The only area where the original model is outperformed is in the truck’s precision, which could be due to the fact that the added images contain a high amount of frames with trucks on them, thus probably increasing the performance. Thus, it could be the case that the angled view additional images do not hinder the performance on the zenithal view but rather enhance it. So it could be that a model trained on both a dataset containing large amounts of angled and zenithal view images would perform better than either a model trained only on the zenithal view or only on the angled view images. Nonetheless, more research should be done in this area to confirm whether this preliminary results hold up in other datasets and in larger amounts of images. Chapter 7 Street footage detection 7.1 Transit cameras footage A possible application area for the trained networks would be to be used on transit cameras footage, or similar security cameras footage. A very useful case study is the city of Barcelona, which has a webpage through which users can access the images of transit cameras (although they are updated only every 5 minutes): Link. They are, though, very low quality images, and some also do not represent the colours accurately, as can be seen in Figures 43. Figure 43: Examples from Barcelona camera traffic.Source Due to these data limitations, of low quality and bad colour, as well as bad lighting, the networks are imprecise in some cameras, but good in others. For example, in Figure 44 the system is good at detecting both the car and the people next to it. It could be used to detect traffic levels in this street as well as how busy the pedestrian zone is. 69 7.1. Transit cameras footage 70 Figure 44: Case with accurate detections. In Figure 45 other scenarios where the network performs good can be seen. The example on the left could be used, for example, to estimate the amount of cars getting in and out of the city, whereas the example on the right could be used, as previously, as an automatic detector of traffic levels in certain parts of the city. Figure 45: Cases accurate detection. Not in all cameras, though, does the network predict accurately. In some, where lighting conditions are poor, or the quality is particularly low, the system has difficulties in detecting objects. For example, in Figure 46 two such examples can be seen. In the left picture, although the system does detect some objects, it fails to detect most of the present objects, such as other cars, bikes and pedestrian present. In the right picture it fails to predict any object at all. So, for the network to be used in such a scenario, the general lighting and quality conditions for the cameras would have to be assessed, and be implemented only in those where it performs accurately. 7.2. Drone footage 71 Figure 46: Cases with few detections (left) or none (right). 7.2 Drone footage As has been mentioned in the beginning, the objective of the trained models will be that of being used from a drone to be able to identify objects. To test if it might work under different conditions than those offered by the VisDrone dataset, a small experiment has been undertaken by recording short videos of street footage with two different drones, a Tello drone and a DJI drone, and with different cameras orientations. You may see the results of those experiments in the following link:Video results. It has been tested upon the 480 YOLO network, as it has a higher processing speed which is necessary for real-world and real-time applications. In Figure 47 a sample of the footage from the Tello drone can be seen, and in Figure 48 a sample from the DJI drone can as well be observed. There are differences between the two, as the Tello’s images are of lower quality and smaller, and with a forward orientation, whereas the DJI’s footage is high resolution and the camera can be at any desired angle (including zenithal view images). Figure 47: Sample from Tello drone. Figure 48: Sample from DJI drone. 7.2. Drone footage 72 When testing these video for the network, several results and conclusions can be reached. In general it works well, specially for cars and in angled-view footage. In Figure 49, the same setting can be seen from one frame to the next. In the first frame, on the left, the system is able to detect the bicycle as well as the person riding it and with high probabilities assigned to each. But in contrast, in the next frame, when the bike is in front of the car, the system stops detecting it. This points to a problem by the system to detect in the same place multiple objects, as there is a car behind the bicycle that it does detect. In addition, the system’s predicted probability of the car also drops, from 94% to 78%. Also in the same frames, it is interesting to look at the person on the right, as in the first frame, when the person is occluded partially by the fence, the system does not detect him, but in the next one it does, as the object is no longer partially occluded. Nonetheless, in both cases, the system is able to detect the cars and people, and leaves out only one or two objects. It is thus, a fairly good detector, that seems to perform better when there is a clear, unobstructed view of the object and when there are no multiple objects in the same place. Figure 49: Frames with bicycle. When testing with the DJI drone, with an angled view and high resolution images, the aforementioned problems are not so present as, due to the angle view, not many objects overlap over one another, and even in occluded objects it still is able to detect them sometimes as there is a clearer view, as can be seen in Figure 50. The overall precision with cars seems to be high, as most cars are detected. When it comes to the detection of people, the system is not so reliable, as the same person is in some frames detected and in others not, as can clearly be seen in Figure 51. In the first frame it is detecting the woman, but in the second one it is no longer, and it is something 7.2. Drone footage 73 Figure 50: Frame result DJI drone. that happens multiple times, as the system goes detecting and non detecting the same person as it moves along or even when the person is still. Figure 51: Frames with person. This problem might correlate to another result, which is that the system tends to perform better in detecting people when multiple people are together, as seen in the right frame in Figure 52. And also sometimes the system seems to detect not just the person, but also the shade of the person, as can be seen in the left frame. Figure 52: Frames with multiple people. This might be due to the nature of the dataset itself, because, as it can be seen in Figure 53, the largest amount of people can be found in large groups in the frames, and given the high amount that appear, the system is likely to have learned how to identify large groups of 7.2. Drone footage 74 people more than single individuals. Figure 53: Frame from VisDrone dataset. When it comes to zenithal view images, as has already been tested before, the system does not perform particularly well, but is able to detect some of the overall cars, as can be seen in Figure 54 Figure 54: Output zenithal view. Chapter 8 Application area: accident prediction The developed models are fairly accurate and can have a wide array of possible application areas, one of which is that of accident prediction. That is, by means of the detected and located objects that the YOLOv4 network gives, after some post-processing the paths of these objects can be estimated and possible collisions between objects can be inferred. This is a real possibility as it has already been researched recently by Chavan, Deesha et al. in their paper "COLLIDE-PRED: Prediction of On-Road Collision From Surveillance Videos" [7] in 2021. Their model, COLLIDE-PRED, involves a YOLOv4 neural network for object detection and classification, with the results of it being fed to a siamese region proposal network (SiamRPN), which is a network architecture for object tracking, and will give a trajectory for each object fed by the YOLO network. After this, the trajectories are fed to a Transformer, which is a type of deep learning network, which then makes predictions for the future paths of each object. Their system then compares the predicted paths of the different objects, and a collision is predicted if at the same instant the model predicts to objects will be in the same position. A simpler model is here constructed, based as well on the YOLOv4 network already trained, but instead of feeding its results to other neural networks, simple programs and mathematical computations are used to estimate the objects’ paths and possible collisions of objects. It is interesting to test these ideas on drone’s cameras, as the prior aforementioned research focused in surveillance cameras, and other previous ones have as well focused on surveillance cameras or on first-person videos (as those recorded from a car itself)[46]. 75 8.1. Object tracking and path prediction 76 8.1 Object tracking and path prediction A very simple method has been used for object tracking and path prediction. For object tracking, the system looks for an object within the bound of the region of interest with the same class category in the previous frame, and if it finds any it considers it to be the same object as the one it is being looked at. This is tried for a previous frame and two previous frames before, thus tracking potentially the object two frames previously. If the system is able to find the object in previous frames, the linear regression of the centres of the regions of interest is computed to do an estimation of the future path of that particular object, which is how the path prediction is made. The system computes these for all the objects in the current frame, and then proceed to solve the systems of linear equation of each object’s regression path with all the others’ predicted paths (when these have been estimated). If the intersection point is found within the bounds of the camera view, and if both objects’ direction is towards that point (that is, their x and y axis speed, computed as the difference in the centre of the ROI between the current and previous frame, is directed towards the intersection), then the system predicts a possible collision. More advanced systems could here include filers for the relative distance to the intersection considering the current positions and speeds of the objects. In Algorithm 4 you may see the basic concept behind the object tracking process. A very simple method is used, as explained just looking for a previous object of the same class whose bound the current centre is within. In simple cases where there is no overlapping of same class objects over one another and the speed of the vehicle and frames per second ensures the fact that the condition stays, this is a good enough approximation. For people, though, as they are objects whose centre moves proportionally far from the region, an offset has been added to the previous’ region of interest bound, to make those larger to better detect people’s paths. With the object tracking algorithm, it is possible to get the previous position of an object, and thus do a simple linear regression of the positions as seen in Algorithm 5 (in the implementation, three points are found, but to be more concise, only two are shown in the algorithm). The path is saved up in a global variable, paths, that is then used to display the different paths and also to predict possible collisions and show to the user those. 8.2. Collision prediction 77 Algorithm 4 Object Tracking function objectTrack(cObj,previousObjectsList) for pObj in previousObjectsList do if cObj.class == pObj.class then if pObj.x < cObj.x < (pObj.x +pObj.width) & pObj.y < cObj.y < (pObj.y + pObj.height)) then return pObj end if end if end for return null end function Algorithm 5 Path prediction for i=1:length(currentObjectsList)do cObj ←currentObjectsList(i) previous ←ObjectTrack(cObj, previousObjectsList) if previous =null then paths(i).path ←linearRegression((cObj.x, cObj.y),(previous.x, previous.y)) paths(i).position ←(cObj.x, cObj.y) paths(i).speed ←(cObj.x −previous.x, cObj.y −previous.y) paths(i).class ←cObj.class paths(i).exists =true end if end for 8.2 Collision prediction With the object tracking and path prediction algorithms, the used method to predict collisions is simple, solve the systems of equations to find the intersection points of two paths. If the intersection is within the bounds of the image size, then it proceeds to analyse the direction of the two moving objects in respect to the intersection. If the sign of the x, y velocity (as defined by the current position minus the previous position) and the sign of the distance to the intersection (as defined by the difference of the current position minus the intersection) are opposing, it means that the object is moving towards the intersection, and as a consequence there is a possible collision. If both do not hold, then the object is moving away from the intersection and is thus not considered a potential collision. The implemented algorithm has some additional filters, such as omitting intersections between people, or considering that a particular object is static if its x, y velocity are smaller than some threshold, which has been set by trial and error (though this threshold is not always useful, as depending on the relative size and distance of objects in the images some clearly non-static objects are considered static). 9.1. Model performance on test set 84 In order to know the speed of each model, in the Google Colab environment (as the speed will depend on the available GPU,CPU and memory of the computer running it) it was tested. To do so, the command needed was !./darknet detector demo ... . 1!./darknet detector demo cfg.data yolo.cfg yolo.weights vid.mp4 −dont_show This is a command that allows for the system to get as input a video and show in real time the predictions the network does. It also computes the average frames per second. The video it was tested upon was a short video taken from the Tello drone, which is a low quality video, and thus it will take less time to access and it will better reflect the processing speed of the network. In Table 11 the results can be seen, with an expected trend of the tiny-yolo being faster than the YOLO, and the higher image input size being slower than the lower input size. Model FPS tiny-yolov4 416 59.9 tiny-yolov4 640 47.2 yolov4 480 39.7 yolov4 640 29.6 Table 11: Trained models’ processing speed. The yolov4 480 seems to be a good compromise between accuracy and speed, as in the test set it has a very similar mAP to the yolov4 640 (60% in front of 61%) but much higher speed, being able to process an extra 10 frames per second. 9.2. Environmental, economic and social impact 85 9.2 Environmental, economic and social impact Environmental impact A very relevant result needed is that of the environmental impact of the project. This impact is due mostly to the negative effect of model training as the amount of hours and energy needed for each model is high. In addition of training, all the testing also resulted in increased computing time. The Tesla K80 has a maximum power consumption of 300W[29]. For each of the models, an average of the computing time has been estimated (as, due to the fact of changing from Google accounts there is no record of exact time). Then, associated with this comes the CO2 emissions per kWh of energy consumed. The problem of computing this now stems from the fact that Google Colab does not state where the cloud services are located, and seem to be assigned randomly. This impacts the calculations, as depending on the location, each kWh emits a different average of equivalent kg of CO2. What seems most likely though, is that they might be located in the USA. This is due to the fact that Google Cloud services data centres, which are the ones used by Google Colab, are predominantly located in the USA[15]. Out of the 23 locations, 14 are located in the USA, 6 in the European Union and the rest around Asia and South America. Thus, the average CO2 equivalent Kg/kWh of the USA and the EU will be used in the calculation, as upper and lower bounds. According to the United States Environmental Protection Agency, the equivalent emissions of kilograms of CO2per kWh consumed is of 0,433eq. kg CO2/kWh [43]. In the European Union it is an average of 0,294 eq. kg CO2/kWh [9]. To compute the total emissions, this factor will be multiplied by the amount of hours and by 0,3 kW (which is the consumption of the GPU). In addition to the GPU, the data center will also be consuming energy but these will be small compared to the high energy intensity of the GPU usage, and paired with the claim that google makes that its data centers run on carbon offset energy (meaning that Google compensates its CO2emissions with carbon capture of some sort[13]) these additional emissions will be omitted. As can be seen in Table 12, the total cloud training and testing emissions range from 43,21 to 63,65 eq. kg CO2/kWh. In addition to these emissions, though, there are the associated emissions from the usage of the personal laptop to, first, run the cloud services, as well as generating the GUI, the datasets, writing the thesis, and many other such tasks. A rough estimate would be of around 8 hours per day, for 6 days a week, for the duration of the 9.2. Environmental, economic and social impact 86 Task Computing time USA emissions EU emission (hours) (eq. kg CO2) (eq. kg CO2) tiny-yolov4 416 (x2) 10 2,59 1,76 tiny-yolov4 640 30 3,89 2,64 yolov4 480 (x2) 80 20,78 14,11 yolov4 640 150 19,48 13,23 yolov4 480 33% 50 6,49 4,41 yolov4 480 50% 40 5,19 3,52 yolov4 480 66% 35 4,54 3,08 model testing 5 0,65 0,44 TOTAL 63,65 43,21 Table 12: Trained models’ training time. semester, which is of 18 weeks, meaning a total of 864 hours. The used computer has a consumption of 78 W, which means a total consumption of 67,39kWh. In Catalonia, the emission factor is of 0,25 eq. kg CO2/kWh [40]. Thus, the additional emissions from the usage of the computer are 16,85 eq. kg CO2. It is rather small when compared to the consumption of the training and testing, given the amount of hours of each. This shows the high impact that the training of deep neural network has, as it requires very powerful hardware which in turn consumes high amounts of energy. Economic impact The economic cost of the project is small, as thanks to Google Colab the cost of training and testing the networks has been null. There is though, the associated costs with the power used for the computer. Considering a mean of 0,3082 e/kWh over the period February-May 2022 [31], it means a total cost for the computer electricity of 20,77 e. In addition to these, were this project to have been developed within a company, all the hours worked would have come at a cost as well. Considering the average engineering intern salary of 8 e/hour, and given the fact that 24ECTS are equivalent to 720 hours, the total cost of the employment for the realization of this project would have been of 5760 e(without taking into account contributions to social security). With the addition of the VAT, the total budget would need to be of 6994,73e. 9.2. Environmental, economic and social impact 87 Social impact The social impact of the project ascertains two main things: privacy concerns, and potential benefits arising from it. As was seen, the initial goal was that of creating a self-made open dataset, but this was denied as it may have infringed privacy regulations such as GDPR. When some testing was performed on street footage, it was always intended in a way such that no person could be identifiable from the videos, and the videos are not open to the public but only accessible through the link provided here. There are some potential benefits to the project, such as the collision prediction algorithm, that if it were further developed, could be deployed and may be able to avoid some accidents. The traffic camera application could also help policymakers as well as commuters better know in real time the state of streets, both for private vehicles as well as for pedestrians. Chapter 10 Conclusions 10.1 Conclusions Throughout the project, several different tests, experiments and approaches have been made, with a set of conclusions for each. •The developed GUI for datasets creation is useful in stationary as well as low speed movement camera settings. •The GUI for dataset validation works as intended, and has been proven to be necessary as there has been around 6-9% of modifications as from the original annotations. •When installing and using Darknet, the alternative of using it through Google Colab, instead of running it locally, is a better option as for higher complexity models an average computer is unable of training or executing it. •The testing of Roset’s models on the VisDrone dataset, even when in zenithal view only, produced very poor results, and the same occurred when testing in the Stanford dataset the trained networks on the VisDrone dataset. The reasons for these seem to be a combination of multiple factors, including lighting conditions, resolution of images, most prominent type of objects. Contrast, on the other hand, is not clear to be a driving factor in the difference in performance from one dataset to another. •Having tested a same model with different percentages as of total of zenithal view images, it can be concluded that, a priori given the small data, it seems that additional angled-view images improve performance on zenithal view, even if they are not in the 88 10.1. Conclusions 89 same orientation. With a correlation coefficient of 0.9706 and a p-value of 0.0294 the results, although based on just 4 data points, seem to point to that conclusion. •The trained yolov4 models performance has been tested on drone footage obtained from two different drones. •4 total models have been trained: one tiny-yolov4 with input an input of 416x416 pixels, one tiny-yolov4 with input of 460, one yolov4 with input 480 and one yolov4 with input 640. In front of the test set, they have a mAP with threshold of 0.5 of 34,08% for the tiny-yolo 416, 51,62% for the tiny-yolo 640, 60,35% for the yolo 480 and 62,28% for the yolo 640. •The average processing speed, when used in a Tesla K80 on Google Colab, is 59.9FPS for the tiny-yolov4 416, 47.2FPS for the tiny-yolov4 640, 39.7FPS for the yolov4 480 and 29.6FPS for the yolov4 640. •Overall, the yolov4 with input 480 seems to be the best compromise between accuracy and speed, performing just slightly worse than the yolov4-640 (1% point of difference in the test set), but much higher than the tiny-yolos(with over 10% points in performance), but with a higher FPS processing speed than the yolov4-640 (39,7 FPS in front of 29,6) FPS. •The performance of the networks on the test set does not reach the goal of 70% of precision (although on the dev set it does). But nonetheless, in some categories, this threshold is surpassed, both in the yolov4 480 and 640 for the classes car and bike (and close in the pedestrian category) with over 80% precision. In order to reach a higher precision level, more amounts of data would be needed in the training process. •The models, although they are able to make some detections with zenithal view images, perform poorly on those. Additional images in zenithal view at the dataset would be needed to increse the precision. •The trained models can be used, with varying levels of success, in the traffic cameras footage of the city of Barcelona. In most well lit, well positioned cameras the models accurately predict all main objects. Although, in some cases, where there is difficult views from the camera, the models detect few if any of the real objects. •The models can be used for drone footage detection and classification with good results, specially in the cases of cars. The model performs best when there are no overlapping 10.1. Conclusions 90 objects, as in those cases only one object is usually predicted. And it detects people the best as well when they are in groups instead of being by themselves. •In the drone footage, when zenithal view images are tested for the models, they are able to detect some of the cars, but are unreliable in other object categories or in detecting all the cars present in the pictures. •A collision prediction algorithm has been developed, which is able to make some predictions regarding possible accidents. It is a very simple algorithm, based on a linear regression of 3 points when possible, for the prediction of paths, and followed by a linear equation solver to detect intersections of paths. •The collision prediction algorithm fails in two regards: making too many false predictions, and being too slow to process each picture. The first one, although problematic, still mean that the system is likely to predict real life collisions. The second though, makes the system too sluggish to be able to respond to any such possible accidents, but is also solvable by running the code on more powerful hardware. •Recalling the original requirements for the system, which were: a precision of 70%, a processing speed of 10 frames per second, a training period of 4 days and a cost of at most 50 e. •The precision level of 70% is not achieved by any of the models in the test set, but for the yolov4 640 that threshold is surpassed in three categories (car, pedestrian and bike) and for the yolov4 480 it is surpassed in two (car and bike). It is a partial fulfillment of this requirement. •The prcoessing speed threshold of 10 FPS is surpassed in all the models in the test data, with the slowest model (yolov4 640) having a processing speed of 29,6FPS, thus fulfilling the requirement. •The training time of 4 days is fulfilled by all the tiny yolos, as well as for the yolov4 480. In the case of the yolov4 640 it is not achieved, surpassing it by 2 days. •The cost of less than 50 eis achieved as for all the models the training has been free thanks to google colab. As has been previously stated, all the codes, as well as all the trained modesl, can be found here: https://github.com/RichardCollJosifov/YOLO 10.2. Possible application areas 91 10.2 Possible application areas The developed model could have a wide array of applications, some of which have already been explored. One of these would be automatically counting the amount of cars getting in or out of a city, as with the Barcelona traffic cameras test example, which showed potential for this area, as in most cases seemed to work correctly. Another possible application is that of being used in drones, as for example for the collision prediction algorithms. This could be further integrated with some kind of warning system for the cars, which would be activated in case of a collision prediction. Or going further into the future, automatically warn a self-driving car to correct its path to avoid the collisions. 10.3 Future research Some of the developed algorithms and models have been found to have certain limitations. Future work on them could deliver more reliable systems that could then be implemented. Firstly, as had been tested, the trained models would need to have more zenithal data to be trained upon in order for them to be more reliable. This could be done either by finding other drone-based datasets with abundant amounts of zenithal view images, or by the usage of the developed GUI for dataset creation and some of the recorded videos in this project for model testing. Secondly, further research could also be undertaken in trying to identify why some datasets, such as Stanford, seem to be incompatible with other ones. Some preliminary results have been reached, but no clear and concise explanation as to why this may happen has been found. This is relevant as it relates to the generalization and applicability of a model being used in different conditions for the same purpose. Finally, the collision prediction algorithm developed is very simple and as a consequence has several limitations. For example, it generates a high proportion of false predictions regarding collisions, as well as being able to generate these only a few frames before any actual collision would occur. Probably, the best way to try and solve these would be by implementation of an algorithm similar to Chavan, Deesha et al. This would require configuring and training two additional neural networks, but the benefits in precision and accuracy would be substantial. More research should be made in the area as well, because there are not any alternatives to 10.3. Future research 92 their algorithm yet tested, and there might be other configurations or algorithms that could be better for the specific conditions of our requirements. References [1] Amazon Web Services. Calculadora de precios de AWS. 2022. url:https://calculator. aws/#/?nc2=h_ql_pr_calc. (visited on 05/03/2022). [2] Yoshua Bengio, Aaron Courville, and Pascal Vincent. Representation Learning: A Review and New Perspectives. 2012. doi:10.48550/ARXIV.1206.5538.url:https://arxiv. org/abs/1206.5538. [3] Alexey Bochkovskiy, Chien-Yao Wang, and Hong-Yuan Mark Liao. YOLOv4: Optimal Speed and Accuracy of Object Detection. 2020. arXiv: 2004.10934 [cs.CV]. [4] Gaudenz Boesch. Object Detection in 2022: The Definitive Guide. 2022. url:https: //viso.ai/deep-learning/object-detection/. (visited on 26/03/2022). [5] Javier Roset Cardona. “Estudi sobre la categorització d’elements terrestres a partir d’imatges aèries de pla zenital”. Universitat Politècnica de Catalunya, 2021. url:http: //hdl.handle.net/2117/360728. [6] CAT1210. Error: cuDNN isn’t found FWD algo for convolution #7669. 2021. url: https://github.com/AlexeyAB/darknet/issues/7669. (visited on 24/03/2022). [7] Deesha Chavan, Dev Saad, and Debarati B. Chakraborty. COLLIDE-PRED: Prediction of On-Road Collision From Surveillance Videos. 2021. url:https://arxiv.org/abs/ 2101.08463. [8] Richard O. Duda and Peter E. Hart. “Pattern classification and scene analysis”. In: A Wiley-Interscience publication. 1973. [9] European Environment Agency. CO2 Intensity of Electricity Generation. 2020. url: https://www.eea.europa.eu/data-and-maps/data/co2-intensity-of-electricity- generation. [10] Tom Fisk. Aerial Views. 2022. url:https://www.pexels.com/@tomfisk/. (visited on 05/04/2022). 93 100 56 app.actualizeDatabase(x,y,width,height); 57 end 58 function [] = generatePicture(app) 59 if(app.previousImage~=0) 60 try 61 oldfolder = cd('frames'); 62 imageA = imread(frame-+app.previousImage+.jpg); 63 imageB = imread(frame-+app.currentImage+.jpg); 64 app.imageHeight = length(imageB(:,1,1)); 65 app.imageWidth = length(imageB(1,:,1)); 66 app.pixelInROI = zeros(app.imageHeight,app.imageWidth); 67 catch 68 cd(oldfolder); 69 YN = uiconfirm(app.UIFigure,'No more images, closing'); 70 if strcmpi(YN,'OK') 71 delete(app) 72 end 73 end 74 cd(oldfolder); 75 imshow(imageB,'Parent',app.UIAxes); 76 hold on 77 78 %Changes to accomodate moving drone 79 if app.movingCamera==false 80 B = filterImage(app,imageA,imageB); 81 else 82 B = filterMovingImage(app,imageA,imageB); 83 end 84 imshow(B,'Parent',app.UIAxes2); 85 86 %Function that automatically generates ROIs 87 try automaticDetection(app,B); catch; end 88 89 %Ask user if he wants to proceed to the next image 101 90 try 91 YN = uiconfirm(app.UIFigure,'Do you want to proceed?'); 92 if strcmpi(YN,'OK') 93 nextImage(app); 94 end 95 catch 96 end 97 else 98 oldfolder = cd('frames'); 99 app.image1 = imread(frame-+num2str(app.currentImage)+.jpg); 100 app.imageHeight = length(app.image1(:,1,1)); 101 app.imageWidth = length(app.image1(1,:,1)); 102 cd(oldfolder); 103 imshow(app.image1,'Parent',app.UIAxes); 104 end 105 end 106 107 function [] = setROIType(app,type,number) 108 index = find(strcmp(app.classTypes,type)); 109 app.roi(app.offROI+number−1).roi.UserData = int2str(index); 110 app.roi(app.offROI+number−1).roi.EdgeColor =... 111 char(app.coloursTypes(index)); 112 end 113 114 function [] = changeROIType(app,type) 115 try 116 app.roi(app.automaticOffROI).roi.UserData = int2str(type); 117 app.roi(app.automaticOffROI).roi.EdgeColor =... 118 char(app.coloursTypes(type)); 119 catch 120 end 121 end 122 123 %Function to change the ROI type, or delete the ROI if inputed by 102 124 % the user 125 function [] = identify(app) 126 try 127 type = getkey(); 128 type =type −48;%Conversion from ASCII to decimal 129 if(type==0) 130 delete(app.roi(app.automaticOffROI).roi) 131 app.roi(app.automaticOffROI).roi = [] 132 app.automaticOffROI = app.automaticOffROI−1; 133 elseif(type>=2 && type<=6) 134 changeROIType(app,type) 135 end 136 catch 137 end 138 end 139 140 %Function that changes the current image to the next one 141 function [] = nextImage(app) 142 saveExit(app); 143 app.automaticOffROI = app.offROI; 144 if(app.previousImage>0) 145 app.previousImage = app.previousImage+1; 146 elseif(app.previousImage==0 && app.currentImage+1>=app.delay) 147 app.previousImage = 1; 148 end 149 app.currentImage = app.currentImage+1; 150 app.Label.Text = string(app.currentImage); 151 generatePicture(app); 152 end 153 154 %Function that automatically goes through the filtered image and 155 %goes generating ROIs around possible locations of objects 156 function [] = automaticDetection(app,image) 157 for column=1:length(image(1,:)) 103 158 rows = find(image(:,column)); 159 for j=1:length(rows) 160 if(app.pixelInROI(rows(j),column)==0) 161 [x1,y1,w1,h1] = createRectangle(app,rows(j),column,image); 162 app.roi(app.automaticOffROI).roi =... 163 images.roi.Rectangle('Parent', app.UIAxes,... 164 'Position',[x1−app.marginOffset,y1−app.marginOffset,... 165 w1+app.marginOffset,h1+app.marginOffset],... 166 'EdgeColor','r','LabelVisible','hover',... 167 'LineWidth',2,'UserData','1'); 168 identify(app); 169 app.automaticOffROI = app.automaticOffROI+1; 170 end 171 end 172 end 173 end For the validation of the VisDrone dataset: 1function [] = validateDataset(app) 2oldfolder = cd('validateDataset'); 3currentfolder = cd('frames'); 4A=dir; 5try 6%Open folder 7nameCurrent = A(2+app.validateFrame(2)).('name'); 8cd(nameCurrent); 9catch 10 %No more images 11 YN = uiconfirm(app.UIFigure,'No more images, closing','success'); 12 if strcmpi(YN,'OK') 13 delete(app) 14 end 15 end 16 104 17 %Function that gives amount of zeros to match VisDrone dataset 18 zerosInitial = getZeros(app); 19 try 20 %Open current image 21 app.imageValidate= imread(zerosInitial+app.validateFrame(1)+.jpg); 22 app.imageHeight = length(app.imageValidate(:,1,1)); 23 app.imageWidth = length(app.imageValidate(1,:,1)); 24 imshow(app.imageValidate,'Parent',app.UIAxes); 25 if((length(dir)−2)>=(app.validateFrame(1)+1)) 26 %There are still more images in this folder 27 app.validateFrame(1) = app.validateFrame(1) +1; 28 else 29 %No more images in this folder 30 app.validateFrame(2) = app.validateFrame(2)+1; 31 app.validateFrame(1) = 1; 32 end 33 catch 34 %Case where there are no images in the folder 35 app.validateFrame(2) = app.validateFrame(2)+1; 36 app.validateFrame(1) = 1; 37 end 38 39 cd(currentfolder); 40 cd('annotations'); 41 Datafile = table2array(readtable(append(nameCurrent,'.txt'))); 42 limit = size(Datafile); 43 for i=1:limit(1) 44 if(Datafile(i,1)==app.validateFrame(1) && Datafile(i,8) ~= 0) 45 typeObject = Datafile(i,8); 46 if(typeObject==1 || typeObject==2) 47 typeObject='3'; 48 colorObject = 'g'; 49 elseif(typeObject==3) 50 typeObject='4'; 105 51 colorObject = 'c'; 52 elseif(typeObject==4 || typeObject==5 || typeObject==11 || ... 53 typeObject==10) 54 typeObject='1'; 55 colorObject = 'r'; 56 elseif(typeObject==6 || typeObject==9) 57 typeObject='2'; 58 colorObject = 'magenta'; 59 elseif(typeObject==7 || typeObject==8) 60 typeObject='5'; 61 colorObject = 'b'; 62 end 63 app.roi(length(app.roi)+1).roi = images.roi.Rectangle(... 64 'Parent', app.UIAxes,'Position',[Datafile(i,3),... 65 Datafile(i,4),Datafile(i,5),Datafile(i,6)],'EdgeColor',... 66 colorObject,'LineWidth',app.lineWidth,'LabelVisible',... 67 'inside','UserData',typeObject); 68 end 69 end 70 cd(oldfolder); 71 end The dataset validation GUI is very similar to the previous one, with just the following differences, which relate to data reading from the file and then the conversion of this into the ROI data type: 1function zerosInitial = getZeros(app) 2if (app.validateFrame(1)*app.reduction<10) 3zerosInitial = 000000; 4elseif(app.validateFrame(1)*app.reduction<100) 5zerosInitial = 00000; 6elseif(app.validateFrame(1)*app.reduction<1000) 7zerosInitial = 0000; 8elseif(app.validateFrame(1)*app.reduction<10000) 9zerosInitial = 000; 106 10 end 11 end 12 13 function [] = validateDataset(app) 14 oldfolder = cd('validateDataset'); 15 currentfolder = cd('frames'); 16 A=dir; 17 try 18 %Open folder 19 nameCurrent = A(2+app.validateFrame(2)).('name'); 20 cd(nameCurrent); 21 catch 22 %No more images 23 YN = uiconfirm(app.UIFigure,'No more images, closing down'); 24 if strcmpi(YN,'OK') 25 delete(app) 26 end 27 end 28 29 zerosInitial = getZeros(app); 30 31 try 32 %Open current image 33 number = app.validateFrame(1)*app.reduction; 34 app.imageValidate = imread(zerosInitial+number+.jpg); 35 app.imageHeight = length(app.imageValidate(:,1,1)); 36 app.imageWidth = length(app.imageValidate(1,:,1)); 37 imshow(app.imageValidate,'Parent',app.UIAxes); 38 dimension = length(dir); 39 catch 40 %Case where there are no images in the folder 41 app.validateFrame(2) = app.validateFrame(2)+1; 42 app.validateFrame(1) = 1; 43 end 107 44 45 cd(currentfolder); 46 cd('annotations'); 47 Datafile = table2array(readtable(append(nameCurrent,'.txt'))); 48 limit = size(Datafile); 49 for i=1:limit(1) 50 if(Datafile(i,1)==app.validateFrame(1)*app.reduction && ... 51 Datafile(i,8) ~= 0 && Datafile(i,8) ~= 11 && Datafile(i,10) ~= 2) 52 typeObject = Datafile(i,8); 53 if(typeObject==1 || typeObject==2) 54 typeObject='3'; 55 colorObject = 'g'; 56 elseif(typeObject==3) 57 typeObject='4'; 58 colorObject = 'c'; 59 elseif(typeObject==4 || typeObject==5 || typeObject==11) 60 typeObject='1'; 61 colorObject = 'r'; 62 elseif(typeObject==6) 63 typeObject='2'; 64 colorObject = 'magenta'; 65 elseif(typeObject==9) 66 typeObject='6'; 67 colorObject = 'y'; 68 elseif(typeObject==7 || typeObject==8 || typeObject == 10) 69 typeObject='5'; 70 colorObject = 'b'; 71 end 72 app.roi(length(app.roi)+1).roi = images.roi.Rectangle(... 73 'Parent',app.UIAxes,'Position',[Datafile(i,3),... 74 Datafile(i,4),Datafile(i,5),Datafile(i,6)],'EdgeColor',... 75 colorObject,'LineWidth',app.lineWidth,'LabelVisible',... 76 'inside','UserData',typeObject); 77 end 108 78 end 79 if((dimension−2)>=((app.validateFrame(1)+1)*app.reduction)) 80 %There are still more images in this folder 81 app.validateFrame(1) = app.validateFrame(1) +1; 82 else 83 %No more images in this folder 84 app.validateFrame(2) = app.validateFrame(2)+1; 85 app.validateFrame(1) = 1; 86 end 87 cd(oldfolder); 88 end Appendix B Video selection Here the criteria for the selection of the videos among the train, dev and test set are explained. All the videos of the VisDrone dataset were analysed and checked to extract the following information: - Type of objects that appear - Type of view (angled or zenithal) - Static or moving camera - Additional regards of contrast, lighting, etc. - Amount of frames With these, a table, part of it seen on Figure 61, was constructed analysing for each video all these aspects. In it, it can be seen that for each video, the objects that appear, the movement of the camera, the orientation of the camera, and additional remarks are evaluated. The selection of which videos to validate with the GUI to then be used for train, dev and test set was based around trying, for the training set, to have the most diverse range of objects, as well as orientations and movements of the camera in order for the models to be more robust. In addition, videos where the lighting conditions were not good, or were recorded at night, or when the contrast was very high were also added as they contain interesting information for the model to learn. In general, the idea was to use the videos that contained the most information, for the trained model to be more robust, as well as to better evaluate the models in front of all types of data. After having selected all the videos to validate, it was also necessary to decide how to divide the videos among the train, dev and test set. A similar approach was used, by trying to have 109 116 47 fprintf(fileID,'%s',s); 48 fprintf(fileID,'\n'); 49 end 50 end Appendix D Datasets comparison To modify the datasets according to the histograms, the following code has been used: 1close all 2clear 3clc 4arrayPositionsDev = [1526 1886; 4829 5041;6214 6892;8400 8609;... 58610 8789;9673 9762;9763 9912;9913 10093;]; 6limit2 = 0; 7for i=1:length(arrayPositionsDev) 8limit2 = limit2 + (arrayPositionsDev(i,2)−arrayPositionsDev(i,1)+1); 9end 10 nofinal = true; 11 j=1; 12 i = arrayPositionsDev(j,1); 13 while nofinal 14 old = cd('images'); 15 A = imread(string(i)+'.jpg'); 16 maximum = max(max(A,[],[1 2])); %Reading the image 17 minimum = min(min(A,[],[1 2])); 18 %Modification of the colour histogram 19 B = 50+(A−minimum).*(150/(double(maximum)−double(minimum))); 20 cd(old); 21 old = cd('imagesContrast'); 22 imwrite(B,string(i)+'.jpg') 117 118 23 cd(old); 24 i = i+1 25 if(i>arrayPositionsDev(j,2)) 26 j = j+1; 27 if(j>length(arrayPositionsDev)) 28 nofinal=false; 29 else 30 i = arrayPositionsDev(j,1); 31 end 32 end 33 end Appendix E Collision prediction Here the code developed to implement the collision prediction algorithms are purported: 1% Function that returns a boolean indicating if two objects are 2%considered the same (1) or not(0) 3function [isInRange] = whithinRange(app,current,previous) 4% Here the parameters for what the same object is considered to 5% be are laid out. In this case, if one object is whithin the 6% ROI of the previous one, it is considered to be the same 7% object 8offset = 1; 9if(current(1)==2) 10 % As people(class 2) move fast relative to their ROI, this 11 %offset is set to facilitate detection 12 offset=2; 13 end 14 if(current(2)>=((previous(2)−previous(4)/2*offset)) && ... 15 current(2)<=((previous(2)+previous(4)/2*offset))) 16 if(current(3)>=((previous(3)−previous(5)/2*offset)) && ... 17 current(3)<=((previous(3)+previous(5)/2*offset))) 18 isInRange=true; 19 return 20 end 21 end 22 isInRange = false; 119 120 23 end 24 25 % Function to find if the object is present 1 frame before 26 function [previous] = findPrevious(app,current) 27 limit = size(app.previousObjects); 28 for i=1:limit(1) 29 % Check for previous objects of the same class 30 if(app.previousObjects(i,1)==current(1)) 31 % If whithin range, consider same object 32 if(whithinRange(app,current,app.previousObjects(i,:))) 33 previous = app.previousObjects(i,:); 34 return 35 end 36 end 37 end 38 previous=[]; 39 end 40 41 % Function to estimate the path of an object 42 function [] = findPath(app) 43 limit = size(app.currentObjects); 44 for i=1:limit(1) 45 previous = findPrevious(app,app.currentObjects(i,:)); 46 % If the object appears in the previous image 47 if(~isempty(previous)) 48 xNow = app.currentObjects(i,2)*app.imWidth; 49 yNow = app.currentObjects(i,3)*app.imHeight; 50 xBefore = previous(2)*app.imWidth; 51 yBefore = previous(3)*app.imHeight; 52 xSpeed = (xNow −xBefore); 53 ySpeed = (yNow −yBefore); 54 55 % Try to find object two frames before 56 prePrevious = findprePrevious(app,previous); 121 57 if(~isempty(prePrevious)) 58 x2Before = prePrevious(2)*app.imWidth; 59 y2Before = prePrevious(3)*app.imHeight; 60 xPoli = [xNow xBefore x2Before]; 61 yPoli = [yNow yBefore y2Before]; 62 else 63 xPoli = [xNow xBefore]; 64 yPoli = [yNow yBefore]; 65 end 66 % Polynomial fit of the two or three points 67 p = polyfit(xPoli,yPoli,1); 68 69 % Offset to avoid predicting paths of obects that are not 70 % moving. 71 spOffset = 0.1; 72 if(abs(xSpeed)>(spOffset*app.currentObjects(i,4)*app.imWidth)|| 73 abs(ySpeed)>(spOffset*app.currentObjects(i,5)*app.imHeight)) 74 x1 = linspace(xNow−app.currentObjects(i,4)*app.imWidth,... 75 xNow+app.currentObjects(i,4)*app.imWidth); 76 y1 = polyval(p,x1); 77 hold(app.UIAxes); 78 color = getColour(app,app.currentObjects(i,:)); 79 plot(app.UIAxes,x1,y1,color,'LineWidth',2); 80 ylim(app.UIAxes,[0 app.imHeight]); 81 xlim(app.UIAxes,[0 app.imWidth]); 82 hold(app.UIAxes); 83 % pahts(i) is a variable to store the positions and 84 % speed, as well as the curve of the predicted 85 % path. used if to disregard previous paths 86 app.paths(i).xspeed=xSpeed; 87 app.paths(i).yspeed=ySpeed; 88 app.paths(i).parameters = p; 89 app.paths(i).xposition = xNow; 90 app.paths(i).yposition = yNow; 122 91 app.paths(i).used = true; 92 app.paths(i).class = app.currentObjects(i,1); 93 else 94 app.paths(i).used = false; 95 end 96 else 97 app.paths(i).used = false; 98 end 99 end 100 end 101 102 % Function to show in the GUI or video the path 103 function [xout,yout] = drawLine(app,x,path) 104 if(x>path.xposition) 105 xout = linspace(path.xposition,x); 106 else 107 xout = linspace(x,path.xposition); 108 end 109 yout = zeros(1,length(xout)); 110 for i=1:length(xout) 111 yout(i)=path.parameters(2)+path.parameters(1)*xout(i); 112 end 113 end 114 115 %Function to warn of a detected collision 116 function [] = collisionDetected(app,x,y,path1,path2) 117 % Warn of a predicted collision being detected 118 app.CollisionwarningLamp.Color = [1 0 0]; 119 hold(app.UIAxes); 120 plot(app.UIAxes,x,y,'*','LineWidth',4,'Color','r') 121 hold(app.UIAxes); 122 [x1,y1] = drawLine(app,x,path1); 123 [x2,y2] = drawLine(app,x,path2); 124 hold(app.UIAxes); 123 125 plot(app.UIAxes,x1,y1,'LineWidth',4,'Color','r') 126 hold(app.UIAxes); 127 hold(app.UIAxes); 128 plot(app.UIAxes,x2,y2,'LineWidth',4,'Color','r') 129 hold(app.UIAxes); 130 end 131 132 % Function to find the intersection between two paths, 133 % if it exists within our bounds. 134 %Returns boolean collision, indicating if there is or not a collision, 135 %as well as the x and y of the collision if it exists 136 function [collision,xcollision,ycollision] = pathCollision(app,path1,path2) 137 try 138 syms x y 139 eqn1 = −path1.parameters(1)*x + y == path1.parameters(2); 140 eqn2 = −path2.parameters(1)*x + y == path2.parameters(2); 141 sol = solve([eqn1, eqn2], [x, y]); 142 xcollision = sol.x; 143 ycollision = sol.y; 144 145 if(~isnan(xcollision) && ~isnan(ycollision)) 146 collision = true; 147 return 148 end 149 catch 150 end 151 collision = false; 152 end 153 154 155 function [] = detectCollisions(app) 156 for i=1:length(app.paths)−1 157 if(app.paths(i).used) 158 for j=i+1:length(app.paths) 124 159 if(app.paths(j).used) 160 [intersection,x,y] = pathCollision(app,app.paths(i),app.paths(j)); 161 % Restrict collisions to the camera view only 162 if(x>0 && x<app.imWidth && y>0 && y<app.imHeight && intersection) 163 % Check if both objects direction is 164 %towards the intersection point 165 if (sign(app.paths(i).xposition−x)~=sign(app.paths(i).xspeed) && ... 166 sign(app.paths(j).xposition−x)~=sign(app.paths(j).xspeed) && ... 167 sign(app.paths(i).yposition−y)~=sign(app.paths(i).yspeed) && ... 168 sign(app.paths(j).yposition−y)~=sign(app.paths(j).yspeed) ) 169 % Not consider person to person collisions 170 if (not(app.paths(i).class==app.paths(j).class && ... 171 app.paths(j).class==2)) 172 collisionDetected(app,x,y,app.paths(i),app.paths(j)); 173 end 174 end 175 end 176 end 177 end 178 end 179 end 180 end 181 % Main function to find collision in a set of frames 182 function [] = collisionDetection(app) 183 init = initialFrame; 184 final = finalFrame; 185 for i=init:final 186 [name,num] = getName(app,i); 187 app.currentObjects = table2array(readtable(append(name,'.txt'))); 188 showImage(app,name); 189 if(~isempty(app.previousObjects)) 190 findPath(app); 191 detectCollisions(app); 192 end 125 193 app.prePreviousObjects = app.previousObjects; 194 app.previousObjects = app.currentObjects; 195 app.paths = []; 196 app.CollisionwarningLamp.Color = [0 1 0]; 197 imwrite(frame2im(getframe(app.UIAxes)), append('vid−',num,'.jpg')) 198 end 199 end