scieee AI-readable full text Open interactive document viewer

Focus detection and sharpness evaluation in keyframes containing faces

Sampedro Casis, Rodrigo

Abstract

In this work, a software tool to blur detection was implemented in order to select the best image-frame in a set of key frames. The main objective is to allow the detection and measurement of the blurring level of an image without human intervention, i.e. by artificial intelligence trained to detect blur. During the implementation of this Master Thesis, it was necessary to understand the concept of the blur, the causes and the different algorithms to detect local blur. This work uses multiple methods to detect local blur, analysing neighbour's results with different types of filters. Therefore, the solution is a local blur detector at pixel level that generates two images as output, one mask of blurred/sharped pixel areas, and a grey-image with the different levels of blur per pixel. However, the blurring detection is applied in 1D (one output per single pixel) losing its 2D position in the image but using the neighbouring pixels' information to convert this method in a 1.5D. On the other hand, the decision thresholds to classify the image as blurred or sharp were created by machine learning algorithm based on using Naïve Bayes techniques and Neural Networks solutions, to get a similar result to human blur compression. Finally the result is a stable software able to accomplish the set goals, with an efficiency similar to that of a human person classification.

Full text

MASTER THESIS TITLE: Focus Detection and Sharpness Evaluation in Keyframes containing Faces MASTER DEGREE: Master in Science in Telecommunication Engineering & Management AUTHOR: Rodrigo Sampedro Casis ADVISOR: Francesc Tarres Ruiz DATE: June, 28th 2017 Title: Focus Detection and Sharpness Evaluation in Keyframes containing Faces Author: Rodrigo Sampedro Caiss Advisor: Francesc Tarres Ruiz Date: June, 28th 2017 Abstract In this work, a software tool to blur detection was implemented in order to select the best image-frame in a set of key frames. The main objective is to allow the detection and measurement of the blurring level of an image without human intervention, i.e. by artificial intelligence trained to detect blur. During the implementation of this Master Thesis, it was necessary to understand the concept of the blur, the causes and the different algorithms to detect local blur. The first chapter summarizes the main causes of blur oriented to understand the difficulty of the problem and a brief introduction of state of the art in blur detection. The second chapter shows the first steps and problems encountered to understand the final solution adopted. Also during the second chapter, each partial-solution and their integration were explained in detail. Finally, in the third chapter, the results and conclusions of the work are explained and compared with other current research. This work uses multiple methods to detect local blur, analysing neighbour’s results with different types of filters. Therefore, the solution is a local blur detector at pixel level that generates two images as output, one mask of blurred/sharped pixel areas, and a grey-image with the different levels of blur per pixel. However, the blurring detection is applied in 1D (one output per single pixel) losing its 2D position in the image but using the neighbouring pixels’ information to convert this method in a 1.5D. On the other hand, the decision thresholds to classify the image as blurred or sharp were created by machine learning algorithm based on using Naïve Bayes techniques and Neural Networks solutions, to get a similar result to human blur compression. Thus, a large database with different types of blur and sharpness levels has been used with a ground-truth labelling by hand. Finally, to get a more precise result, a multiscale analysis of each image was implemented to solve false positives over textures or far-away objects, hence cleaning the noise the result. To conclude the result is a stable software able to accomplish the set goals, with an efficiency similar to that of a human person classification. CONTENTS INTRODUCTION ................................................................................................ 1 1. INTRODUCTION TO BLUR CONCEPT .................................................... 2 1.1. Objectives and Requirements ................................................................................ 2 1.2. Software Deployment ........................................................................................................ 2 1.3. DEFINITIONS AND IDEAS ........................................................................ 3 1.3.1. Causes and types ................................................................................................... 4 1.3.2. Textures, flat areas and blur regions ...................................................................... 7 1.4. State of Art ......................................................................................................................... 8 1.4.1. Types of Detectors ................................................................................................. 8 1.4.2. Techniques & ideas of blur detection ..................................................................... 9 1.4.3. Most Used Non Reference detectors ..................................................................... 9 2. BLUR FEATURES ................................................................................... 11 2.1. First approach to the problem ........................................................................................ 11 2.1.1. Single Feature ...................................................................................................... 13 2.1.2. Problems of Single variance model ...................................................................... 15 2.1.3. Feature Patch Concept ......................................................................................... 16 2.1.4. Improve results based on features or scale ......................................................... 18 2.2. Features ............................................................................................................................ 18 2.2.1. Feature 1: Variance Estimator .............................................................................. 19 2.2.2. Feature 2: Variance rate ....................................................................................... 20 2.2.3. Feature 3: Log Kurtosis ........................................................................................ 21 2.2.4. Feature 4 Power Spectrum trends ....................................................................... 24 2.2.5. Feature 5, 6, 7: Local Linear Filters ...................................................................... 25 2.2.6. Feature 8 and 9: Colour Saturation ...................................................................... 27 2.3. Importance of features .................................................................................................... 28 2.4. Ambiguous threshold ..................................................................................................... 29 2.5. Data Base ......................................................................................................................... 30 2.6. Scale join prediction ....................................................................................................... 31 2.7. Analysis of results ........................................................................................................... 33 2.8. Decision algorithms ........................................................................................................ 34 2.8.1. Naïve Bayes ......................................................................................................... 35 2.8.2. Naïve Bayes Implementation ................................................................................ 35 2.8.3. Neural Network ..................................................................................................... 38 2.8.4. Neural Network Implementation ........................................................................... 40 2.8.5. Combinational Result ........................................................................................... 44 2.9. Face analysis approach .................................................................................................. 44 3. RESULT AND COMPARATIVE ............................................................... 46 3.1. Multi-scale Results of my method ................................................................................. 46 3.2. Comparatives ................................................................................................................... 47 4. CONCLUSIONS ....................................................................................... 51 4.1. Algorithm conclusions .................................................................................................... 51 4.2. Knowledge and personal conclusion ............................................................................ 51 ACRONYMS .................................................................................................... 52 REFERENCES ................................................................................................. 53 ANNEX A ......................................................................................................... 55 1.1. Schedule of Thesis .......................................................................................................... 55 1.2. Code .................................................................................................................................. 56 1.2.1. Previous scripts .................................................................................................... 56 1.2.2. Final Code ............................................................................................................ 56 1.3. Hardware and simulation ................................................................................................ 58 1.4. Data Results ..................................................................................................................... 59 1.5. Data Base ......................................................................................................................... 59 ANNEX B ......................................................................................................... 61 1. DECISION ALGORITHMS ....................................................................... 61 1.1. Naïve Bayes Classifier Algorithm .................................................................................. 61 1.2. K Means Clustering Algorithm ....................................................................................... 61 1.3. Support Vector Machine Algorithm ............................................................................... 61 1.4. Linear Regression and Logistic Regression ................................................................ 61 1.5. Nearest Neighbours ........................................................................................................ 61 1.6. Artificial Neural Networks ............................................................................................... 62 1.7. Random Forests and Decision Trees ............................................................................ 62 1.8. Summary decisions ......................................................................................................... 62 1.1. Visual comparative of learning methods ...................................................................... 62 2. NAÏVE BAYES IMPLEMENTATION ........................................................ 63 2.1. Creation of Big files ......................................................................................................... 63 2.2. Implementation of all database ...................................................................................... 64 2.3. Detection of different types of blur ................................................................................ 64 2.4. Results by scale............................................................................................................... 65 3. NEURAL NETWORK IMPLEMENTATION .............................................. 65 3.1. Properties and tuning of Neural Nets ............................................................................ 65 3.2. Visual representation of Neural structure ..................................................................... 66 4. RESULTS ANALYSIS ............................................................................. 68 4.1. Final Scale results over Database include training ..................................................... 68 ANNEX C ......................................................................................................... 73 1. VISUAL COMPARATIVE ......................................................................... 73 2. SOME IMAGES RESULTS ...................................................................... 75 Introduction 1 INTRODUCTION The main purpose of this project is to solve an automation problem in selecting key frames for online video platforms. Some companies like Ugiat Technologies [1] have algorithms to segment scenes and detect sets of representative key frames, these key frames are useful for online platforms but currently, the selection of the best key frame continues to be manual. One important parameter to select the most appropriate key frame is a low blur effect or low blur-motion in the faces as well as smiles and open eyes. The main work of this project is to develop an algorithm for evaluating the sharp areas of the image and create metrics to decide the best image in a set, based on sharp image information. This document explains the causes and analyses the different ways to detect blur with an algorithm using low-level features that detects and decides whether a pixel is sharp or blurry. On the other hand, the algorithm allows to assess blur/sharp information creating one blur-grey-image letting know if regions of interest like face, smile or eyes are un-blurred and the level of blur of each one. During the realization of the project various methods, strategies and technologies of current interest in the automation of tasks, such as training and machine learning have been used to optimize and improve the results. Finally, once the algorithm detects the blurred areas, a qualitative, quantitative and comparative measure of the results has been made to know if the result of the software fulfils the requirements and whether objectives have been achieved. 8 Focus Detection and Sharpness Evaluation 1.4. State of Art Studies on blur regions detection and characterization of un-sharp have become one of the important research branches since image processing started. In order to improve zoom images, de-blur image or compensate blur-motion some strategies of detection, classification and restoration had been created. Currently continues to improve driven by the digitization of content, the multimedia boom of the internet and the increase of capacities in consumer electronics such as smartphones. There are different types of algorithms depending on complexity requirements and time response and others that need references or training images. Mainly the most widespread algorithms are based on grey analysis but there are a few algorithms based on colours analyses. The common use of the digital camera at end of 90's and 2000’s, popularized algorithms for focus detection (based on reference detection), just as smart phones have popularized image enhancement, compensation function and classification in 2007. The need to measure the introduction of blur in compression algorithms, the use of super-resolution techniques combining multiples sharp images and the human visual perception models in the current devices have exponentially increased the number of publications and new methods, parameters and comparative databases of blur detectors over last 5 years, understanding it as a hot topic with research and development. 1.4.1. Types of Detectors Usually, the algorithms are classified by the complexity, which is related to their consumption of resources. In blur detection methods, this classification is summarized under the necessity or not of having references (multiple relative’s images) to create a metric value:  FR (Full Reference metrics), original image is compared with previous or predefined image to know if the original is better/worse than reference. These metrics are easy to compute (less resources) and not require training for decision, very useful for videos or compression blur detection.  NR (Non Reference metrics), does not need reference information, requires more complex algorithms and trained decision makers. These type of algorithms are more similar to human vision perception but they need good databases adapted to the specific problem for training.  RR (Reduced Reference metrics), use some available features extracted from previous reference as edges to compare with actual image. It is a trade-off between FR and NR, allow to implement metric with high time requirements like camera focus detection/correction. Example safe statistics during some photograms, compare and decide based on previous data. Focus Detection and Sharpness Evaluation 9 As project’s requirement, it is necessary to detect sharp/blur on generic images, based only on one key frame, this work uses Non Reference (NR) metrics not needing reference images. 1.4.2. Techniques & ideas of blur detection As I mentioned before, the blur is very similar to an average filtering or Gaussian filtering, one of the first types of techniques for detecting blur is very similar to the method most used to fix it, blind image de-convolution. Gaussian/PSF deconvolution techniques were created in 70’s for astronomical images and improved in 90’s. These types of methods are based on recovery of the PSF (Point Spread Function, explained 1.5.1) to restore the image. Many of these methods [3] based on PSF function and de-convolution or Gaussian deprocessing, need great resources, long computing times and often they need reference image to restore original. Before the complex process, the blur can be measured based sigma value of gaussian convolution for the specific PSF. Low DoF (depth of field) methods, are based to detect photography technique, where usually one object is focused near the centre and surrounding pixels are out of focus. This technique uses frequency and spatial comparisons using wavelet transform, creating a DoF indicator based on the ratio of wavelet coefficient in high frequencies. This type of detectors [4] are not a general blur detector for blur detection on commons images. Low directional high frequency energy methods [5], are methods used to measure the blur motion based on evaluate the high frequency energy and calculate the direction of the motion of an image. The idea is to define the energy as sum of squared derivative of image and the concept of high frequency energy decreased incomparably along the direction of the motion in blurred image. Edge sharpness analysis methods [6] are techniques based on getting the Edge of the image (related with high frequency) and create parameters or coefficients based on statistics or measures over the edges. This is the main type of technique that is used in this document, because allows to use different types of methods over the same input (edges image), usually have low processing time requirements. Finally, there are extra techniques based on frequency phase [7], different types of transforms [8] and combination of the previous types which currently are not the hot spot for development but some of they are used in this software. A good comparison of most common methods can be found in this publication [9]. 1.4.3. Most Used Non Reference detectors Within the framework of non-reference and mainly in Edge Sharpness analysis, there are different math-statistics models for detecting blur: 10 Focus Detection and Sharpness Evaluation  Variance metrics: flat and blurred regions have low variance between pixel information, these type of metric measure the variance to get a flatnesscoefficient where best focussed images get greater intensity variations than blurred images. This models [10] measure the variance of the histogram of edge pixels images (measure wide of normal histogram).  Autocorrelation metrics: autocorrelation function (ACF) is the inverse Fourier transform of the power spectrum, ACF will contain sharpness information and smooth regions, result in a low broad ACF peak at blurred images [11].  Edge Histogram entropy: anisotropy can be measure as the entropy evaluated at different directions. Anisotropy decrease as more degradations are added to the images (more blurred per example) [12].  Histogram frequency or spectral trends: blurred images have low power at high frequencies, the discrete cosine transform (DCT) coefficients and the trends of power spectrum derivative allows you to differentiate unfocused images.  Edge Width analysis: a sharp image have narrow edges, a blur image have wide edges, measuring the edge width is an estimate of how fuzzy an image can be [13].  Local edge kurtosis: similar to variance metric, allow to measure how peak is the histogram of edge pixels [14]. The relation between wide and high of histogram.  Derivative magnitude statistics: use Gradient magnitude and Laplacian magnitude as high pass filter. Accordingly, the distributions of the log gradient magnitude for blurred regions should have shorter tails than that for other regions. These detectors outputs are numeric parameters like statistics (mean, variance, maximum) or visual parameters of the relationship with its neighbours. Normally it is necessary to use functions that allow normalizing or dimensionless the parameter and adjust the results or adapting to the human perception model. Finally, almost the most used methods or estimators have been studied for the realization of this project, however only a few have been finally implemented, due to lack of resource, effectiveness or complexity problems. Moreover most part of the implementations, show the result parameter normalized (0-255) to show in a 2D image, a visual interpretation of the measure. 11 2. Blur Features 2.1. First approach to the problem This point is an explanation of the first strategy performed, tests and results obtained as the introduction for 2.2 the final procedure solution. As a first step in the realization of the project, a blur image detector based on derivative filters was performed. The first stages are responsible for importing the image, rescaling (if it exceeds the maximum size) and extracting the grey image. The software analyses image of 600K of the pixel (around 780x780 standard picture), if the size is greater, the image is scaled with the same proportion to 600K pixels of resolution. The software uses a bicubic interpolation in 2D with the nearest 4-by-4 neighbourhood that is the best approximation without artificial effects. Fig. 10 Most extended interpolation methods 1D and 2D. The conversion from colour image to grey image is based on luminance computed as: 𝐿𝑢𝑚𝑖𝑛𝑎𝑐𝑒=0.2989∗𝑅𝑒𝑑+0.5870∗𝐺𝑟𝑒𝑒𝑛+0.1140∗𝐵𝑙𝑢𝑒 (1) Fig. 11 Original (left) and grey-scale image result. The second step, extract the image’s edges, reduce noise with different filters to know which is the most appropriated for our case. Only the magnitude of the edge is useful for our case. Then gradient or laplacian filters are applied to extract the edge of the image, selecting a kernel size of 3x3 or 5x5 to reduce image’s noise and remove fiction 12 Focus Detection and Sharpness Evaluation edges. When and image is sharp the variance of edge’s pixels values get high results, when image is blurred get low results. As third step, an easy-dummy detector based on variance measure the level of blur, other parameters are collected to normalize the measure in step fourth. These extra parameters are related with area, brightness, level of decision etc. Variance (5) is a common an easy statistic parameter, but has problems with high-noisy images because noise’s power is related with variance, distorting the measurements. Thus, gradient filter is in general better than laplacian filter, because the second is more sensible to noise interference and only in low noise and high texture images laplacian filter get better results than gradient filter. The fourth main step is based on normalize and compare with the results of other images. As summary the process to get the edge and measures of blur based on variance of one image is: 1. Pre-noise filter, average filter 3x3, mode symmetric. 2. Select kernel size, Sobel technique with kernel of 3x3, 5x5, 7x7 and 9x9 based on image size (Normally 3x3 o 5x5). 3. Get derivative image in X axis and Y axis. 4. Sum both images as vector to get the module, only magnitude is interesting 𝑒𝑑𝑔𝑒𝑚𝑎𝑔=√𝑑𝑒𝑟𝑣𝑎𝑡𝑖𝑣𝑒𝑥2+𝑑𝑒𝑟𝑖𝑣𝑎𝑡𝑖𝑣𝑒𝑦2 (2). 5. Calculate grey-threshold based on Otsu’s method for mask edge area. 6. Calculate sum of pixel as pseudo energy 𝐸𝑖𝑚𝑔=∑𝑝𝑖𝑥𝑒𝑙𝑣𝑎𝑙𝑢𝑒 (3) and edge’s area as result of edge’s image binarization and dilate based on Otsu results. 7. The variance pixel value of edge’s image is normalized with the area of edges and pseudo energy. 𝑉𝑎𝑟𝑛𝑜𝑟𝑚=𝑣𝑎𝑟𝑖𝑎𝑛𝑐𝑒∗𝐸𝑖𝑚𝑔 𝐴𝑒𝑑𝑔𝑒 (4), in order to compare image with different quantity of edges and edges intensity. 13 Fig. 12 Sobel derivative image (left), normalized edge image (centre), edge mask area image (right), Gradient images (top), Laplacian images (bottom). This model based on variance allows to compare similar images or consecutive images in a video (reference method). The use of extra parameters related with size, edges’ quantity or edges’ area, compensate if the image has a low or high quantity of edges allowing to compare different types of images with similar noise and textures conditions. A second approach was based on edge’s width measures, blurred images have wider edges than sharp images, the laplacian filter is better to get a defined edge width. Some papers like [15] based on JNB (Just Noticeable Blur) technique was implemented during this project, but its complexity compared to statistical methods like the variance or kurtosis, forced to discard width methods. 2.1.1. Single Feature The first software test, made on C++ QT and opencv libraries show that after 15 test, the right approach to the problem is based only on gradient edge image variance. Therefore this method allows to compare images but not define a threshold that separates the different scales of blur of each image. In order to get a non-reference method, the original image has been blurred to compare it with itself. The idea is fansy, “blur” areas are similar after Gaussian filter, but focussed areas change, measuring the rate of changes on sharpness areas, the original image can be catalogued. The idea was proposed on “A Noreference Image Blur Metric Based on Two pass Edge Analysis” [16] based on width edge analysis, however, in my work, it is done with the variance rate change. After analysing the behaviour of 150 photos, it has been detected the existence of a range between 1-3 sigma as parameter of Gaussian filter that has different trends on blurred and sharped images. The procedure is based on the variance changes between original and digital blurred images. Comparing the variance changes between original and different levels of blur manage by gaussian filter’s sigma, the rate of change can be measured. 14 Focus Detection and Sharpness Evaluation The trends show that blurred images have a lower rate of change that sharpened images. In flat or blurred areas do not significantly change the values of the regions and only slightly modifies their variance. Fig. 13 Process to get variance rate of change. On base of results, a classification threshold can be defined. In figure 14, 100 images analysed show original focus images red, 0.8 sigma yellow, 1.2 sigma green, 1.6 sigma blue and 2.4 sigma purple. For values higher than 1.2 sigma human vision detect the image like blurred. Fig. 14 Rate of change Variance at different blur level, when image is blurred. The conclusion is that this feature apparently is quite useful to evaluate between focused or totally unfocused photos, it can also be used to analyse which photo is better, but it does not end up being completely generic. When photos have too many textures get high results and flat images get low results due to the extra parameters that normalized variance are not enough to compensate the different textures environments. On the other hand the noise of the image must be low, because the model process can measure this noise like sharp edges, in conclusion, this algorithm only can used for binary classification sharpened/blurred images and are not enough for project’s requirements. 15 2.1.2. Problems of Single variance model There are some problems related with textures an noise when the variance is used as blur detector but exits more conceptual problems related with the way to analyse the images. Variance is a 1-D value, the position of pixels has been lost; the variance of global image evaluate all area of the image, an often some parts are sharpened and others are blurred. The main problem of the model is how to save 2-D information and how to analyse the different regions of the image. Fig. 15 Focus object (left) 7.1 mark vs Focus background (right) 8.8 mark. As the first solution is to analyse only the part of the image related to the edge mask, avoiding flat and blurred regions, apparently works except when the main object is out of focus and the background is focused. In figure 15, the background focused (right) get a better result than plants focused and background blurred (left). These type of problems do not meet the requirements of images with faces, where the face must be appropriately focused. The solution must detect the state of blur in hot areas, giving more importance to the purpose of the photo than to the context or background. One solution for both 2D and regions analysis is to mesh the image in small pictures and analyse each one separately and later calculate the global value based on the parts. The mesh strategy increases complexity and make difficult evaluate the blur level of the image, but can be implemented and used for face analyse putting one block per face. 16 Focus Detection and Sharpness Evaluation Fig. 16 Small block image analysed with different sigma of blur level. In figure 16 can be observed the trend of decreasing the sigma of the pixels (root of the variance), on top of image the same block with different level of blur is analysed (left-right with more blur), on the bottom of the histogram of each block (behind-front) show that blur block are less wide have a lower variance when the block in analysis is increasing its blur. Finally variance is an easy/simple parameter for detect blur within its limitations, however, there are other parameters that allow us to discern some more specific types of blur without having the defects of the variance. As a conclusion, the model of multiple estimators should be implemented to discern false positives and improve detection. 2.1.3. Feature Patch Concept In general, the problem of previous solutions is that is difficult to make something generic with a specific tool. In order to solve this problem in a generic form and getting the specific result, a modular software with different implementations is needed. The first modules should prepare the image for the measurements, the second perform and combine multiples blur measurements, the third analyse the results and decide the value of blur obtaining a 2-D image with results per pixel and finally a higher specific modules can analyse the face areas of the image based on blur/sharp results image. This solution (Fig.17) allows one form to make multiples measures by pixel, keeping 2-D information and evaluating each area of the image at pixel level. The first and second modules are already implemented in the former solutions, while the third modules are a more generic improvement on 2.1.1 and 2.1.2 solutions. The main problem of this solution is the need of greater amount of resources (multiple estimators) together with the requirement to use machine learning to obtain a reliable decision maker to analyse the multi-feature input pixel. 17 Fig. 17 Modular software structure. Patch concept is where an image of NxM pixels is transformed to A*A x N*M pixels, where A*A is the number of neighbours pixels (patch around one specific pixel). The patch pixels are in a vertical vector, one vector for each original pixel. These vectors are all concatenated forming a matrix of N*M columns, where each column is the original pixel and the neighbours pixels of the patch. This form allows to get all neighbours pixels in a vertical vector, another advantage is the fact of realise the operation measurement as vector operation. As all pixels have their own column, it allows to use GPU parallel processing like cuda to solve quickly the mathematical measure calculation. Fig. 18 Patch and features process transformation. 24 Focus Detection and Sharpness Evaluation Variance estimator is strongly related with edges areas, but kurtosis only appears where edges’ areas do not form part of textures (view Fig 29). 2.2.4. Feature 4 Power Spectrum trends Natural images have a similar frequency slope when power spectrum is analysed in a log scale. Due to the low-pass filtering characteristic of a blurred region, some high frequency components are lost and the amplitude spectrum slope of a blurred region trends to be steeper. Blur attenuates high frequency components and therefore makes the power spectra fall off much faster than its sharp counterpart. In David J.Field’s publication [17], explain the bases of the behaviour of natural images in power spectrum context. Computing the power spectrum of an image 𝐼 with size AxA by taking the squared magnitude after Discrete Fourier transform (DFT), where 𝐼(𝑢,𝑣) denotes the Fourier transformed image. Can be expressed the two-dimensional frequency in polar coordinates, 𝑢=𝑓 𝑐𝑜𝑠 𝜃 and 𝑣=𝑓 𝑠𝑖𝑛 𝜃 and construct 𝑆(𝑓,𝜃). 𝑆(𝑢,𝑣)=1 𝐴2|𝐼(𝑢,𝑣)| ; 𝑝𝑜𝑙𝑎𝑟 𝑐𝑜𝑜𝑟𝑑𝑖𝑛𝑎𝑡𝑒𝑠 → 𝑆(𝑓,𝜃) (13) 𝑆(𝑓)=∑𝑆(𝑓,𝜃)≅𝐾 𝑓−𝛼 0 (14) Where K is an amplitude scaling factor for each orientation and 𝛼 is the frequency exponent denominated slope of power spectrum. For natural images 𝛼≈2, in blurred images has large values between 2 and 10, i.e. lower amplitude in power spectrum. In [18] a similar technique based on average power spectrum was develop by Liu Xu in radians where average term n, is the number of different values of 𝜃, the code implemented in c was found and incorporated in to the project. 𝐽(𝜔)=1 𝑛∑𝑆(𝜔,𝜃)≅𝐾 𝜔−𝛼 0 (15) Fig. 30 Liu Xu, average power spectrum results [18], blue clear image, red blurred image. 25 In figure 30, can be observed the trend of blurred images (red) with a higher negative slope than clear images blue. This new feature analyse the patch image of each pixel getting a value of average power spectrum in log scale of neighbours pixels. (𝐼𝑜𝑟𝑖𝑔𝑖𝑛𝑎𝑙)𝑁𝑥𝑀𝑃𝑎𝑡𝑐ℎ 𝑡𝑟𝑎𝑛𝑠𝑓 → (𝐼𝑃𝑎𝑡𝑐ℎ)𝐴∗𝐴𝑥𝑁∗𝑀 For each column of 𝐼𝑃𝑎𝑡𝑐ℎ average spectrum power is calculated as: 𝐴𝑣𝑠𝑆𝑝𝑒𝑐𝑃𝑜𝑤𝑒𝑟= ∑log(𝐽(𝜔)) 𝜔 (16) Fig. 31 Log Average Spectrum Power (left), grey-spectrum feature combination (right). As show results, natural regions are clearer than the blurred (grey areas), or artificial regions (black areas). 2.2.5. Feature 5, 6, 7: Local Linear Filters Anther form to detect blur is using spatial filters such as Gabor [19] and Laplacian. They capture local band-pass or high-pass information that supplements frequency and gradient domain features in order to detect specific patterns. Gabor functions are a biological mechanism found in the visual cortex of mammalians, especially in primates to detect or discern particularly textures. Gabor’s filters are linear filters directly related with the same mechanism of human visual system (a large explanation in [20]). Based on a dataset images and ground-truth labels, blurred and unblurred patches can be analysed obtaining linearly independent filters to detect unblurred patches. 26 Focus Detection and Sharpness Evaluation The Image & Visual computing lab of University of Hong Kong [21] allows to download in some projects, the Gabor’s linear filters results after long learning process over one million of blurred and unblurred images. These filters are denoted as the generalized eigenvectors of eigenvalues which characterizes the clear areas. The linear filters result are provided in 11, 15 and 21 kernel’s size. Fig. 32 First 11 linear filters (top) [21], matrix of 46 eigenvectors (columns) compose by 121 coefficients (rows) in real value (left, bottom) and in normalized 0-255 (right, bottom). Per each scale, the results are 46 or more eigenvectors (where each one is a linear filter). These filters are non-intuitive and get edge-spatial bright results over sharped areas and dark pixels over blurred areas as figure 32 show. Fig. 33 Test image and first 29 linear filter’s results. The filters (eigenvectors) are given in eigenvalues order and the results’ source explains that the first five filters are most independent with gradient-based statistical measures like the previous features. As conclusion first, second and fourth eigenvector results are selected as feature 5, 6 and 7. 𝑓5,6,7= 𝐼𝑜𝑟𝑖𝑔𝑖𝑛𝑎𝑙∗𝐹𝑔𝑎𝑏𝑜𝑟 (17) 27 Fig. 34 Normalised filter’s results f4 (left), f5 (centre) and f6 (right). 2.2.6. Feature 8 and 9: Colour Saturation In [22] and [23] blur has been related to low colour saturation, thus in order to use this relation as blur feature, the minimum value of RGB (Red, Green, Blue values) normalised by colour’s saturation should be calculated for each pixel. 𝑆𝑝𝑖𝑥𝑒𝑙=1− 3 𝑅+𝐺+𝐵·min(𝑅,𝐺,𝐵) (18) Due to the different types of lighting, saturation intensity must be normalized using the highest value in the image. 𝐹8=𝑆𝑝𝑖𝑥𝑒𝑙−𝑆𝑚𝑎𝑥 𝑆𝑚𝑎𝑥 (19) Fig. 35 Feature 8 (left), feature 9 (centre) and f8-f9-original combination (right). For feature 8 saturation intensity image is enough but for feature 9 patch concept is used in order to get a mask of sharped areas and blur levels: (𝐼𝑠𝑎𝑡𝑢𝑟𝑎𝑡𝑖𝑜𝑛)𝑁𝑥𝑀𝑃𝑎𝑡𝑐ℎ 𝑡𝑟𝑎𝑛𝑠𝑓 → (𝐼𝑃𝑎𝑡𝑐ℎ)𝐴∗𝐴𝑥𝑁∗𝑀 28 Focus Detection and Sharpness Evaluation For each column of 𝐼𝑃𝑎𝑡𝑐ℎ saturation intensity patch is calculated as: 𝐹9=𝑚𝑎𝑥 [𝑆𝑝𝑖𝑥𝑒𝑙]𝑝𝑎𝑡𝑐ℎ −𝑆𝑚𝑎𝑥 𝑆𝑚𝑎𝑥 (20) 2.3. Importance of features Although many features have been implemented (9 features), all of them can be catalogued in 4 main types. The first statistical methods variance and kurtosis that detect the clear areas or textures, the second local learned linear filter that detects main unblurred patrons, third the spectrum features, that in a different form detect different levels of the blur as statistic features and finally extra-helper features. Fig. 36 Dragon-fly test image (left), multi features combination image (right) based on first three important types of features. These extra-helped features are not key features but help given extra information to improve the results. An example is to use more eigenvectors results as linear filters creating new features where the most part of the information is overlapping with the second type but other part it is new information. Other form to get extra features is the use of colour intensity features, the rate of change of variance and autocorrelations or entropy features. Most parts of extra-features like entropy or autocorrelation have not been implemented due to the possible scarce new information and the high computational resources consumption. The RAM and time required per each image analysis is a compromise that does not allow to add more features than the ones indicated. 29 Fig. 37 Row of beer and motion image (left), multi features combination image (right) based on first three important types of features. As show figure 36 and 37 focus, depth of field blur, motion blur, flat or texture areas appears with dark values while sharpened areas are bright areas. Fig. 38 Final multi-feature results per test images. Finally, the original test images with the 9 features results of features filters see Fig.38 as each feature give some context to blur/sharp areas. 2.4. Ambiguous threshold Ones the features images have been calculated, the blurred and sharpened areas must be defined. 30 Focus Detection and Sharpness Evaluation How to decide if the area is or is not diffused and the degree of it? On base to Fig. 37 and Fig. 38 a grey-image with the sum of different features can be made as blur level image result (Fig. 39). On the other hand, this image doesn’t define with notoriety the different regions and the value of them. The process of binarizing and dilate can be one option to get more defined areas but it is only a gross approach. Fig. 39 Blur sum combination (left), normalized image (centre), binarize image (right). Finally, a difficult multi-threshold based on multi-features should be implemented to decide the blurred or unblurred regions. The complex threshold is a difficult task to perform and practically impossible to optimize by a person. The solution is the use of machine learning where a set of data and the ground-truth with a classifier algorithm that defines the threshold to minimize the error on the training data set. If the database is sufficiently large and varied, the decision algorithm should be generic and robust. Naïve Bayes classifier is a simple probabilistic classifier based on Bayes’s theorem [24] commonly used for text categorization or medical diagnosis, implemented on most math software. On the other hand, neural networks [25] allows to classifier data on base a large data set with the same mechanism than our brain and also is implemented in most software. 2.5. Data Base In order to satisfy a large database, some blurred images from different public database have been included mainly from Hong Kong university (1000 labelled images) [21], UPC GTAV face database [26] (unlabelled images) and atresmedia web base images (atresplayer [27]). Fig. 40 Dragon-Fly test image (left), manual ground-true (right). 31 To simplify and generalize the process, the images have been quickly and manually catalogued, with errors of 15-25% in order to speed up and give robustness to the database. Also, flats region can be catalogued as sharp that decrease the analytic performance of accuracy but generalise the learning. Finally, a dataset of 1250 images have been used, 1000 for training, 200 for the test (mainly related with faces) and second test based on focus blur of 50 images. Our ground-truth labelled image is based on label sharped areas with 255 (white) value. The Hong Kong University’s database label blur areas. Therefore, it is necessary to obtain the negative image to adapt it to our system. Fig. 41 Hong Kong University’s blur database images and Gtav[26] faces and Atresmedia images[27] and web Hollywood images. Our dataset is centred on faces or tv-programs in order to learn and test our case of study measuring the real performance on key frames. Fig. 42. Database subsets distribution for train and test. 2.6. Scale join prediction In the introduction of the bases of blur (1.3.2), the problem of textures and low details resolution was described to know the problems to identify a region too far in the picture or too near with textures. Almost the image noise that interfered 32 Focus Detection and Sharpness Evaluation with the results creating false detection can be reduced using higher scales averaging the original noise. In order to solve the know problems and improve the level details of the algorithm, all features have been processed with 3 different path sizes of 11x11, 15x15, 21x21 pixels and both algorithm Naïve Bayes and Neural Network were trained on the different scales. Two different strategies have been implemented one easy combination of each scale named multi-scale zero that give a good grey sharp level to measure and other multi-scale based on iterative interference approximation to get a better binary result. 𝑀𝑢𝑙𝑡𝑖𝑠𝑐𝑎𝑙𝑒𝑧𝑒𝑟𝑜=𝑅11+𝑅15+𝑅21 3 (21) The multi-scale feature function found with the linear filter (point 2.2.5) is the best appropriated function to join the 3 results as iterative interference join. The model based on scale ambiguity of studies [32] [33] that use the Loopy belief propagation for approximate inference [34] to fuse information from different level to get a better solution. Reference [21] explains: “Specifically, a blur response 𝑏𝑖𝑠 is calculated on the patch centred at pixel 𝑖 at a particular scale 𝑠. The model connects the blur score of each pixel with those of the surrounding pixels. Inter-scale correlation is also built among patches centred at the same corresponding pixel in different levels. Fig. 43 Multi-scale graphical model [21] Given local blur response {𝑏 𝑖𝑠} in each scale s and for each pixel 𝑖, the total energy on the graphical model is expressed as: 𝐸(𝑏)=∑∑|𝑏𝑖𝑠−𝑏𝑖𝑠+1| 𝑖 3 𝑠=1 +𝛼∑∑∑|𝑏𝑖𝑠−𝑏𝑗𝑠| 𝑗 ∈ 𝒩𝑖 3 𝑠=1 +𝛽∑∑|𝑏𝑖𝑠−𝑏𝑖𝑠+1| 𝑖 2 𝑠=1 (22) Where 𝑏𝑖𝑠 is the score that we need to infer for each pixel. The first data term is unary to preserve the overall feature structure in image space. The second term is the spatial affinity, where 𝒩𝑖𝑠 is the four-neighbor set for pixel ‘𝑖’ in scale ‘𝑠’. 33 The last term is the inter-scale affinity, which bridges feature responses in different levels 𝑏𝑖𝑠 and 𝑏𝑖𝑠+1 have the same center pixel in two scales 𝛼 and 𝛽 are weights. All the terms in Eq. (22) use the ‘𝑙1’ norm distance for robust inference. Eq. (22) can be optimized via loopy belief propagation [34]. It starts from an initial set of propagation messages, and then iterates through each node by applying message passing until convergence. The final blur response map in the top layer is our result. “ 𝑀𝑢𝑙𝑡𝑖𝑠𝑐𝑎𝑙𝑒𝑖𝑡𝑒𝑟𝑎𝑡𝑖𝑣𝑒=𝑀𝑆𝑓𝑢𝑐𝑛𝑡𝑖𝑜𝑛(𝑅11,𝑅15,𝑅21,𝛼) (23) where has been use 𝛼=0.5 and 𝑅𝑥 result scale x. Finally an easy adaptation Eq.(23) of the iterative function which allows to get the best multi-scale interference result has been implemented with our results getting the improvement mentioned in the publication [21]. 2.7. Analysis of results As the groundtruth is not perfectly defined and it is possible to find blur zones within sharp regions, but it is not so common to find sharp areas in the blur label region, the following estimators have been defined capable of measuring the efficiency of the algorithm for its comparative. The most extended use to compare binary classification is precision, recall and accuracy. The pattern recognition precision is defined as the number of true positives over the number of true positives plus the number of false positives, i.e. is the fraction of retrieved true result that are relevant in the prediction. Also, is called positive predictive value (PPV), note that the meaning and usage of "precision" in the field of information retrieval differs from the definition of accuracy and precision within other branches of science and technology. Recall is defined as the number of true positives over the number of true positives plus the number of false negatives, i.e. is the fraction of relevant true results that are successfully retrieved, in binary classification is also named as sensibility and it can be viewed as the probability that a relevant document is retrieved by the query or a measure of the proportion of positives that are correctly identified. Fig. 44 Precision and Recall visual interpretation. 40 Focus Detection and Sharpness Evaluation specific algorithm to get the partial derivative of the error respect each weight to minimize the total error over all data of the training in the iteration. As conclusion changing weights and threshold, “learning process”, any nonlinear math function can be simulated. The number of neurons and the graph diagram of connections defines the precision of the network to approach the nonlinear function, the size of the database defines how of generic (near) is the solution to the real function. Finally, a neural network can be interpreted as a complex system that allows to define complex boundaries to classify the pixel making an approximation to the real function that separates the different output base on input. The use of neural networks have two benefits over other methods like Naïve Bayes, first it allows to split the database in multiple training steps reducing resource’s pic of RAM and second it gets more specific boundaries for classification with the same database. On the other hand, neural networks are more complex to develop, can memorize results instead of learning. Other characteristics are that increasing the number of iteration or the complexity of the net graph the result can be improved but exponentially increases the CPU resources, the time needed to train the net and create a big probability of overfitting (memorize results). 2.8.4. Neural Network Implementation The first approach of a neural network was made on 3 layers of neurons, a first layer with a high number of neurons to process the input, a second layer to reduce the outputs and finish the process and the output of the net with one neuron. The conclusion of experimental tests are that the use of more layers helps to direct the process or the intelligence minimizing errors and noise. If a neuron is not really necessary and does not contribute to the system its coefficient tends to be ignored (multiplied by zero). On the other hand, it has been experimentally detected that those solutions that decrease the number of neurons in each layer allow to obtain solutions more precise (low noise) with a less use of resources. For image processing, it can be understood that one horizontal pyramid layer where the number of neurons progressively decreases, acts in a similar way to multiple filters that extract and contrast the pertinent information to finally process the output based on summary and concrete information. This type of behaviour is similar to the Lateral Geniculate Nucleus (LGN) in the thalamus of the brain base on multiple layers which is responsible for the first processing of visual information to extract and helps the visual system focus its attention on the most important information. One of the most important parts in the training of neural networks is the algorithm used, how the data is used for training, number of iterations of each train and how the features are mixed. Some of this tuning work is summarised in Annex B. 3. 41 Training protocol The training has been made using 70% data to train, 15% to test and 15% for validations, all based on Matlab implementation algorithm. The network trains until get the maximum number of iteration (epochs) or gets a gradient error over validation set less than 1*10E-6. All structures are feed-forward multilayer neural networks, consecutive full connected layers with previous and next layer. In order to get the better solution in the minimum time, multiple neural networks have been developed and tested with some small subset in parallel over different machine hardware. After the first fit over all database of training, all solutions are evaluated by hand (visual analysis) using 5-15 test images. The best solutions have been the base for the second generation of networks, sometimes retraining the same network with different parameters like long batch iterations or using the same strategy with more neurons per layer or more layers, see Fig 51. Fig. 51 Strategy of networks schema solution. The first step to get the solution was developed with smaller subset of 10 million of pixels with low iteration number per subset around 50-100 iterations depending of the complexity of the net. The idea is to train with small subset to reduce the resources used, but trying to use low iterations to avoid overfitting. Approximately can be understood as try to obtain a similar result that 1 training of 100 million pixels with 1,000 iterations, using 10 subs-trainings of 10 million pixels with 100 iterations per subset. If the subset is not enough big or have much iteration networks only memorize and forget real knowledge of previous subsets trained. A more detailed explanation can be found on Annex B 3. Finally, if the strategy and conditions are adequate the solution is the knowledge acquired by the network, common to the different similar subsets, that allows to detect the blurring in a generic way. This procedure has been used due to the long time and resources necessary to train the entire database on each network. Before the first generation of schemas, the most appropriated strategies are used to create new net o retrain base on the same strategy but with more resources. This second generation has been trained with 50 million of pixel per subset and 200-1000 iterations over each subset. On first generation only trained on scale 11, the second generation procedure has been used for all scales. As result, only 42 Focus Detection and Sharpness Evaluation a few structures that work in scale 11 can be useful for scale 15 and 21. Finally, a new evaluation of second generation networks discards non-useful nets Figure 52. See more in Annex B 3. The final neural networks properties used are: Table 1 Neural Net Schema, Iteration training and error. It is denoted a specific good detection for each net, some cases conservative, optimistic in sharpness, clear binarization or grey solution. Finally, has been chosen a combined solution that provides a better measure in grey-level image. 𝐼𝑛𝑒𝑡=∑𝐼𝑛𝑒𝑡𝑗 𝑁 𝑗=1𝑁 (32) As can be observed, the best structure in the different scales using the same training has been the pattern of 106 neurons in 6 layers, first prediction in Fig. 52. The network diagrams and schemas can be found in Annex B point 3. Fig. 52 Original (first on left ), nets results left to right, combination result (last right) for each scale, 11, 15 , 21 up-down rows for two test images. Name Neurons/Layer Structure Iteration1 Iteration2 performance Net_11 106/6 [50,25,15,10,5,1] 50 800 0.7093 Net_11_2 134/5 [60,45,20,8,1] 70 1000 0.9393 Net_11_3 171/7 [80,40,20,15,10,5,1] 50 500 0.9474 Net_11_4 56/3 [50,5,1] 150 2000 0.8370 Net_15 106/6 [50,25,15,10,5,1] 50 800 0.8235 Net_15_2_1 96/4 [50,35,10,1] 200 1500 0.9657 Net_21 106/6 [50,25,15,10,5,1] 50 800 0.8401 Net_21_3 171/7 [80,40,20,15,10,5,1] 70 500 0.8588 43 Finally, the neural network gets a better visual result and grey-level solution than Naïve Bayes over the same database, reducing the number of required resources and being easy to implement in other languages like C/C++/Java/Python saving the structure and coefficients. As negative aspects, it needs a much more elaborated planning, knowledge and strategies, as well as a significantly longer training time than Naive Bayes. By other hand has more noise and “salt” effect result that result in a lower performance in the mask, i.e. lower values for performance, recall and accuracy than can be improved dilating and erasing. Fig. 53 Dragon-fly and rows of beers test image. First row grey image, net scale 11,15,21, second rows net zero combination, multiscale combination, final result, mask result. Fig. 54 Neural Net Precision-Recall, Accuracy –Threshold analysis. One unexpected result was the different rate of convergence at different scales. The different patch size changes the value of input data and finally the partial derivative when the network is learning. The experimental result shows as with the same training parameters patch of 11x11 and 21x21 have a similar rate of convergence and similar quality results, therefore the patch size of 15x15 have problems to converge (Fig.53 third image of second row), needing more iterations and getting a lower performance quality results than Naïve Bayes. This issue 44 Focus Detection and Sharpness Evaluation forced to analyse each scale solution as a single solution with different performance at different scales. Fig. 55 Final colour map sharp analysis of test image by neural network. 2.8.5. Combinational Result Finally, with a NBC and Neural Net result per each scale, there are two output per scale, one for nets results and other that is the combination of Naive Bayes and Neural network results. Also, there is two types of Scale join prediction that conclude with 4 possible results per image: Fig. 56 Combination Precision-Recall and Accuracy-Threshold analysis. 𝐼𝑐𝑜𝑚𝑏𝑠𝑐𝑎𝑙𝑒 =𝐼𝑛𝑒𝑡𝑠𝑐𝑎𝑙𝑒+𝐼𝑛𝑏𝑠𝑐𝑎𝑙𝑒 (33) 𝐼𝑅𝑒𝑠𝑢𝑙𝑡𝑎𝑑𝑜={𝐼𝑛𝑒𝑡𝑖𝑡𝑒𝑟𝑎𝑡𝑖𝑣𝑒,𝐼𝑛𝑒𝑡𝑧𝑒𝑟𝑜,𝐼𝑐𝑜𝑚𝑏𝑖𝑡𝑒𝑟𝑎𝑡𝑖𝑣𝑒,𝐼𝑐𝑜𝑚𝑏𝑧𝑒𝑟𝑜} (34) 2.9. Face analysis approach Finally, once the Blur detector algorithm is a generic form to get the level and mask over a generic image, the most popular detector of faces, eyes, nose and smiles can be implemented to get the hot areas of the images. 45 Fig. 57 Top results grey-scale, colour analysis Atresmedia image, focused faces foreground, blurred faces background. One possible and simple analysis is to assume that good photograms must have the hot areas in the 70-100 best sharps regions of the images, with more of 70% of the area as sharpened. Fig. 58 Face, eyes, smile, nose analysis of Sharp. 46 Focus Detection and Sharpness Evaluation One of the most important points when evaluating the sharpness of a face is a correct and level of sharpness of eyes and mouth. Photograms with eye or mouth fast movements, closed eyes or small smiles are not desirable. Therefore, as previously indicated in section 1.3.2, it is not important that flat regions are classified as blurred. What is really important is to avoid false positives, i.e. a high precision and specialization in the level of sharpness of the regions of interest. As can be observed the algorithm meets the requirements, allowing clearly identify, eyes, nose and mouth in the photographs. In Annex C point 2 a visual analyse of results can observe the tendency that those correct faces show similar levels of sharpness in hair, eyes mouth and beard. On the other hand, those images not so suitable but correct show a less sharpness in eyes and mouth than in hair and beards. Finally, if any eye is closed or not smiled the results are significantly smaller. 3. Result and Comparative The result of previous publications, Chakrabarti (FFT) [35], Liu [36], Su [37], Shi[14] has been downloaded with the same database of 1000 images[21] labelled for training. The main problem to compare the algorithms is that these paper didn’t explain which images are for training and which images are for test or validation. Therefore we have comparative results Precision-Recall extracted from [14] and the predictions or results on the same database of training and test, but we do not know how to differentiate them and an objective analysis cannot be made. A first visual comparison was performed and can be found in Annex C point 1. To get an objective comparison, the best method of previous publication has been download and compile and tested over our dataset of testing to compare. Finally, a non-objective analysis over the results of the data training has been developed to compare the result assuming certain risks as possible disadvantages of our algorithm in Annex B point 4. 3.1. Multi-scale Results of my method Over subset of Test1, mainly based on faces following mean results have been measured, using as mask threshold 0.5 in range [0,1] (binarize by round). Table 2 Multi-scale result Analysis. The results have low accuracy due to the fact that groundtruth label all face, head and shoulders as sharp. However, the reality is that only the elements of interest, Test1, th=0.5 P P-g R R-g S S-g A A-g Neural_zero 0.89 0.82 0.11 0.18 0.55 0.56 0.57 0.59 Combination_zero 0.86 0.77 0.28 0.32 0.58 0.59 0.62 0.63 Neural_iterative 0.84 0.72 0.30 0.32 0.59 0.59 0.63 0.62 Combination_iterative 0.81 0.75 0.46 0.47 0.63 0.63 0.68 0.66 47 eyes, ears, nose, mouth, hair and beard are truly classified as sharp. Measuring all face flat regions as an error. On the other hand, it is necessary to remember that the same labelling contains a manual error from labelling with an excess of sharp labelled. Fig. 59 Final Analysis Precision-Recall Accuracy. As can be seen, there is a problem with the Zero combination, the easy explanation is that zero combination is focused on grey-level of blur, therefore many pixel around 0.4-0.6 values are round to 0,1 and reduce the accuracy of the “binarization” but increase the qualitative result getting a sharp level. 3.2. Comparatives As it is reflected in [14], Shi method is the current best method published based on the database [21], also its source code is available in the image processing department of the Hong Kong University. An evaluation of the dataset of Test1 was carried out by Shi method, obtaining the following mean results for a threshold of 0.5 in the range [0,1]: Table 3 Test1 result for threshold 0.5, Shi and my combination iterative solution results. Test 1, thr=0.5 P P-g R R-g S S-g A A-g My Comb. iterative 0.81 0.75 0.46 0.47 0.63 0.63 0.68 0.66 My Net Zero 0.89 0.82 0.11 0.18 0.55 0.56 0.57 0.59 Shi 0.66 0.63 0.80 0.76 0.67 0.68 0.67 0.66 48 Focus Detection and Sharpness Evaluation Fig. 60 Comparison from [14] left and comparison using our dataset of test for Shi and my different result of this thesis right. The method proposed, improve the result over the test subset, respect other implementation like Shi, remember that the objective of the TFM is to get a blur analysis algorithm specialised for TV key frames, mainly based on faces. The precision and a conservative predictions are more important that the mean accuracy, avoiding generation of false positives. The visual analysis (see Annex C point 1) show a conservative trend in our method that can get lower accuracy on really blurred images. Nevertheless, there is a second subset Test2 base only in 50 images, mainly focus blur detection that has been analyse for both methods getting mean results for threshold 0.5 in the range [0,1] (mask by round function). Table 4 Test2 result for threshold 0.5, Shi and my combination iterative solution results. Fig. 61 Precision-Recall, Accuracy-Threshold analysis over subset Test2. As a conclusion, we can understand that the results based on Net Zero Eq.32 and Eq.21 result are better for measurements of levels of grey and get higher performance for the specific detection of blur in facial patterns. However, for a Test 2, thr=0.5 P P-g R R-g S S-g A A-g 𝑴𝒚 𝑪𝒐𝒎𝒃.𝒊𝒕𝒆𝒓𝒂𝒕𝒊𝒗𝒆 0.71 0.65 0.70 0.68 0.83 0.79 0.80 0.77 𝑴𝒚 𝑵𝒆𝒕 𝒁𝒆𝒓𝒐 0.80 0.68 0.33 0.36 0.73 0.71 0.74 0.72 Shi 0.53 0.51 0.89 0.85 0.89 0.86 0.67 0.66 49 more general use of the algorithm, the most appropriate solution is the combination Eq.33 using the iterative method Eq.23 between scales. Finally, a large time-lag has been detected in the time necessary for the processing of an image between Shi and the algorithm propose. Based on 250 results of Shi and my algorithm using the same machine to evaluate blur, it took 15% less average time for processing each image. Taking into account that both algorithms share several features (kurtosis, linear filters and spectrum filter) and the structures such as multiscale iterative analysis, it is concluded that the Shi implementation is not optimized and does not use GPU resources adequately, besides using certain computational features more expensive than those proposed by my method. I conclude that my proposal is based on a greater number of features that are simpler from the point of view of computations, which in turn have been processed in a more segmented and optimized way. Fig. 62 Comparative Result mask in difficult images for blur detection. Fig. 63 Mask comparative analysis over face images using our combination iterative method. 56 Focus Detection and Sharpness Evaluation  15th – 28th December, improve database and result.  20th of December – 30th January: Start to write Master Thesis Memory.  5th – 25th of January: Analyses results of NB.  5th – 25th of March: Analyses results of Neural Network.  April: Neural Network strategies and pacification.  1th – 15th May: Neural Network multi-scale solution.  15th – 25th May Final join solution.  June: End memory and result compilations. 1.2. Code This section gives a summary perspective of the structure and the main folder to run the proposed algorithm over a different data base. 1.2.1. Previous scripts The first scripts bases on scale, get grey images, edges and variance are Oldcode, Rodrigo and AnalysisofResultados folders. These folders contain different script to test concepts, blur digital image and results analysis to get patrons. They have common structure base on:  Function folder, Scale, edge filters, interpolation, thresholds derivatives and concrete parameters functions are storage inside.  Original Images folder or Test folder with image to analysis.  Result folder with the analytical o array results.  Source_dif_xx intermeddle folder where digital blurred image are storage to compare with original.  Face, smile, eyes and other folder for concrete result or image to analysis. 1.2.2. Final Code The final folder of script have some subfolder:  ./feature: it is the place where the nine features functions are.  ./IMG: it is the place where original images, ground truth and intermeddle results are storage.  ./IMG/groundtrue: collection of PNG ground truth images.  ./IMG/Original: collection of original images to analys.  ./IMG/Results: intermeddle storage of results.  ./IMG/Results/XX: storage place for image_file_feature where XX is the scale, an the name of file begins with F_originalname.mat.  ./IMG/Results/total: storage folder of scales for the concatenated files for NBC processing.  ./IMG/Results/total/XX: storage folder for Big files where XX is the scale of the file. 57  ./IMG/Results/true: storage the scale folder for ground truth base on sharp.  ./IMG/Results/true/xx storage folder for image_groundtruth.mat in the scale XX.  ./newImageData: folder where new database generate edge-dilate solution to make easy the manual labelling of ground truth.  ./Results: Storage folder for final results, bu scale, multi scale etc…  ./Results/XX: Combinational result of NB and Net solutions for scale XX.  ./Results/XX/net: Neural Network solution for scale XX.  ./Results/XX/nb: Naïve Bayes solution for scale XX.  ./Results/multiscale: storage the different multiscale solutions.  ./Results/multiscale/net: storage multiscale iterative solution base on Neural scale solutions.  ./Results/multiscale/net_zero: storage the simple multiscale join solution for Neural network scale solutions.  ./Results/multiscale/total: storage the iterative combinational multiscale join solution.  ./Results/multiscale/total_zero: storage the simple multiscale join solution for combinational scale solutions.  ./Test : image test folder.  ./Test/result: storage test solutions.  ./UGM multiscale iterative functions.  Files nb_sclae_trining.mat, net_sclae_tring.mat, storage of classification object by scale and trining.  Files Resultados_YYY, analysis result over YYY subset.  Learn_chineese_filter [14] filter from Hong Kong University. Main script to run:  CreationFeatures.m: analysis the image and generate feature files.  CreationFeatures2.m: analysis the ground truth and generate true files.  GenDatabase.m: generate edge-dilate files to label the images.  Compactresult_feature.m: allows to concatenate the result in bigfiles.  Compactresults_true.m: allows to concatenate the true files in bigtruefile.  multiScaleBlurInterference: Adaptation for iterative multiscale-join.  NeuralNetScript.m & SuperNeuralNetScript.m: define and train neural networks.  Retrain.m: allow to retrain neural object with new o the same data improving the convergence.  TestimageNetXX.m: where XX is the scale allows to show the result of nets.  ResultanalysisWithoutScale.m: allows to evaluate each independent solution per each scale.  ResultanalysisSclale.m: allows to evaluate the scale combination solution.  AnalysisOtherResuls.m: allows to analysis other paper results.  DemoTestanalysis.m: allow to test the algorithm with test demo images. 58 Focus Detection and Sharpness Evaluation 1.3. Hardware and simulation During the pre-analysis, simulations and training a high computational capacity was required, due to a large amount of data volume and the improvement of the results a basis of trial and error. Mainly a laptop and computer have been used, later the university server was joined and finally, all the devices were used with the objectives to obtain the best results in the fastest way (parallel analysis and strategies).  Main computer CPU AMD FX 8120 8 cores, 24 GB RAM, 256 +60 GB SSD, NVidia 720 4 GB.  Main laptop, CPU i7-4750HQ, 8 cores, 8 GB RAM 256 GB SSD, NVidia 740 2 GB.  Main Server Intel Xenon, 8 cores, 16 GB of RAM, 200 GB SSD.  Secondary laptop, i5 6500U, 4 cores 8 GB of RAM, 256 GB SSD.  Secondary computer, i5-4500U 4 cores, 12 GB RAM, NVidia Ge Force 720 2 GB.  Temporal Cluster, 3 computers of CPU AMD FX 8350 8cores, 16/32 GB RAM, 256 GB SSD, NVidia 920 4 GB, share at nights. Fig. 64 Computational Resources of the project. 59 Its main use has been nocturnal although in the last stages of the project they remained in operation several weeks. 1.4. Data Results In order to describe with greater clarity the different types of files generated, outputs, intermediates and classifiers a brief description has been made.  Features files: are the files that contain the 9 columns one per features and one row per pixel from original image, the mean size is around 15- 25Mbytes.  Truefiles: are the files that contain the ground truth, one column and one row per pixel from original image with a mean size of 250-500 Kbytes.  Big features files: there are multiples types depending of the number of files concatenated. Most typical 100,250,500 concatenated files one with all features files concatenated. Have Large size from 500 Mbytes – 19 Gbytes  Bigtruth files: there multiples types depending of the number of files concatenated. Most typical 100,250,500 concatenated files one with all ground truth files concatenated. Acceptable size of hundreds of megabytes.  Classifications files: are the learning classification boundaries for each scale base on big features files, big truth files analysis. The net object are one object with the model properties, training methods and init parameters, also has structure matrix that define the layer and coefficients and weight for the connection between neurons. Naïve Bayes object has statistic values that define the boundaries and allow to calculate the probability of belonging to a set.  Results files: are png image in grey scale. Typically there is for each image by scales (11,15,21) for neural solution, Naïve Bayes solutions, combination. Also, there is in multiscale solution for zero approximations, iterative approximation, based on neural scale solution and combination for neural + Naïve Bayes. 1.5. Data Base The database is formed by 1000 images from [21], where approximately 300 are mainly motion blur, 500 are mainly focuses blur and 200 are a mix of motion, focus and natural blur. Also, 100 images from gtav[26] have been added, these images have a good focus of face over blurred or flat background. 60 Focus Detection and Sharpness Evaluation Finally, 150 tv images from Hollywood and atresmedia[27], have been added, these images have a mix of all types of blur, with multiples faces on images and different backgrounds. The total database has a 41.32% of pixel labelled as sharp, including manual error and classification as sharp the flat areas inside a focus object. The Test 1 subset based mainly on face images has a 27.61% of pixel labelled as sharps including manual error and classification as sharp the flat areas inside a focus object. The Test 2 subset based mainly on focus images has a 43.39% of pixel labelled as sharps including manual error and classification as sharp the flat areas inside a focus object. 61 Annex B This annex explains certain decisions or strategies with better visualization of the data publish in the main document. Its objective is only to clear and explain the decisions taken. 1. Decision algorithms A brief description of the proposed methods to be used and the reason for the use of this method in the project. 1.1. Naïve Bayes Classifier Algorithm Naïve Bayes classifiers are a family of simple probabilistic classifiers based on applying Bayes’ theorem with strong (naïve) independence assumptions between the features. The Matlab implementation is easy to use and get a good result over the data set with fast and simple training, but need high resources of RAM. 1.2. K Means Clustering Algorithm Kmeans clustering is a technique for finding similarity groups in a data, called clusters, is often called an unsupervised learning, thus you don’t have to label the data the algorithm does it automatically. This method is mining not optimised for classification. 1.3. Support Vector Machine Algorithm SVM is a supervised machine learning algorithm that can be employed for both classification and regression purposes. The algorithm defines hyperplanes to separate intuitively the data point’s base on coordinates. The main problem is a very long time and high memory requirements to get performance similar to NBC or Neural Net over our problem. 1.4. Linear Regression and Logistic Regression Based on statistics line, planes, curves and cumulative logistic distributions can define boundaries to classified and make regression. The main problem is a low accuracy or difficult to learn in our problem of training. 1.5. Nearest Neighbours KNN is a non-parametric classification method that estimates the value of the probability density function or directly the a posteriori probability that an element x belongs to the class C from the information provided by the set of prototypes. This method is the third interested method to test, that finally cannot be tested by time reason during the thesis planning. 62 Focus Detection and Sharpness Evaluation 1.6. Artificial Neural Networks Neural Network is a different approach that using multiples types of layers, connections and models of the artificial neural model together with backpropagation algorithm which reduce the error of the results, have hard training strategy. 1.7. Random Forests and Decision Trees A decision tree is a decision support tool that uses a tree-like graph or model of decisions and their possible consequences, including chance-event outcomes, resource costs, and utility. As a method, it allows you to approach the problem in a structured and systematic way to arrive at a logical conclusion. The implementation of the training is not an easy way that together with height CPU requirements, long and complex training that crash matlab. 1.8. Summary decisions Table 4 Learning Machine method summary. 1.1. Visual comparative of learning methods Visual analysis of method from martin-thoma web blog (link) can be used to understand how different machine learning algorithm work. Name Algorithm Problem Status Naïve Bayes Matlab implementation Implemented K Means Clustering Minering method Discarded Support Vector Machine Long timing Discarded Linerar, Logistic Regression Bad accuracy Discarded Nearest Neighbours Not Implemented Neural Network Complex learning Implemented Random Forest, Decision Trees. High CPU requeriments Discarded 63 Fig. 65 Visual Interpretation of learning methods. 2. Naïve Bayes Implementation During the implementation of Naïve Bayes, multiple investigations have been carried out until the final solution is reached. The main problems encountered during the realization of the results are: 2.1. Creation of Big files To perform the training of the algorithm it is necessary to have the samples in the correct format, grouped in a vector. Therefore to facilitate the task of loading data and reduce read times as well as memory management has been chosen to previously concatenate in a file the necessary information for further analysis. Another element of interest is that the verification of the information is robust, checking that the lengths of ground truth and features are the same, as well as the elimination of format elements that affect the algorithms. A script is defined that loads in memory progressively a number of files of features and ground truth, generating one output file with all features and all ground truth 64 Focus Detection and Sharpness Evaluation responses and a list of errors if certain files have not passed the validations and they have been excluded. 2.2. Implementation of all database One of the biggest problems has been the generation and training of the most massive files, the bigfiles of each scale. Due to their size, it was necessary to use the combination and combination of several resources to obtain a computer with an effective capacity of 16-32 GBytes of ram and 100 GBytes of a 512 MB SSD disk used as SWAP. Finally with these capacities has been achieved peaks of 52-38 GBytes of RAM to process of 1250 features, with slight or null improvements respecting classifiers based on 750-900 files. The final solution has been finely chosen by a Multiclassifier strategy that allows you to calculate different classifiers in a simpler way, combine their results and in some cases getting improvements over the use of a single classifier. 2.3. Detection of different types of blur There are three main cases of photographs based on base data, focus blur, motion blur and a few of natural blur. As there is a great variety of each type can be made specific training with each type of blur. The results are classifiers able to detect blur and to differentiate its origin to allow to apply the corrective algorithm. However, this type of training on a smaller subdata base gets worse blur detection. On the other hand, great amount of images have a combination of different types of blur, which generate multiple detections with different origin. In [39], a simpler method than the proposed one in this thesis has been done to realize a concrete analysis of each type of blur using Naive Bayes like algorithm of training. As an interesting point, the use of a specialized database to detect flat zones and textures can help to declassify areas as blur and allowing improve the algorithm. However, given the burden of work on labelling this strategy has not been implemented. Finally, multiple classifiers with a biased but not specialized detection have been proposed, in order to obtain a combined result that equals or improves to a single implementation of Naive Bayes. In order to facilitate the processing of the base data and to have an incremental result, the Naïve Bayes training were carried out in different stages, skewed on a specific type of blur, with the aim of obtaining results equivalent to the total use of the database and use fewer resources. For each classifier the efficiency is evaluated in relation to the test database, obtaining in all cases very similar results and selecting the best case. It is explained on point 2.8.2 and Fig. 46. 65 2.4. Results by scale The result obtained for umbral 0.5 in range [0,1] (round function to create mask), the same process of fig 47, for all test image get an average of test subset: Table 5 . Analysis Result of Naive Bayes per each scale. Where P is precision, R is recall, S specificity, A is accuracy and the –g indicate the use of pseudo parameters based on grey level images. 3. Neural Network implementation The realization of neural networks has been based on a trial, error and improvement test. Multiple solutions have been trained and tested in parallel. Finally, only a small set of final solutions have been selected and combined to generate the neuronal response. 3.1. Properties and tuning of Neural Nets BFGS, Quasi-Newton Backpropagation [31] (secant methods) is an alternative to conjugate gradient methods for fast optimization that use less memory resources with little more time to converge. It is based on the basic step of Newton’s Methods where the Hessian matrix is update based on function on gradient to not spent high resources to compute real Hessian. Neural model, the activation function of the neuron most used is tangential sigmoid, in our case was replaced with Elliot sigmoid which allows to compute its derivate more quickly. The last steps of the net should be implemented by activation function from [0, 1] like logarithm sigmoid but finally, the training was made over [-1, 1] (by performance reasons) and solver making a translation over ground truth and output predictions. The Training was made in multiple steps by RAM limits constrains. Therefore is important to use a subset of the database with all the types of blur (good mix) and get enough files on the train to generalise the real solution. Under certain umbral of small subset or bad mix the algorithm doesn’t learn blur detection and try to memory or detect specific patrons of the subset. Divide the database in some subsets mean that some knowledge learn during the first subset are forgotten during the learning of other subsets. For this reason, the size and the mixture of the data are vital achieving homogeneous and incremental learning. From the Point of view of the analysis of results without combination for all the data over each scale get a mean of: Test1, thr=0.5 P P-g R R-g S S-g A A-g Scale 11 0.83 0.76 0.30 0.34 0.58 0.60 0.63 0.63 Scale 15 0.83 0.78 0.30 0.34 0.59 0.59 0.63 0.64 Scale 21 0.82 0.76 0.32 0.37 0.60 0.60 0.63 0.64 Combination 0.81 0.75 0.46 0.47 0.63 0.63 0.68 0.66 72 Focus Detection and Sharpness Evaluation Fig. 80 Shi [14] Scatter P-R. Fig. 81 Shi[14] Scatter P-A. 73 Annex C 1. Visual Comparative Visual comparative where clear areas are black and blurred areas are white. Each rows has original, groundtruth, combination zero, Chakrabarti[35], Liu[36], Shi[14], Su[37] results for visual comparative. 74 Focus Detection and Sharpness Evaluation 75 Fig. 82 Comparative result proposed algorithm test image, from left to right: original, groundtruth, combination zero, Chakrabarti[35], Liu[36], Shi[14], Su[37]. The best methods to measure grey-scale level are Su and our proposal, the best methods for mask areas are Liu, Shi and our iterative proposal (see fig 62). 2. Some images Results The following results are predisposed in a first rows like Eq.34 with the original image, net zero result, net iterative result, combination zero result and combination iterative result. The second row is the colormap net solution. Fig. 83 Result proposed algorithm test image. 76 Focus Detection and Sharpness Evaluation Fig. 84 Result proposed algorithm test image Fig. 85 Result proposed algorithm test image. 77 Fig. 86 Result proposed algorithm test image. Fig. 87 Result proposed algorithm test image Fig. 88 Result proposed algorithm test image 78 Focus Detection and Sharpness Evaluation Fig. 89 Result proposed algorithm test image Fig. 90 Result proposed algorithm test image Fig. 91 Result proposed algorithm test image 79 Fig. 92 Result proposed algorithm test image Fig. 93 Result proposed algorithm test image