scieee AI-readable full text Open interactive document viewer

Migration of a stereoscopic camera system from Matlab to the TMS320DM814x DaVinci platform

Fité Sànchez, Joan

Abstract

The maintenance of the railways is done at night in a noisy environment. A system is needed to prevent the occupational accidents while the train tracks are restored. The master thesis is focused the migration of a stereoscopic camera system developed in Matlab to an embedded environment. A stereoscopic camera system is capable of measure the distance of an object using the images of two different cameras knowing the separation between them. If an object is detected inside a specific area with a distance lower than a threshold, an alarm is generated. The embedded system used is the TMS320DM814x DaVinci board. The platform includes an ARM Cortex A8 and a floating point DSP C674x that makes it suitable for digital video systems. To execute the migration, the C6EZACCEL would be used. It interacts between the ARM and the DSP that has its own library. The C6EZACCEL has several functions implemented but also allows to create new ones. The author of the master thesis has optimized a part of the Matlab algorithms from an initial execution time of 8 seconds to 94,7ms.

Full text

MASTER THESIS TITLE: Migration of a stereoscopic camera system from Matlab to the TMS320DM814x DaVinci platform MASTER DEGREE: Master in Science in Telecommunication Engineering & Management AUTHOR: Joan Fité Sànchez DIRECTOR: Antoni Gelonch SUPERVISOR: Albert Puig DATE: July 9th 2012 Títol: Migration of a stereoscopic camera system from Matlab to the TMS320DM814x DaVinci platform Autor: Joan Fité Sànchez Director: Antoni Gelonch Data: 9 de juliol de 2012 Resum El manteniment del ferrocarrils es produeix de nit en ambients sorollosos. És necessari un sistema que previngui els accidents laborals mentrés les vies dels trens són restaurades. La tesina del màster es centra en la migració d’un sistema esteroscòpic de càmeres desenvolupat en Matlab a un sistema encastrat. Un sistema estereoscòpic de càmeres és capaç de mesurar la distància a un objecte utilitzant les imatges de dos càmeres diferents separades a una distància coneguda. El sistema encastrat utilitza la placa TMS320DM814x. La plataforma inclou un ARM Cortex A8 i la DSP C674x de coma flotant que el fa perfecte per sistemes digitals de video. Per dur a terme aquesta migració s’ha utilitzat el C6ACCEL que interactua entre el DSP i el ARM. El C6ACCEL té varies funcions implementades però també permet crear de noves. L’ autor de la tesina ha optimizat una part dels algoritmes de Matlab d’un temps inicial de 8 segons fins a 94,7 ms. Title: Migration of a stereoscopic camera system from Matlab to the TMS320DM814x DaVinci platform Author: Joan Fité Sànchez Director: Antoni Gelonch Date: July 9th 2012 Overview The maintenance of the railways is done at night in a noisy environment. A system is needed to prevent the occupational accidents while the train tracks are restored. The master thesis is focused the migration of a stereoscopic camera system developed in Matlab to an embedded environment. A stereoscopic camera system is capable of measure the distance of an object using the images of two different cameras knowing the separation between them. If an object is detected inside a specific area with a distance lower than a threshold, an alarm is generated. The embedded system used is the TMS320DM814x DaVinci board. The platform includes an ARM Cortex A8 and a floating point DSP C674x that makes it suitable for digital video systems. To execute the migration, the C6EZACCEL would be used. It interacts between the ARM and the DSP that has its own library. The C6EZACCEL has several functions implemented but also allows to create new ones. The author of the master thesis has optimized a part of the Matlab algorithms from an initial execution time of 8 seconds to 94,7ms. INDEX INTRODUCTION .............................................................................................. 3 CHAPTER 1. WORK ENVIORNMENT ............................................................. 4 1.1. TMS320DM814X ................................................................................................................4 1.1.1. Features .................................................................................................................5 1.1.2. ARM Cortex-A8 ......................................................................................................6 1.1.3. DSP C674x ............................................................................................................6 1.2. Personal Computer ...........................................................................................................7 CHAPTER 2. C6EZACCEL .............................................................................. 8 2.1. Advantages and disadvantages ......................................................................................8 2.2. Devices supported ..........................................................................................................10 2.3. DSP kernel .......................................................................................................................11 2.3.1. Function IDS ........................................................................................................12 2.3.2. Extended Input Arguments ..................................................................................12 2.3.3. Memory management ..........................................................................................13 2.4. Using C6EZAccel in an ARM application ......................................................................14 CHAPTER 3. TECHNIQUES TO REDUCE THE EXECUTION TIME .............. 16 3.1. Algorithms .......................................................................................................................16 3.2. TI DSP Libraries and intrinsic operations ....................................................................19 3.3. Software Pipelining ........................................................................................................20 3.4. Compiler ..........................................................................................................................21 CHAPTER 4. STEREOSCOPIC CAMERA SYSTEM VISION ......................... 22 4.1. Stereo vision camera vision system .............................................................................22 4.2. Block diagram .................................................................................................................23 4.2.1. Transforma ..........................................................................................................24 4.2.2. Block search ........................................................................................................25 4.2.2.1. Edge search .........................................................................................................26 4.2.2.1.1. Gaussian filter ..............................................................................................26 4.2.2.1.2. Spline interpolation .......................................................................................27 4.2.2.1.3. Derivative filter..............................................................................................27 4.2.2.1.4. Logic block ...................................................................................................27 4.2.2.2. Lineal interpolation ...............................................................................................28 4.2.3. Search of candidates ...........................................................................................28 4.2.4. Disparity analysis .................................................................................................29 CHAPTER 5. RESULTS OF THE MIGRATION ............................................. 30 5.1. Evolution of the execution time in an algorithm ..........................................................30 5.2. Errors due to the migration ...........................................................................................32 5.3. Final results ....................................................................................................................32 CHAPTER 6. CONCLUSIONS ....................................................................... 35 6.1. Reached targets ..............................................................................................................35 6.2. Future work lines ............................................................................................................35 REFERENCES ............................................................................................... 36 APPENDIX A. IMPLEMENTATION OF THE C6ACCEL IN THE MAIN CODE 37 A.1. ARM main code ...............................................................................................................37 A.2. Implementing a new DSP kernel....................................................................................40 APPENDIX B. COMPILER INTRINSICS INSTRUCTIONS ............................. 45 APPENDIX C. COMMERCIAL BROCHURE OF THE SYSTEM ..................... 47 Migration of a stereoscopic camera system from Matlab to the TMS320DM814x Davinci platform 1 CONTENTS OF FIGURES Fig. 1. 1 Block diagram of a DaVinci Processor. ................................................ 4 Fig. 1. 2 TMS320DM814x [1] ............................................................................ 6 Fig. 1. 3 High level C6000 DSP Architecture [1] ................................................ 7 Fig. 2. 1 Schematic of the intercommunication between the DSP and ARM [2] . 8 Fig. 2. 2 Processor load of the SoC as function on the running mode [2] .......... 9 Fig. 2. 3 Block Diagran view of calling multiple DSP kernels in C6Accel [2] .... 10 Fig. 2. 4 Structure of an ID function [3] ............................................................ 12 Fig. 2. 5 Schematic of a DSP function call [3] [4] ............................................. 14 Fig. 3. 1 Comparison of lineal execution (a) and pipeline execution (b) ........... 20 Fig. 4. 1 Schematic of an stereoscopic camera system ................................... 22 Fig. 4. 2 Images from the master and slave cameras ...................................... 23 Fig. 4. 3 Block diagram of the whole stereoscopic camera system .................. 23 Fig. 4. 4 Correction of a biconvex distorsion .................................................... 24 Fig. 4. 5 Before (a.) and after (b.) of the biconvex correction distortion ........... 25 Fig. 4. 6 Block diagram of the Block Search .................................................... 25 Fig. 4. 7 Block diagram of the Edge Search .................................................... 26 Fig. 4. 8 Input and output images of the Gaussian filter................................... 27 Fig. 4. 9 Output image of the Lineal Interpolation ............................................ 28 Fig. 4. 10 Disparity image generated with the disparity map........................... 29 Fig. 5. 1 Evolution of the execution time .......................................................... 31 Fig. 5. 2 Call sequence of the functions........................................................... 34 CONTENTS OF TABLES Table 1. 1 Main features of the TMS320DM814x .............................................. 5 Table 2. 1 List of devices able to run the C6EZAccel [3] ................................. 11 Table 2. 2 Codification of the category of function [3] ...................................... 12 Table 3. 1 Clock cycles of each .M unit ........................................................... 16 Table 5. 1 Percentage of optimization ............................................................. 31 Table 5. 2 Errors on each function due to the migration .................................. 32 Table 5. 3 Execution time of each function in the different stages ................... 33 Table 5. 4 Functions on the call sequence ...................................................... 33 Table 5. 5 Execution of each call sequence option .......................................... 34 Migration of a stereoscopic camera system from Matlab to the TMS320DM814x Davinci platform 3 INTRODUCTION The master thesis is involved in the Argus product (Active Reverse Guide System) of the IDNEO Technologies where the author has been working for a year collaborating in the designing of the hardware as well of the software. Argus, a railway project, is a stereoscopic camera system able to detect any object in front of it in a certain distance. The system is composed by two cameras that are continuously acquiring images and it is installed in the railway engine. Argus prevents the occupational accidents while the train tracks are restored. The maintenance of the railways is done at night in a noisy environment. The developed system advises with a buzzer and/or a led when an object is inside or cross the train tracks. The system needs to process the images on real-time, so the execution time of the algorithms become important. The master thesis is focused on the optimization of the algorithms to reduce the execution time. As a complex project, it is developed by different departments and people. The algorithms have been designed in the Matlab software by the image processing technicians. The author of the report was the responsible to migrate and optimize a part of these algorithms from the Matlab environment to an embedded one. In Chapter 1, we explain the TMS320DM814x, a TI evaluation board composed by a DSP and an ARM processor. We use an evaluation board to optimize the algorithms while the hardware department finishes the designing of the embedded system. The features of the computer used to evaluate the execution time of the Matlab algorithms are also explained. Chapter 2 contains information of the C6Accel API that allows the memory share between the ARM and the DSP and the parallel working. The techniques used in the algorithms to reduce the execution time are presented in the Chapter 3. In Chapter 4, we explain the Argus system. We divide the Argus system in three main blocks. The first one gets the images from both cameras, detects the edges and interpolates the images. The second block processes the edges and determines if they are common in both images or not. The third block makes a disparity analysis and determines if inside a specific region there is an object or not. Although the report is centered in the optimization of the first block, the author also collaborates in the other ones. The results of the optimization are presented in Chapter 5, which includes an evolution of a function from the Matlab environment to the embedded system. We calculate the execution time of each function in the ARM and DSP of the block 1 and decide the best call sequence to reduce even more the time. To sum up, Chapter 6 details the targets reached and future work lines. Fig. 2. 3 Block Diagran view of calling multiple DSP kernels in C6Accel [2] The previous schematic (Fig. 2. 3) shows to possible ways to run an application from the ARM and DSP. The Application 1 makes “n” C6Accel calls from the ARM to the C6Accel API, adding “n” overhead to the execution time of the application. On the other hand, the Application 2 is more efficient than the Application 1. The Application 2 makes a single call to a DSP kernel and then inside the DSP makes several calls to functions. The waste time for the interaction between the ARM and the DSP is reduced with the Application 2. In our case, we choose the way of Application 2. 2.2. Devices supported There are different two-core heterogeneous SoC processors from Texas Instruments that support the C6EZAccel. The table below shows these devices, specifically the ARM+DSP ones which run Linux on the ARM; the yellow one is the selected for the project. Migration of a stereoscopic camera system from Matlab to the TMS320DM814x Davinci platform 11 Table 2. 1 List of devices able to run the C6EZAccel [3] TI Device Number ARM Core Type DSP Core Type Version OMAP-L137 ARM926EJ-S TMS320C674x fixed and floating point DSP v1.x or earlier OMAP-L138 ARM926EJ-S TMS320C674x fixed and floating point DSP v1.x or earlier OMAP-L138 ARM926EJ-S TMS320C674x fixed and floating point DSP v1.x or earlier OMAP3530/25 ARM Cortex-A8 TMS320C64x+ fixed point DSP v1.x or earlier DM370 ARM Cortex-A8 TMS320C64x+ fixed point DSP v1.x or earlier DM6467 ARM926EJ-S TMS320C64x+ fixed point DSP v1.x or earlier DM8168/C6816X ARM Cortex-A8 TMS320C674x fixed and floating point DSP V2.x or later DM8148 ARM Cortex-A8 TMS320C674x fixed and floating point DSP V2.x or later 2.3. DSP kernel The DSP has implemented an algorithm with several kernels ready to be invoked from the ARM with the C6Accel API, but maybe the user needs to create his/her own kernels. Instead of using the implemented ones of TI, we decide to develop most of them. The C6Accel provides an algorithm with a large number of kernels. The algorithm implements the XDAIS interface (eXpress Dsp Algorithm Interface Standard), helpful to create and delete instances of algorithm. Moreover, the algorithm also implements the iUniversal interface that provides a description of the functions and arguments to be used by the algorithm. 2.3.1. Function IDS Each kernel of the XDAIS algorithm has a unique function ID that the codec can identify. The list of the functions ID is in the header file iC6Accel_ti.h at the C6Accel directory (ti\sdo\codecs\C6Accel). This function ID is composed by 32 bits: Vendor Field for customer added custom kernel Field to identify type of DSP function Field for function ID for kernel to be executed on DSP Fig. 2. 4 Structure of an ID function [3] The first field (8 bits) is used to identify the vendor ID that in the case of TI is 0x01. The next field (8 bits) identifies the category of function being executed as the Table 2. 2 below indicates. Table 2. 2 Codification of the category of function [3] XX01XXXX DSP Library XX02XXXX IMAGE Library XX03XXXX MATH Library XX04XXXX ANALYTICS Library XX05XXXX MEDICAL Library XX06XXXX POWER CONTROL Library XX07XXXX AUDIO SPEECH Library The third field (16 bits) is reserved to identify the kernel that is to be executed on the DSP. 2.3.2. Extended Input Arguments The extended input arguments structure carries information such as the number of functions being called in that particular API call and an array of function structures listed below. iC6ACCEL_InArgs( Int size; Int Num_fxns; FXN_struct fxn[MAX_FXN_CALLS]; } CODEC_InArgs; Migration of a stereoscopic camera system from Matlab to the TMS320DM814x Davinci platform 13 struct FXN_struct{ XDAS_Int32 Fxn_ID; Int Param_ptr_offset; }FXN_struct; Each one of the function has its own parameter structure defined in the iC6ACCEL_ti.h interface header file. An example of a parameter structure is shown below where InArrID1 and OutArrID1 are integer buffers and Col is an integer scalar. struct IMG_median_3x3_8_Params{ unsigned int InArrID1; unsigned int OutArrID1; int Col; }IMG_median_3x3_8_Params; All vectors to be passed to the functions are passed using the inBuffs and outBuffs of the Universal process API calls. Each function parameter structure contains IDs that are responsible to identify the correspondence between the inBuffs and outBuffs shared and the function argument. 2.3.3. Memory management As we said before, the application code runs on the ARM while the codecs run on the DSP. The DSP and ARM exchange information using a shared memory in the DDR2 defined in the CMEM module. The DSP processes buffers and data aligned contiguously in memory while the ARM can work on fragmented buffers thanks to its MMU (Memory Management Unit). The best way to create a aligned contiguously memory is using the function Memory_alloc() provided by TI. The function defines memory blocks on the memory region defined in the CMEM module (by default the start address is 0x96C00000 and a maximum size of 20MB). If the programmer uses other functions to reserve memory, as for example “malloc”, the C6Accel could not be able to translate between the physical to virtual address, making impossible the interaction between ARM and DSP [5]. 2.4. Using C6EZAccel in an ARM application The implementation of a new DSP function involves different files as the schematic Fig. 2. 5 shows. In this section, we briefly explain the content of each file. We do not include any one of the files where the functions ID are defined. In the Appendix A is included all the steps that the user has to follow to success when a new DSP function is defined. Fig. 2. 5 Schematic of a DSP function call [3] [4] The appmain.c file is the responsible to allocate in memory all the buffers, to create the c6accel handle and of course to invoke the functions. The main code cannot invoke a DSP function directly. We need to call what we call “C6accel function”. They are defined in the c6accelw.c The C6accelw.c file contents all the C6Accel functions. A C6Accel function adapts all the parameters to fit in the iUniversal framework implemented in the XDAIS. The C6Accel functions always have the same structure: the c6accel handle, input variables and output variables. The input variables are encapsulated in the input buffers while the output variables in the output buffers. There are up to fifteen input buffers and others fifteen for the output buffers. All the buffers need to be defined and assigned to one of these fifteen. Even if we want to return a single value, we need to spend a buffer of one position. Once we define the buffers, we must assign the function ID and call the universal_process (c6accel.c). Migration of a stereoscopic camera system from Matlab to the TMS320DM814x Davinci platform 15 The c6accel.c file includes the function universal_process that is the one that discerns between the different libraries. The algorithm applies a mask to the function ID to determine which one of the libraries should call. In the library file (c6accel_stauplib.c), we apply another mask to determine the function to call. All the parameters are checked before we invoke the DSP function. The DSP function file (Function1.c) runs the entire implemented algorithm. The DSP function must be defined as void, they cannot return a value. All the C6accel functions returns an error code, helpful to determinate what is the cause of a possible error.  _EOK (0): No error happens.  _EFAIL (-1): Error appears when invoke the Codec Engine interface. This error often is caused if the buffers/vectors being passed to the codec are not assigned as contiguous memory. It can also occur if the application makes an asynchronous call to C6EZAccel when there is already a pending asynchronous call.  _PARAMFAIL (-6): Error due to invalid parameters. This error occurs when the parameters passed do not satisfy the parameter specifications of the underlying kernel.  _FXNIDFAIL (-7): Error on function ID passed. This error appears when the application passes a wrong function ID to the codec. In such case, please verify if the function ID being passed that is defined in the application codec interface header file iC6accel_ti.h. If the DSP returns a value different from zero, the C6Accel will understand that an error has happened and it will not allocate the data in the buffers. CHAPTER 3. TECHNIQUES TO REDUCE THE EXECUTION TIME There are different techniques to optimize your algorithms and reduce the execution time of the application. First of all we explain techniques to be applied in the algorithms that are useful in all the architectures (not only for the C6000 family). Each one of them has a numeric example to show the real effect when they are applied in an algorithm. A second block of techniques relative how the libraries and intrinsic instructions of TI could reduce the execution time. The software pipelining concept is also explained to improve the efficiency of the application. The chapter is concluded with a description of the compiler used by TI and which is the best “level of optimization” option to achieve the best performance. 3.1. Algorithms One of the first optimizations in a system is in the manner that the algorithms are implemented. The strategies presented below are efficient when the algorithms are invoked so many times, as for example to manipulate an image of 752x480 (360.960 pixels) stored in an array of 8 bits.  Use the properly size of variables for each case. The programmer often declarates an integer variable as int (32b), neglecting if a short (16b) or a char (8b) variable is enough. The Table 3. 1 shows the required clock cycle by the .M for each operation. For example if we want to implement an algorithm that multiplies the pixel value by a constant, we obtain the next execution times (only is taken into account the multiply operation): Table 3. 1 Clock cycles of each .M unit Operation Operations/Clock cycles Execution time of the example (f=500MHz) 32bx32b 1 721,92 us 16bx32b 1 721,92 us 16bx16b 2 360,96 us 8bx8b 4 180,48 us Migration of a stereoscopic camera system from Matlab to the TMS320DM814x Davinci platform 17  Reutilization of common expressions and avoid unnecessary intermediate variables like the example below shows: In the CODE A, the CPU executes four adds and three assignments or loads. On the other hand, in the CODE B, the CPU only executes two adds and two loads (we can exchange f to a in CODE B). If this piece of code is executed in each pixel of our image (752x480), the CODE B executes 721.920 adds less than CODE A and 360.960 loads. If all the variables are char (int8) and taking into account that in one cycle of clock the system can add up to 4 operations and the DSP is running with a frequency of 500MHz then: Cycles of clock A=(4*752*480)/4 + (3*752*480)=1.443.840  2,88ms Cycles of clock B=(2*752*480)/4 + (2*752*480)=902.400  1,80 ms  Reorganize the operands of an operation. Mathematically, there is no difference between the CODE A and CODE B below. If we look careful what the system does in both blocks some differences appears. CODE A a=b*c*(d+e) The “b” variable is moved to a register and then is multiplied by the “c” variable. The result is storage in a temporally register. Then “d” is loaded into a register and added to “e”. The temporally register is multiplied by the result of the add between “d” and “e”. The last step is to copy the result of this multiplication to the “a” variable. CODE B a=(d+e)*b*c First “d” is loaded into a register and then is added to “e”. The result of the adding is multiplied by “b” and the result of this operation is multiplied by “c”. The last step is to copy the result to the “a” variable. The CODE A needs four loads to a register, two multiplies and one addition. On the other hand, CODE B needs only two loads, two multiplies and one addition. a=b+c d=b+c-e f=d+e CODE A a=b+c d=a-e f=a CODE B  Change multiplications/division by adds and shifts as for example: 2*x  x+x or x<<1 4*x, 8*x  x<<2, x<<3 x/4  x>>2  Extract the maximum operations from inside the loop to outside it as the example below shows: In the CODE A, we increment the “i” variable by 1 in each iteration. Then we multiple this variable by the number of rows when we access into the cell array. On the other hand, CODE B is more efficient because it avoid a multiply in each iteration, incrementing “i” by row instead of by 1. For example this technique was used in the derivative filter (explained at 4.2.2.1.3) obtaining an important reduction of the execution time from 5,4 ms to 0,2 ms.  Hardcoded functions. The typical function in digital processing is the convolution between a signal and a filter. Usually the programmer develops a function where the signal and filter are passed as parameters. Using this strategy, the programmer obtains a flexible function that could be invoked in different system. Otherwise, this is not the optimized one. In a typical convolution function, the system has to access to the memory and load each cell of both vectors (signal and filter). The best option, If the coefficients of the filter are fixed and its length is not too big, is to use define directives instead of a vector as the example below shows. In code A at the main code, we declare a buffer called “filter” of 5 positions and we invoke the convolution function (conv). This function needs the input buffer or also called signal, the filter and the output as parameters. Inside the function, the system has to load the cell of the signal and the filter for each iteration and then load this result to the corresponding cell of the output. for (i=0; i<cols; i+=row) for (j=0; j<row; j++) array[i+cols]=…; CODE B for (i=0; i<cols; i++) for (j=0; j<row; j++) array[i*row+cols]=…; CODE A Migration of a stereoscopic camera system from Matlab to the TMS320DM814x Davinci platform 19 On the other hand, in code B we do not need to declare a filter at the main code. We invoke the convolution function (conv) which only requires the input buffer and the output buffer. Inside the function, the system has only to load the cells of the input buffer. The coefficients of the filter are hardcoded inside the function. Code A is flexible while Code B spends less execution time. 3.2. TI DSP Libraries and intrinsic operations Texas Instruments provides highly optimized DSP software libraries for the C6000 family of devices. These libraries incorporate many standard math, image or audio functions. The programmer could use these optimized libraries, reducing the execution time and the developing time too. On the hand, the C6000 family has intrinsic operations that are useful to optimize the code, allowing the programmer to directly invoke C600 assembly operations. Some examples of the intrinsic operations are presented below: _amem2, _amem4, _amem8  Loads and stores 2/4/8 bytes of memory. _mpy, _mpyus, _mpysu  Multiplies the 16 LSBs of one variable by the 16 LSBs of a second variable. 4.2.2.1. Edge search The edge search block is the responsible block to find the edges of the image. An edge is detected when there is change in the saturation value. In the Fig. 4. 7 below, the reader could see the block diagram of the edge search composed by a Gaussian filter with line decimation, a spline interpolation and a double derivative block. At the end, the logic block generates an image with the edges. Fig. 4. 7 Block diagram of the Edge Search 4.2.2.1.1. Gaussian filter A Gaussian filter is a filter that smoothes an image by a Gaussian function. In image processing is used to reduce the image noise and reduce the details. The visual effect of this technique is a small smooth blur of the image. Mathematically, a Gaussian filter is a convolution of the image with a Gaussian function and acts as a low pass filter, reducing the image’s high frequency components. The equation of a Gaussian function in two dimensions is at (4.1) equation. (4.1) Once the standard deviation is fixed, the coefficients of the filter can be found easily. The dimensions of the filter implemented are 3x3. Moreover, we decimate the lines of the image by a factor of 5 to reduce the computational cost. The resolution of the output image is 752x96. The Fig. 4. 8 shows the effects of the Gaussian filter. Migration of a stereoscopic camera system from Matlab to the TMS320DM814x Davinci platform 27 a). Input image (752*480) b). Output image of the gaussian filter (752*96) Fig. 4. 8 Input and output images of the Gaussian filter 4.2.2.1.2. Spline interpolation To detect the edge is needed to know exactly where the transition is done. Thus, we need extra pixels to determine when this transition is done thanks to the next two blocks (derivative filter). Instead of the linear interpolation, we use the cubic spline interpolation. The benefits of this interpolation resides that the value of the new pixel is determinated by the ten neighbors pixels of its line. The value of the pixel is obtained through the balanced value of these ten pixels. The new size of the output image is 2254x96. 4.2.2.1.3. Derivative filter The derivative filter is used to know exactly the pixel transition. We concatenate two derivative filters. The first derivative is useful to know the maximums and minimums. If we apply again a derivative filter over the output of the first derivative filter, knowing it as second derivative, we are able to detect inflexion points. 4.2.2.1.4. Logic block The logic block gets the first derivative filter and the second derivative filter to generate an image with the edges. We apply a filter to each one of the derivative signals (the 1st and the 2nd derivative). If both outputs of these filters are higher than a threshold, the pixel of the output image gets the value of the one from the first derivative filter. If not, the value of the pixel is zero. The size of the image remains equal to the previous blocks (2254x96). 4.2.2.2. Lineal interpolation A lineal interpolation of the original image after the correction of the distortion is needed to validate the common edges of the master and slave. We decide to use a lineal interpolation instead of the spline interpolation as we did before. Fig. 4. 9 Output image of the Lineal Interpolation The pixel value of the output image is generated through the two pixels close to this one. The new image (displayed in Fig. 4. 9) has a resolution of 2254x480. 4.2.3. Search of candidates Once we applied the block search in both master and slave image, we analyze their outputs in the Search of Candidates block. Briefly explain this block looks for common edges of both images and stores information as the distance of a first and a second closer maximum of an edge and the value of this maximum or also called disparity. The Fig. 4. 10 shows the disparity image from the disparity map of the original image got it from the camera. As we can see the railways are well detected and the distance to the objects is encoded with the pixel value. The further is the object, the darkness is the pixel. Migration of a stereoscopic camera system from Matlab to the TMS320DM814x Davinci platform 29 a). Original image from the camera (752*480) b). Disparity image (752*96) Fig. 4. 10 Disparity image generated with the disparity map. 4.2.4. Disparity analysis The disparity analysis is done to determine if an object is inside a region and activate an alarm. The cameras are allocated in a height of 2.5 m, so the point of view is not parallel to the ground plane. The first step to do in this block is to find the ground plane. It will allow us to change the cameras point of view through image processing. Once the perspective is changed, we can define a zone of interest of this image and process if this box is empty or not. If the number of found edges inside the box is higher than a threshold, an alarm will be generated. CHAPTER 5. RESULTS OF THE MIGRATION The results of the implementation from Matlab to the embedded system are presented below. First of all, we provide an example of the evolution of the time execution of a function. The reader could see the importance of the implemented techniques in an algorithm. Then the final results are presented. 5.1. Evolution of the execution time in an algorithm The most common function in signal processing is the convolution between two signals. Following this criteria, we choose the Gaussian filter algorithm as example of how the execution time can be decreased. The Gaussian filter algorithm, as the other functions, has been implemented first in Matlab. Matlab is a powerful mathematical software that can operate arrays easily. It is able to generate a C code from the Matlab code. However, this code is not efficient and the best mode to achieve the optimization is writing again algorithm in C. The size of the image has changed while the report of the master thesis was written. These modifications are done to obtain a better performance of the system. The department responsible for the development of the algorithms in Matlab decides that the best resolution is 752x480. However, the results shown in this section are obtained with the same size of the image: 1153x923. The Fig. 5. 1 displays the evolution of the execution time in the Gaussian filter. We can appreciate that the C code generated by Matlab spends 192,7ms. The code generated by Matlab has some features that makes it not suitable for our application:  Declarates all the variables as double (64 bits).  Makes a copy of the array to be sure that the size of the array is the required one and avoid memory access problems.  Checks the dividend in each division to avoid a division by zero. Once we see the poor efficiency of the C code of Matlab, we decide to write again the algorithm. We start the implementation of the Gaussian filter in the ARM side where the function has as parameters the input image, the filter and the output image. We obtain a considerable reduction from 192,7 ms to 154 ms. As the coefficients of the filter are constant, we decide to hardcoded them. This technique reduces the spend time in memory access. At this point the arrays are defined as integer 32b (int) when the maximum possible value after the filter fits in integer 16b (short). Using the properly size of the variables, the execution time is reduced until 68,8 ms. Migration of a stereoscopic camera system from Matlab to the TMS320DM814x Davinci platform 31 After that we implement the function in the DSP side obtaining an important reduction of the spend time by the function. Moreover if we use compiler intrinsic instructions, the execution time decreases until 18,2 ms. Fig. 5. 1 Evolution of the execution time The optimization level achieved until the “Assembler” point (18,2 ms) respect to the first version of the algorithm “C Matlab” (192,7) is about 91%. The Table 5. 1 presents the percentage of optimization in each step respect to the C code generated by Matlab. Table 5. 1 Percentage of optimization Percentage of optimization Algorithms 19,82% Hard code filter 25,22% Int 16 64,30% DSP 89,88% Assembler 90,56% The Gaussian filter is concatenated with decimation, so we decide to implement the decimation inside the Gaussian filter. At the end, the execution time of the Gaussian filter is 8,7 ms. Notice that the Matlab code has not implemented the decimation inside the algorithm. 5.2. Errors due to the migration The fact to migrate from the Matlab enviornment to the TMS320DM814x causes some errors. The Matlab code rounds the float values while the system truncates it. It provokes a number of erroneous pixels that need to be checked to determinate if the algorithm is affected or not. Although all the buffers and variables are defined as integers, there are operations that can introduce errors like the divisions or shifts. We have calculated the error on each block processig the same input buffer in Matlab and in the embedded system. We get the output buffer for each function implemented in the system and then we compare to the Matlab output. We define an erroneous pixel as the pixel that its value in Matlab differs from more than one its value in the TMS320DM814x. The Table 5. 2 presents the percentage of error in each function. We can observe that the error in each function alone is neglible, but if we concatenate the different blocks the error rises to 2 %. However the system is unaffected by this percentage of error. Table 5. 2 Errors on each function due to the migration Function Nº of pixels Erroneous pixels Error Gauss Filter 72.192 0 0,% Interp. Horizontal 216.384 30 0,014% DX filter 216.384 0 0% Arith. Block 216.384 303 0,140% Block search 216.384 4.370 2,020% Interp. Full 1.081.920 16 0,001% 5.3. Final results The execution time of each function of the block search (Gauss filter, interp. Horizontal, DX filter, Arith. Block) and the interpola full is detailed in the Table 5. 3. We can see the different development stages, from the Matlab enviornment to the DSP. The yellow cells indicate which side of the system (ARM or DSP) is selected to run each function. The average optimization level obtained is above 93% respect to the C Matlab code. Migration of a stereoscopic camera system from Matlab to the TMS320DM814x Davinci platform 33 Table 5. 3 Execution time of each function in the different stages Function Matlab (ms) C Matlab (ms) ARM (ms) DSP (ms) Optimization Transforma 1.536 483,5 35,41 36,2 93,09% Gauss filter 252 69,4 5,8 3,1 95,53% Interp. Horizontal 621,20 107,2 6,9 4,7 95,62% DX filter 920,3 10,1 5,4 0,2 98,02% Arith. Block 394 32,6 14,02 1,5 95,40% Interp. Full 3.360 80,9 9,4 15,3 81,09% The call sequence is composed by three blocks (see Table 5. 4) that are invoked twice. As we said in the Chapter 2, the C6Accel adds an overhead in each call to the DSP. When we run the block search in the DSP, we have to add an overhead of 5,8ms to the execution time. Table 5. 4 Functions on the call sequence Function Execution time (ms) Transforma 35,41 (ARM) Block Search 15,5 (DSP) Interpola full 9,4 (ARM) Once we choose the running side for each function, we can decide the strategy to obtain the maximum performance. As we comment in the chapter 2, the C6Accel allows a parallel working of both sides of the system. We execute the block search (gauss filter, interpolation horizontal, DX filter and arithmetic block) in the DSP and the interpolation full in the ARM. There are three different options of call sequence for our application as the Fig. 5. 2 shows. The first two sequences (a, b) execute first the algorithm of the master camera (orange) and wait until it has finished to start the algorithm of the slave camera (blue). The main difference between them is that in a) the system is set to work in synchronous mode, while b) in asynchronous mode. In synchronous mode, the ARM waits until the DSP has finished its function. On the other hand, in asynchronous mode, the ARM and DSP run in parallel. The third option is to combine the slave and master image algorithm to obtain the best optimization in the call sequence. The third option call sequence starts acquiring the images of both cameras and correcting the camera distortion of the master. After that, we invoke the block search of the master that runs in the DSP and the transforma function of the slave at the same time. The system is set to wait until the DSP finishes its algorithm to start the next block: interpola full of the master. After that at the same time, the interpola full of the master and the block search of the slave image starts. The interpola full of the slave image is also executed while the block search of the slave image is running. TRANSFORMA BLOCK SEARCH INTERP. FULL GET IMAGE TRANSFORMA BLOCK SEARCH INTERP. FULL GET IMAGE ARM side DSP side wait wait TRANSFORMA BLOCK SEARCH INTERP. FULL GET IMAGE TRANSFORMA BLOCK SEARCH INTERP. FULL GET SLAVE ARM side DSP side TRANSFORMA BLOCK SEARCH INTERP. FULL TRANSFORMA BLOCK SEARCH INTERP. FULL GET IMAGE GET IMAGE ARM side DSP side a) b) c) Fig. 5. 2 Call sequence of the functions The faster call sequence is the third option, as we can observe in Table 5. 5, with an execution time of 94,7 ms. This sequence can be done because the block search and the interpola full are independent functions. Table 5. 5 Execution of each call sequence option Call sequence Execution time(ms) Option a) 120,62 Option b) 101,57 Option c) 94,7 The running time of the system with the C Matlab in the ARM side for the call sequence is 1,587 s (793,8 ms for each camera). On the other hand, after the optimization, the execution time of the system is only 94,7 ms for both cameras. The level of optimization achieved is 94,03%. If we compare with the Matlab environment (8,003 s for each camera), the level optimization achieved is 98,81%. Migration of a stereoscopic camera system from Matlab to the TMS320DM814x Davinci platform 35 CHAPTER 6. CONCLUSIONS 6.1. Reached targets The target of the project has been the migration from the Matlab world to an embedded system of a stereoscopic camera system. This implementation has been done with the TMS320DM814x evaluation board of Texas Instruments. We have decided to use this board for the framework agreement between Texas Instruments and IDNEO. The board is equipped with an ARM and DSP that are easily intercommunicate through the C6Accel API. This API allows the memory share between them, parallel working and creates an easy codec interface to call functions running in the DSP from the ARM. The main problem of an image processing system is the execution time of the system. The idea of the Argus project is provide a safety tool to the railway employees. The execution time has been reduced with the different methods presented in the report. The methods used algorithms techniques that try to minimize the operations or memory accesses in each iteration of the loop. Others important tools to optimize the system are the software pipeline that is provided by the C6Accel and the powerful compiler that reduce and reorganize the code. The objective of the master thesis was to reduce the execution time since the images are captured to the edges are detected. The C code generated by Matlab spends 1,587 s, while the code implemented by the author spends only 94,7 ms, that means an optimization of 94,03%. If we compare with the execution time in Matlab (8.003 ms), the optimization level increases up to 98,8%. The problems found during the master thesis have been solved with the TI literature ([7], [8], [9], [10]) and the TI forum ([6]). The main problems are related to the memory management and the interaction between the DSP and ARM. 6.2. Future work lines A huge part of the code has been optimized but there is still code to optimize. Nowadays we are working on the optimization of the other algorithms to achieve a real time stereoscopic camera system. Now the system is able to detect and generate an alarm (buzzer and/or a led) if an object is placed in a determined zone. In a closer future, the Argus will split the detection zone in three zones to discern better the dangerous level. We are also working in the objects classification to determine if the object detected is a person or not. The last step will be the implementation of the system in a passengers train. // Create the parameter structure of the function DSP_mult2array_Params *DSP_mult2array_paramPtr; DSP_mult2array_paramPtr = pFnArray; //Check if the parameters are correct If( (DSP_mult2array_paramPtr ->array1_InArrID1>INBUF15) | ( DSP_mult2array_paramPtr->array2_InArrID2>INBUF15) | ( DSP_mult2array_paramPtr ->nelements) < 0 | ( DSP_mult2array_paramPtr->result_OutArrID1)>OUTBUF15)) return(IUNIVERSAL_EPARAMFAIL); // Call the implemented function else mult2array( (short*) inBufs->descs[DSP_mult2array_paramPtr - >array1_InArrID1].buf, (short*) inBufs->descs[DSP_mult2array_paramPtr - >array2_InArrID2].buf, DSP_mult2array_paramPtr ->nelements, (short*) outBufs->descs[DSP_mult2array_paramPtr- >result_OutArrID1].buf); } break; } return(0); } 4. The step 4 consist of create the C6Accel ARM side API call. The below code should be added in the “c6accelw.c” file. The API contains a C6accel handle argument in addition to all the arguments of the original DSP kernel call. All the C6Accel APIs return error codes, so the return values are always integers. In our case we have to included: int C6accel_DSP_mult2array( C6accel_Handle hC6accel, short* restrict ptr_array1, short* restrict ptr_array2, int npoints, short* restrict ptr_result ) { XDM1_BufDesc inBufDesc; XDM1_BufDesc outBufDesc; XDAS_Int32 InArg_Buf_size; IC6Accel_InArgs *CInArgs; UNIVERSAL_OutArgs uniOutArgs; Int status; Migration of a stereoscopic camera system from Matlab to the TMS320DM814x Davinci platform 43 /* Define pointer to function parameter structure */ DSP_mult2array_Params *fp0; XDAS_Int8 *pAlloc; ACQUIRE_CODEC_ENGINE; /* Allocate the InArgs structure as it varies in size*/ InArg_Buf_size= sizeof(Fxn_struct)+ sizeof(DSP_mult2array_Params)+ sizeof(CInArgs->size)+ sizeof(CInArgs->Num_fxns); pAlloc = (XDAS_Int8 *)Memory_alloc(InArg_Buf_size, &wrapperMemParams); CInArgs= (IC6Accel_InArgs *)pAlloc; uniOutArgs.size = sizeof(uniOutArgs); /* Set up buffers to pass buffers in and out to algorithm */ inBufDesc.numBufs = 2; outBufDesc.numBufs = 1; /* Fill in input/output buffer descriptor parameters and manage ARM cache*/ CACHE_WB_INV_INPUT_BUFFERS_AND_SETUP_FOR_C6ACCEL(ptr_arra y1,0,npoints*sizeof(short)); CACHE_WB_INV_INPUT_BUFFERS_AND_SETUP_FOR_C6ACCEL(ptr_arra y2,1,npoints*sizeof(short)); CACHE_INV_OUTPUT_BUFFERS_AND_SETUP_FOR_C6ACCEL(ptr_result, 0,npoints*sizeof(short)); /* Initialize the extended InArgs structure */ CInArgs->Num_fxns = 1; CInArgs->size = InArg_Buf_size; /* Set function Id and parameter pointers for first function call */ CInArgs->fxn[0].FxnID = MATH_MULT2ARRAY _FXN_ID; CInArgs->fxn[0].Param_ptr_offset = sizeof(CInArgs->size)+sizeof(CInArgs- >Num_fxns)+sizeof(Fxn_struct); /* Initialize pointers to function parameters */ fp0 = (DSP_mult2array_Params *)((XDAS_Int8*)CInArgs + CInArgs- >fxn[0].Param_ptr_offset); /* Fill in the fields in the parameter structure */ fp0->array1_InArrID1 = INBUF0; fp0->array2_InArrID2 = INBUF1; fp0->result_OutArrID1 = OUTBUF0; fp0->npoints= nelements; /* Call the actual algorithm */ if (hC6accel->callType == ASYNC) { /* Update async structure */ if (c6accelAsyncParams.asyncCallCount!=0) { status = UNIVERSAL_EFAIL; printf("Async call failed as %d are still pending\n"); } else{ /* Context Saving */ c6accelAsyncParams.asyncCallCount++; memcpy(&(c6accelAsyncParams.inBufs),&inBufDesc, sizeof (XDM1_BufDesc)); memcpy(&(c6accelAsyncParams.outBufs), &outBufDesc,sizeof(XDM1_BufDesc)); memcpy(&(c6accelAsyncParams.inArgs), CInArgs,sizeof(UNIVERSAL_InArgs)); memcpy(&(c6accelAsyncParams.outArgs),&uniOutArgs,sizeof(UNIVERSAL_O utArgs)); c6accelAsyncParams.pBuf = pAlloc; c6accelAsyncParams.pBufSize = InArg_Buf_size; /* Asynchronous Call to the actual algorithm */ status = UNIVERSAL_processAsync(hC6accel->hUni, &inBufDesc, &outBufDesc, NULL,(UNIVERSAL_InArgs *)CInArgs, &uniOutArgs); } } else{ /* Synchronous Call to the actual algorithm */ status = UNIVERSAL_process(hC6accel->hUni, &inBufDesc, &outBufDesc, NULL,(UNIVERSAL_InArgs *)CInArgs, &uniOutArgs); /* Free the InArgs structure */ Memory_free(pAlloc, InArg_Buf_size, &wrapperMemParams); } RELEASE_CODEC_ENGINE; return status; } Migration of a stereoscopic camera system from Matlab to the TMS320DM814x Davinci platform 45 APPENDIX B. COMPILER INTRINSICS INSTRUCTIONS Migration of a stereoscopic camera system from Matlab to the TMS320DM814x Davinci platform 47 APPENDIX C. COMMERCIAL BROCHURE OF THE SYSTEM The Appendix C shows the commercial brochure of the system used to promote it in conventions.