BAL IMAGES ANALYSIS FOR THEIR AUTOMATIC QUANTIFICATION A Degree Thesis Submitted to the Faculty of the Escola Tècnica d'Enginyeria de Telecomunicació de Barcelona Universitat Politècnica de Catalunya by Alejandro Campos Almazán In partial fulfilment of the requirements for the degree in Enginyeria de Tecnologies I Serveix de Telecomunicació – Sistemes Audivisuals ENGINEERING Advisors: Ferran Marqués Acosta, Montse Pardás Feliu Barcelona 21/06/2021 Final Report
Abstract Bronchoalveolar lavage (BAL) images are a medical test from which different pathologies can be extracted based on their cellular distribution. In the hospital La Vall d’Hebron technicians make manual count to determine this cell distribution. We did not have any labelled BAL image, because this was the first contact with the problem. In this project, maxtree-based solution is used to do the first segmentation, and then, a correcting process is carried out in order to correctly label 56 BAL images. With this small dataset, and taking into account the maxtree results in some aspects were not as good as we expected, we decided to test and train a CNN based in the U-Net. We applied specific techniques for small datasets and we tested different parametrizations of the network. Finally, we obtain 70% IoU global score approx. in the validation of the CNN.
1 Acknowledgements Carrying out this project has been a great experience for me, full of small successes and failures, of motivation and frustration at the same time, of better and worse moments and ideas. But especially, it was an experience full of learning, which result is not as important to me as everything I have learned along the way. I would like to express my deep gratitude to professor Ferran Marques and professor Montse Pardàs, my research supervisors, for trust me to carry out this project, their constancy, their patience guidance, their valuable and constructive suggestions, their support, encouragement and their great knowledge and experience. Without them, none of this would have been possible. Also; I want to thank Philippe Salembier for giving me the opportunity to work with the Maxtree software, the cornerstone of my project and for solving all my problems and doubts with extreme patience; Rocco Clemente Bonjour, for showing, providing and explaining me his code to generate tiles from WSI; Adrià Marcos Morales, whose help was essential to correct the output segmentations of the maxtree algorithm, thank you for being so patient and having spent so much time on my problem. And finally, I would like to express my very great appreciation to Ignasi Nogueiras, who helped me in the worst moments, with his best advices, his wisdom, his big patience, support and his unconditional friendship. For all this, my sincerest gratitude my friend.
2 Revision history and approval record Revision Date Purpose 0 09/03/2021 Document creation 1 24/06/2021 Document revision DOCUMENT DISTRIBUTION LIST Name e-mail Alejandro Campos Almazán [email protected] Ferran Marqués [email protected]du Montse Pardàs
[email protected] Written by: Reviewed and approved by: Date 21/06/2021 Date 24/06/2021 Name Alejandro Campos A. Name Ferran Marques Position Project Author Position Project Supervisor
3 Table of contents Abstract(.............................................................................................................................................(0! Acknowledgements(.......................................................................................................................(1! Revision(history(and(approval(record(....................................................................................(2! Table(of(contents(............................................................................................................................(3! List(of(Figures(..................................................................................................................................(5! List(of(Tables:(..................................................................................................................................(5! 1.!Introduction(............................................................................................................................(8! 1.1.!Introduction,to,the,problematic,.......................................................................................,8! 1.2.!Introduction,to,the,data,....................................................................................................,11! 2.!State(of(the(art(of(the(technology(used(or(applied(in(this(thesis:(.......................(12! 2.1.!BAL,Images,Analysis,..........................................................................................................,12! 2.2.!Semantic,Image,Segmentation,........................................................................................,12! 2.3.!Maxtree,...................................................................................................................................,12! 2.4.!Convolutional,Neural,Network,(CNN),..........................................................................,14! 2.4.1.!Unet)....................................................................................................................................................................)14! 3.!Project(Development(.........................................................................................................(16! 3.1.!Appropriate,Image,Selection,..........................................................................................,16! 3.2.!Maxtree-based,Solution,....................................................................................................,18! 3.2.1.!Image)Simplification)....................................................................................................................................)18! 3.2.2.!Macrophage)Detection)................................................................................................................................)21! 3.2.3.!Lymphocytes,)Polymorphonuclear)and)Eosinophiles)Detection).............................................)31! 3.2.4.!Mask)creation).................................................................................................................................................)38! 3.2.5.!Manual)Labelling)Corrections).................................................................................................................)39! 3.2.6.!VGG)Image)Annotator).................................................................................................................................)39! 3.3.!Convolutional,Neural,Network,,U-Net,..........................................................................,42! 3.3.1.!Introduction)....................................................................................................................................................)42! 3.3.2.!Network)Architecture).................................................................................................................................)42! 3.3.3.!Data)Augmentation)......................................................................................................................................)42! 3.3.4.!Transfer)Learning).........................................................................................................................................)43! 3.3.5.!Training)mini-batch)size)............................................................................................................................)43! 3.3.6.!Activation)Function).....................................................................................................................................)43! 3.3.7.!Classification)...................................................................................................................................................)44! 3.3.8.!Adam)Optimizer)............................................................................................................................................)45! 3.3.9.!Dice)Loss)Function).......................................................................................................................................)45! So,)the)generic)formula)to)compute)it.)[17])............................................................................................................)46! 4.!Results(....................................................................................................................................(47!
4 4.1.!Metrics,,IoU,...........................................................................................................................,47! 4.2.!Final,Results,..........................................................................................................................,47! 4.2.1.!Loss)Function).................................................................................................................................................)49! 4.2.2.!Optimizer).........................................................................................................................................................)49! 4.2.3.!Learning)Rate)Annealing)...........................................................................................................................)50! 4.2.4.!Number)of)epochs)........................................................................................................................................)51! 4.2.5.!Global)and)per)Class)IoU)Score)...............................................................................................................)52! 4.2.6.!Pixel)detection)IoU)score)...........................................................................................................................)53! 4.2.7.!Tricky)solution)...............................................................................................................................................)53! 4.2.8.!Maxtree)Results).............................................................................................................................................)54! 5.!Conclusions(and(future(development(..........................................................................(55! 5.1.!Conclusions,...........................................................................................................................,55! 5.2.!Future,Development,..........................................................................................................,55! 5.2.1.!New)techniques)to)classify)lymphocytes)............................................................................................)55! 5.2.2.!Improve)Transfer)Learning)......................................................................................................................)55! 5.2.3.!Improve)Class)Imbalance)..........................................................................................................................)56! 5.2.4.!Squamous)cellularity)detection)..............................................................................................................)56! 6.!Bibliography(.........................................................................................................................(57!
5 List of Figures Figure 1: Bronchoalveolar Lavage (BAL) Image Cut .......................................................... 8! Figure 2: Macrophages ...................................................................................................... 9! Figure 3: Lymphocytes with a macrophage ........................................................................ 9! Figure 4: Polymorphonuclears with a macrophage ............................................................ 9! Figure 5: Eosinophiles ........................................................................................................ 9! Figure 6: Bronchial cilindric cell ........................................................................................ 10! Figure 7: Squamous mouth cell ........................................................................................ 10! Figure 8: Blood & Mucus .................................................................................................. 10! Figure 9: Semantic Segmentation of a street picture [3] .................................................. 12! Figure 10: Tree representation of BAL Image cut (inverse) ............................................. 13! Figure 11: U-net architecture. Each blue box corresponds to a multi-channel feature map. The number of channels is denoted on top of the box. The x-y-size is provided at the lower left edge of the box. White boxes represent copied feature maps. The arrows denote the different operations. [9] ..................................................................................................... 15! Figure 12: Tile suitable for analyse vs not suitable .......................................................... 16! Figure 13: Normal distribution of the two tile types .......................................................... 17! Figure 14: Spurious nucleolus .......................................................................................... 18! Figure 15: Spurious maxima located in mucus ................................................................ 18! Figure 16: Opening vs Reconstruction ............................................................................. 19! Figure 17: Closing vs Dual Reconstruction ...................................................................... 19! Figure 18: Granulometry of one image ............................................................................. 20! Figure 19: Closing vs Dual Reconstruction ...................................................................... 20! Figure 20: Top Hat 3 vs 4 pixels radius structuring element ............................................ 20! Figure 21: Top Hat 7 vs 8 pixels radius structuring element ............................................ 21! Figure 22: Reconstruction with 3 pixels radius structuring element ................................. 21! Figure 23: Maxtree Representation .................................................................................. 22! Figure 24: Macrophage cytoplasm analysis ..................................................................... 23! Figure 25: Macrophage Soup ........................................................................................... 24! Figure 26: Macrophage nucleus analysis ......................................................................... 25! Figure 27: Macrophage Detection Example ..................................................................... 26! Figure 28: Macrophage cytoplasm image of candidates .................................................. 26! Figure 29: Macrophage cytoplasm opening and dual reconstruction ............................... 27! Figure 30: Macrophage nucleus hole filled ....................................................................... 28! Figure 31: Macrophage nucleus cleaned ......................................................................... 28!
6 Figure 32: Macrophage image of candidates cleaning example 1 ................................... 28! Figure 33: Macrophage image of candidates cleaning example 2 ................................... 29! Figure 34: Macrophage detection example 1 ................................................................... 30! Figure 35: Macrophage detection example 2 ................................................................... 30! Figure 36: Polymorphonuclear / Eosinophile / Lymphocyte ............................................. 31! Figure 37: Lymphocytes, polymorphonuclears and eosinophiles detection ..................... 32! Figure 38: Nuclei Overlapped ........................................................................................... 33! Figure 39:Example of how 4 pixels radius structuring element remove relevant data ..... 34! Figure 40: Second cut example ........................................................................................ 34! Figure 41: Distance Function ........................................................................................... 35! Figure 42: Analysis by maxima of distance function 1 ..................................................... 36! Figure 43: Analysis by maxima of distance function 2 ..................................................... 36! Figure 44: Example of small cells detection 1 .................................................................. 37! Figure 45: Example of small cells detection 2 .................................................................. 38! Figure 46: Output masks examples .................................................................................. 38! Figure 47: Correcting masks in the VGG Annotator ......................................................... 39! Figure 48: Images Segmentation Procedure .................................................................... 40! Figure 49: Correction example 2 ...................................................................................... 41! Figure 50: Correction example 1 ...................................................................................... 41! Figure 51: Data Augmentation in play [11] ....................................................................... 42! Figure 52: ReLU vs Sigmoid [26] ..................................................................................... 43! Figure 53: Sigmoid vs ReLU ............................................................................................ 44! Figure 54: Output segmentation maps ............................................................................. 45! Figure 55: Sørensen–Dice coefficient [25] ....................................................................... 45! Figure 56: IoU [19] ............................................................................................................ 47! Figure 57: Validation Results ........................................................................................... 48! Figure 58: Adam vs Adamax ............................................................................................ 50! Figure 59: Static learning rate vs variable ........................................................................ 51! Figure 60: IoU Score along 180 epochs ........................................................................... 51! Figure 61: Correlation between class representation and its IoU ..................................... 53! Figure 62: Lymphocyte vs Polymorphonuclear ................................................................ 55!
7 List of Tables: Table 1: Mean grey level of suitable images for analysis ................................................. 17! Table 2: Mean grey level of images not suitable for analysis ........................................... 17! Table 3: Maxtree nodes applying different morphological techniques ............................. 19! Table 4: Parameters final values ...................................................................................... 24! Table 5: Macrophage nuclei parameters final values ....................................................... 25! Table 6: Small cells cytoplasm parameters final values ................................................... 31! Table 7: Small cells nuclei parameters final value ........................................................... 32! Table 8: Results Table ..................................................................................................... 48! Table 9: Loss Function results comparison ...................................................................... 49! Table 10: Correlation between class representation and its IoU ...................................... 52! Table 11: CNN vs Maxtree ............................................................................................... 54! !
14 Maxtree is the classic image processing tool we will use to have a first approximation to the semantic segmentation. 2.4. Convolutional Neural Network (CNN) Convolutional neural networks are a type of deep artificial neural networks widely used in the field of computer vision. They have been applied to many tasks, including image classification, super-resolution and semantic segmentation [6]. The role of the CNN is to reduce the images into a form which is easier to process, without losing features which are critical for getting a good prediction [7]. Convolutional Neural Network are currently the state of art technique in image segmentation field of research. Since astounding results on ImageNet has been demonstrated, all other methods have rapidly been abandoned [8]. 2.4.1. Unet U-Net architecture consists of a contracting path (left side), a fully connected path and an expansive path (right side). In total the network has 23 convolutional layers. The contracting path follows the typical architecture of a convolutional network. It consists of the repeated application of two 3x3 convolutions (unpadded convolutions), each followed by an activation function and a 2x2 max pooling operation with stride 2 for downsampling. At each downsampling step we double the number of feature channels. Every step in the expansive path consists of an upsampling of the feature map followed by a 2x2 convolution (“up-convolution”) that halves the number of feature channels, a concatenation with the correspondingly cropped feature map from the contracting path, and two 3x3 convolutions, each followed by an activation function. At the final layer a 1x1 convolution is used to map each 64-component feature vector to the desired number of classes. To allow a seamless tiling of the output segmentation map, it is important to select the input tile size such that all 2x2 max-pooling operations are applied to a layer with an even x- and y-size [9].
15 Figure 11: U-net architecture. Each blue box corresponds to a multi-channel feature map. The number of channels is denoted on top of the box. The x-y-size is provided at the lower left edge of the box. White boxes represent copied feature maps. The arrows denote the different operations. [9]
16 3. Project Development As we said in the state of the art, a CNN trained on a large and versatile dataset, learns information about object characteristics that is generic enough to transfer to objects that are not in the original dataset. But what happen if we do not have that annotated dataset? We have just received the BAL images from la Vall d’Hebron hospital, we do not have any labelled image. So, as first approximation, we decided to use classical techniques to tackle the problem. Because the manual labelling is a hard and tedious task, having a first technique that classifies quite well the pixels of the images into the different classes, would be a good starting point, which would reduce the manual labelling task. Having studied different classical segmentation techniques for our problem, we decided to implement a Maxtree solution on grayscale images. Due to its tree and branch structure and its good handling of connected components we thought that the Maxtree solution would be suitable for our problem. 3.1. Appropriate Image Selection The first step, is to decide which tiles are suitable for segmentation and which are not. Because some tiles are clean and they have cells that can be well differentiate, but others can have much contamination, and classify cells can be a difficult task, also for doctors. For that reason, in order to carry out the correct and accurate count of the inflammatory cell types, it is necessary to determine which tiles of the WSI are suitable for a correct classification. Dismiss not suitable tiles would not be a problem from a statistical point of view, taking into account that WSI statistics are quite homogeneous in every tile due to the centrifugation step and that a WSI can contain hundreds of thousands of cells. Also, when technicians analyse these images in the hospital, they ignore the parts with a lot of mucus, where the counting of inflammatory cells is very difficult, so in some way, they do the same. To carry out this task, a thresholding algorithm is used, based on the average grey level of the image. If the mean grey level of the image is lower than a threshold, the tile is automatically rejected. Figure 12: Tile suitable for analyse vs not suitable
17 To determine the threshold, we analyse some images, and here we have an example of the mean grey level of ten images suitable for the analysis and ten images which are not. Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7 Image 8 Image 9 Image 10 223 225 219 210 232 220 222 216 236 228 Table 1: Mean grey level of suitable images for analysis Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7 Image 8 Image 9 Image 10 193 200 196 191 198 213 208 202 212 208 Table 2: Mean grey level of images not suitable for analysis In the next figure we can see the probability density function of both tile types, approximating them as gaussian and computing mean and variance about twenty images of each class. Figure 13: Normal distribution of the two tile types As we can see, 215 is the mean grey level where the curves intersect, so it is where we decide to put the threshold. 215
18 3.2. Maxtree-based Solution 3.2.1. Image Simplification As we said before, we are going to use Maxtree algorithms to develop the first segmentation. But before computing it, reducing the number of nodes of the tree and remove spurious candidates without losing relevant image data would be important in order to reduce the computation time and to not have spurious detection. For that reason, morphological cleaning techniques have been used; opening, closing, reconstruction with the original eroded image as marker and dual reconstruction with the original dilated image as marker. Best techniques should reduce the maximum number of nodes without losing relevant data, the nuclei, their shape and their separation, so it is important to not remove nuclei and to not increase the overlap between them, either. Opening and opening by reconstruction of erosion are two morphological techniques which remove those maxima smaller than the structuring element, so the goal of applying them is to remove small maximums that bother us or do not contribute to us when analysing the tree. For example; spurious maxima located in the mucus, nucleolus inside cells, or variations in the grey level of the nuclei. In Figure 15: Spurious maxima located in mucus and Figure 14: Spurious nucleolus we can see how applying morphological techniques can help reducing remove these unwanted maxima. Closing and closing by reconstruction of dilation are two morphological techniques which remove those minima smaller than the structuring element, so the goal of applying them is to remove small minima which do not contribute to us when analysing the tree without remove relevant data. s in the nuclei grey level Figure 15: Spurious maxima located in mucus Figure 14: Spurious nucleolus
19 It is important to remark that in order to have more visual information, images are inverted in grey level scale, to look for maxima and not for minima. This is applied in all the project, so when we talk about maxima, are actually minima of the original image and vice versa. 3.2.1.1. Opening vs opening by reconstruction of erosion and closing vs closing by reconstruction of dilation Firstly, we are going to test which operation most reduce the number of nodes in the tree. In the next table we can see the average number of nodes that different images Maxtrees have depending on the cleaning technique we apply. These averages are computed with 43 different images, with 3 radius pixels disk structuring element. Table 3: Maxtree nodes applying different morphological techniques Opening by reconstruction of erosion and closing are the two operations which reduce the largest number of nodes. But it is also very important to preserve the relevant data for the correct segmentation of the image. For that reason, opening by reconstruction of erosion and closing by reconstruction of dilation are applied. These are the techniques who best preserve the natural shape of the cells and do not cause overlap between cells. Image Opening Opening by reconstruction Closing Closing by dual reconstruction Average Nº Nodes 36.816 7.754 6.664 13.544 36.531 Figure 17: Closing vs Dual Reconstruction Figure 16: Opening vs Reconstruction
20 3.2.1.2. Size of structuring element In order to estimate the size of the elements in the image and which radius size of the structuring element starts to remove relevant data, granulometry techniques have been applied. Accumulate granulometry of 43 images has been computed. It seems clear that something is happening when the opening by reconstruction of erosion is made with the original eroded image as marker using structuring elements which radius are 4, 8 and 11 pixels. In these values we are removing something that seems important. So, we are going to study these cases (not 11 because in 8 we see we start to remove relevant information). • Reconstruction with the original eroded image as marker using 4 pixels radius structuring element: spurious maxima located in the mucus and variations in the grey level of the nuclei are removed, but at the same time we start to remove relevant data as some nuclei maxima. Figure 20: Top Hat 3 vs 4 pixels radius structuring element Figure 18: Granulometry of one image Figure 19: Closing vs Dual Reconstruction
21 • Reconstruction with the original eroded image as marker using 8 pixels radius structuring element compared with 7 pixels radius structuring element: relevant data as nuclei maxima are removed. Looking at the results, and taking into account that this software will be an intermediate step, which goal is to label images to train a CNN, calculation time is not the most important, we prioritize to keep relevant data. For that reason, we decided to clean the image applying reconstruction with the original eroded image as marker using 3 pixels radius structuring element. Which as we saw before, is very useful to reduce the number of nodes in the tree. To clean minima, it is necessary to apply closing by dual reconstruction of image dilation, since with the closing, we obtain an unwanted overlapping. With the original image dilated as marker using 3 pixels radius disk structuring element, we manage to clean some noise in the background of the image without overlapping nuclei, so that was the selected technique. 3.2.2. Macrophage Detection The first step is to compute the maxtree, which is an easy task thanks to maxtree processing toolbox [4]. Figure 21: Top Hat 7 vs 8 pixels radius structuring element Figure 22: Reconstruction with 3 pixels radius structuring element
22 The first analysed cells are macrophage, which we considered easiest for their shape and regularity. They always have the same structure, ellipse shape nucleus with cytoplasm. Taking this into account, two variable cuts in the trees have been done, one to determine the cytoplasm and another to determine the nuclei. 3.2.2.1. Macrophage cytoplasm, first cut To decide whether or not a node belongs to macrophage cytoplasm 4 parameters are used, which are actually thresholds. If the node accomplishes them, the node is considered as macrophage cytoplasm node, if it does not accomplish them, it is not. The parameters are the following: 1. min_leaf_glvl: minimum leaf grey level that must have a node to be macrophage cytoplasm candidate. 2. min_cito_glvl: minimum grey level that must have a node to be macrophage cytoplasm candidate. 3. max_cito_leafdist: maximum grey level distance to the leaf that a node can have to be a macrophage cytoplasm candidate. 4. min_cito_area: minimum area that must have a node to be macrophage cytoplasm candidate. Figure 23: Maxtree Representation
23 This algorithm has the advantage of performing a local analysis of the nodes, since the assignation to a macrophage cytoplasm depends on the leaf, if a node does not present a grey level close enough to the leaf, it cannot be assigned as macrophage candidate. And if a node belongs to a branch which does not have a high enough grey level leaf, it cannot be assigned as macrophage candidate. This makes that perhaps a macrophage with a cytoplasm which grey level is lower than some mucus, is detected as macrophage, because it may have a higher leaf and despite the fact that this grey level is lower than the common of macrophage cytoplasm, it can be assigned as macrophage cytoplasm candidate, since its classification depends on the distance to the leaf. Another important feature is that cytoplasm candidate nodes must have a minimum area, understanding as area the sum of the number of pixels stored in the current node and all its descendant nodes [4]. This is because the rest of cells are smaller than macrophages, and the rest of parameters do not filter them, so some of the other cell types would be determined as macrophages. For that reason, we need to filter these candidates with little area. We do not use a parameter to filter how big a macrophage cytoplasm, this is because in some images appears what is called “soups of macrophage”, where many macrophages appear sharing a common cytoplasm. This cytoplasm is very big, and these macrophages have to be counted as well. Finally, the last parameter is to filter the nodes which have a very low grey level, since some mucus can be detected as macrophage if it has spurious maxima and enough area. Leaf max_cito_leafdi st min_cito_glvl min_cito_area MACROPHAGE MACROPHAG E Figure 24: Macrophage cytoplasm analysis
30 • Macrophage detection examples Figure 35: Macrophage detection example 2 Figure 34: Macrophage detection example 1
31 3.2.3. Lymphocytes, Polymorphonuclear and Eosinophiles Detection These three types of cells have been grouped because their size is very similar, it depends more on the chosen BAL sample than on the type of cell. For that reason, we decided firstly, detect these three types of cells together, making a cut in the tree, and once they are detected, separate them making another cut. 3.2.3.1. First maxtree cut, looking for cytoplasm, joint detection As we do in macrophage detection, we are going to take advantage of the Maxtree analysis to select lymphocytes, polymorphonuclears and eosinophiles candidates. So, the first step is to compute the Maxtree. Once this step is done, the same algorithm used in the macrophage cytoplasm is applied, we do a variable cut in the tree, following a series of parameters, which will determine if a node is considered as candidate or not. 1. min_leaf_glvl: minimum leaf grey level that must have a node to be considered as candidate. 2. min_cyt_glvl: minimum grey level that must have a node to be considered as candidate. 3. max_cyt_leafdist: maximum grey level distance to the leaf that a node can have to be considered as candidate. 4. min_cyt_area: minimum area that must have a node to be considered as candidate. 5. max_cyt_area: maximum area that must have a node to be considered as candidate. It is exactly equal that macrophage cytoplasm detection, changing parameters. Figure 24 • Final values chosen Table 6: Small cells cytoplasm parameters final values min_leaf_glvl min_cyt_glvl max_cyt_leafdist min_cyt_area max_cyt_area 145 50 0.25 50 600 Figure 36: Polymorphonuclear / Eosinophile / Lymphocyte
32 3.2.3.2. Second maxtree cut, looking for cytoplasm, joint detection Now, following as we did in the macrophages, we intend to make a second variable cut in the tree, trying to find the nuclei candidates. The used values for the parameters are the following: 1. min_leaf_glvl: minimum leaf grey level that must have a node to be considered as candidate. 2. min_nuc_glvl: minimum grey level that must have a node to be considered as candidate. 3. max_nuc_leafdist: maximum grey level distance to the leaf that a node can have to be considered as candidate. 4. min_nuc_area: minimum area that must have a node to be considered as candidate. 5. max_nuc_area: maximum area that must have a node to be considered as candidate. It is exactly equal that macrophage cytoplasm detection, changing parameters. Figure 26 • Final values chosen Table 7: Small cells nuclei parameters final value • Detection Example min_leaf_glvl min_nuc_glvl max_nuc_leafdist min_nuc_area max_nuc_area 185 170 0.89 20 300 Figure 37: Lymphocytes, polymorphonuclears and eosinophiles detection
33 This cut, besides providing us the pixels which belong to nuclei, should provide us the necessary information to differentiate cells; considering that, as we have seen, lymphocytes only have one nucleus, eosinophiles two, and polymorphonuclear three or more. But actually, we saw that in the vast majority of cases, nuclei are overlapped, and cleaning the image will be not enough to differentiate the different type of cells. 3.2.3.3. Images of candidates cleaning To generate candidate images, we use the same technique used in macrophage detection, and equal to macrophages case, images of candidates are not as good as we want. We only did a small opening by reconstruction with the original image of candidates dilated as marker using a 3 pixels radius disk structuring element to remove spurious maxima in mucus. Nuclei detected outside cytoplasm, are automatically rejected. We also reject the candidates detected inside macrophage nuclei, because we consider that macrophage nuclei are better detected, and it is very rare to find a lymphocyte, polymorphonuclear or eosinophile above a macrophage. The real goal in these cells cleaning is to achieve separate nuclei, because this will be the way to differentiate the cell type. We have tried with openings, using different sizes of structuring elements. The size we saw we obtained acceptable results and it did not remove relevant data is 3 pixels radius structuring element, because with 4 pixels we start to lose relevant data. Figure 38: Nuclei Overlapped
34 And here we have a successful example, but they are isolated cases. The most common is not to achieve good separation. This was a serious problem, because we cannot differentiate one type of cell from the others, we needed to find a way to do it. At first, we think about doing a third cut into the tree, but we have tried and the cut was not very accurate, because leaves were not in every nucleus, and not always a maximum was related to a nucleus. 3.2.3.4. Distance Function The distance transform provides a metric or measure of the separation of points in the image. It calculates the distance between each pixel that is set to off (0) and the nearest nonzero pixel for binary images. In our case, we use Euclidean distance [10]. Figure 39:Example of how 4 pixels radius structuring element remove relevant data Figure 40: Second cut example
35 It can be computed with cascading erosions, as we can see in Figure 41. Taking into account that the maxtree solution does not seem to help us in this task another option is to find a solution based in the shape of nuclei, implementing a distance function solution. Our intention was to find the maxima in the distance function of the image of nuclei candidates, and this would return the number of nuclei in a cell. Here we have some results, where Maxima1 are maxima of the distance function calculated with a very restrictive threshold, whereas Maxima2 are maxima of the distance function calculated with a less restrictive threshold. These maxima are computed using maxtree cuts, such as in cell detection, but in this case, there are almost no nodes. Figure 41: Distance Function
36 Figure 42: Analysis by maxima of distance function 1 Figure 43: Analysis by maxima of distance function 2
37 The proposed technique is not always effective. It improves the separation of the cleaning techniques but it continues confusing the cell type. This was the final way we used in the classical algorithm to differentiate cells counting the number of connected components coming out of the maxima of distance function inside the cells. If it has one connected component is a lymphocyte, if it has two it is eosinophile and if it has more it is polymorphonuclear. If the cell candidates do not have any maxima of distance function, they are rejected. I want to remark that in this case, the cells are marked with cytoplasm, because they can have more than one nucleus. The results in small cells (lymphocytes, polymorphonuclears and eosinophiles) are not as good as in the macrophage case, because as we said before, the algorithm continues confusing the cell type. It seems that looking for maxima in the image is not the best way to separate the overlapped nuclei, because not all maxima in the image are nuclei and not all nuclei have the maximum of the cell inside. As we have seen, it was a difficult task that we underestimated. However, the cell cytoplasm is quite well segmented, the problem is how to differentiate one type of cell from the others. More research can be done to achieve this classification using classical techniques (as proposed in future development or others). Nevertheless, the results obtained could already be used as a preliminary ground truth for training a machine learning algorithm. Figure 44: Example of small cells detection 1
38 3.2.4. Mask creation Once we have applied all these techniques, masks have to be generated. The algorithm generates as output grey scale images, where 0 value pixels are background, 64 value pixels are macrophage, 128 value pixels are lymphocytes, 191 value pixels are polymorphonuclears and 255 value pixels are eosinophiles. Figure 45: Example of small cells detection 2 Figure 46: Output masks examples
39 3.2.5. Manual Labelling Corrections To solve the classification problem of the small cells and to improve the results of the maxtree, we decide to correct by hand the output masks, in order to train a small CNN to start testing how they work with this problematic. If it works better than the maxtree algorithm, we could continue labelling images with the output of the CNN and correcting them by hand, but it is always easier to correct something more or less good than correct something from zero. 3.2.6. VGG Image Annotator Once an algorithm segments the images in the different classes and background, the segmentation has to be corrected. For that reason, a tool to correct the labelled images is needed. We use the VGG Image Annotator (VIA), a simple and standalone manual annotation software for image, audio and video. VIA runs in a web browser and does not require any installation or setup. The complete VIA software fits in a single self-contained HTML page of size less than 400 Kilobyte that runs as an offline application in most modern web browsers [11]. With this annotator, we can generate easily new annotations with so many different shapes, but if you have previous annotations, the only way to load them in the browser is convert all the regions in a recognizable shape (square, rectangle, circle, etc.), in our case, ellipses are the defined shapes that best suit our cells. After that, we should write them in a .json file, to be able to modify the masks. And loading this .json file in the browser annotator we can start to correct our labelled images. Figure 47: Correcting masks in the VGG Annotator
46 So, the generic formula to compute it. [19] 𝐷𝐿 = 1 − 𝐷𝑆𝐶 Jaccard Loss is very similar to Dice Loss but instead of optimize Sørensen–Dice coefficient it optimizes the Jaccard Coefficient (IoU) Figure 56: IoU . MSE Loss is based on the Mean Square Error. All these loss functions are applied for each mask separated, but the backpropagation is computed with the whole mini-batch. Where A is ground truth mask and B is predicted mask or vice versa.
47 4. Results 4.1. Metrics, IoU The Intersection-Over-Union (IoU), also known as the Jaccard Index, is one of the most commonly used metrics in semantic segmentation. The IoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union between the predicted segmentation and the ground truth. This metric ranges from 0–1 (0–100%) with 0 meaning overlap and 1 meaning perfectly overlapping segmentation [22]. The IoU computed in the network is calculated over the whole mini-batch, with all channels together and pixel by pixel. This means that it is not directly the averages of IoUs of each class, because the number of pixels in each class is taken into account to calculate the coefficient, so the classes with more representation counts more. In addition, we calculate two metrics for the validation data, which both take into account all the validation images. One that calculates IoU for each class and another that determines the IoU of pixel detection, only taken into account if the pixel is detected and not the class to which it is assigned. 4.2. Final Results To finish adjusting the results of our network, different parameterizations have been tested to see what results we obtain. We test different Loss Functions (Jaccard Loss, Dice Loss, MSE Loss), different optimizers (Adam, Adamax), different learning rates (static, variable) and different number of epochs. Figure 56: IoU [21]
48 Optimizer Epochs LR Loss Function Macrophage IoU Lymphocyte IoU Polymorph onunclear IoU Eosinophiles IoU Valid IoU Score Train IoU Score Pixel Detection IoU Adam 40 Fixed: 1e -3 Jacard Loss 0,72 0 0,534 0 0,61 0,623 0,68 Variable: 1e -3 until 30, 1e-5 Jacard Loss 0,747 0 0,598 0 0,621 0,632 0,733 60 Fixed: 1e -3 Dice Loss 0,747 0,473 0,531 0 0,684 0,737 0,79 Variable 1e -3 until 40, 1e-5 until 55, 1e-6 Dice Loss 0,741 0,46 0,544 0 0,69 0,716 0,79 80 Fixed 1e -3 Dice Loss 0,73 0,34 0,53 0 0,649 0,69 0,78 Variable 1e -3 until 50, 1e-5 Dice Loss 0,75 0,501 0,527 0 0,695 0,746 0,778 Variable 1e -3 until 50, 1e-5 until 70, 1e-6 Dice Loss 0,75 0,512 0,535 0 0,7 0,824 0.794 Adamax 40 Fixed: 1e -3 Dice Loss 0,737 0,504 0,527 0 0,619 0,691 0,774 Variable: 1e -3 until 30, 1e-5 Jacard Loss 0,742 0,587 0,525 0 0,693 0,758 0,785 60 Variable: 1e -3 until 45, 1e-5 Dice Loss 0,748 0,501 0,527 0 0,684 0,763 0,769 Variable 1e -3 until 35, 1e-5 until 55, 1e-6 Dice Loss 0,74 0,587 0,536 0 0,693 0,78 0,782 80 Variable 1e -3, 1e-5 Jacard Loss 0,745 0,562 0,581 0 0,685 0,802 0,788 Variable 1e -3 until 50, 1e-5 until 70, 1e-6 Dice Loss 0,75 0,498 0,53 0 0,687 0,778 0,785 Table 8: Results Table Figure 57: Validation Results
49 4.2.1. Loss Function Jaccard Loss, Dice Loss and MSE Loss have been applied in the net in order to see how they work. Jaccard Loss and Dice Loss are similar, outperforming MSE Loss, they converge towards similar solutions. Looking at the results (Table 8, Table 9) Jaccard Loss seems to converge into a better solution with fewer epochs and with Adamax optimizer, whereas Dice Loss seems to converge towards a better solution with more epochs and combined with Adam optimizer. 4.2.2. Optimizer Adam and Adamax optimizers have been tested in the network. Adamax is an extension of Adam optimizer based on the infinity norm. Both present similar behaviours, superior to SGD. Looking at the results (Table 8, Figure 58), Adamax seems to perform better with fewer epochs and with fixed learning rates, whereas Adam seems to converge towards a better solution with more epochs and with variable learning rates. Adamax presents smoother growing in the initial validation epochs, but differs more from training results in the last epochs. Adam starts with irregular growing in the first epochs but it finally remains stable more according with training results. Parametrization Loss Function Valid IoU Score Train IoU Score Adam 40 variable lr 1e-3 until 30, 1e-4 JaccardLoss 0,621 0,632 DiceLoss 0,579 0,615 Adamax 40 variable lr 1e-3 until 30, 1e-4 JaccardLoss 0,693 0,758 DiceLoss 0,63 0,679 Adamax 60 variable lr 1e-3 until 35, 1e- 5 until 55, 1e-6 JaccardLoss 0,645 0,732 DiceLoss 0,693 0,78 MSELoss 0,601 0,671 Adam 80 variable lr ariable lr 1e -3 until 50, 1e- 5 JaccardLoss 0,686 0,723 DiceLoss 0,695 0,746 MSELoss 0,605 0,641 Adamax 80 variable lr ariable lr 1e - 3 until 50, 1e- 5 JaccardLoss 0,685 0,802 DiceLoss 0,684 0,763 MSELoss 0,6732 0,755 Table 9: Loss Function results comparison
50 4.2.3. Learning Rate Annealing A commonly used technique, known as learning rate annealing, recommends starting with a relatively high learning rate and then gradually lowering the learning rate during training. The intuition behind this approach is that we would like to traverse quickly from the initial parameters to a range of "good" parameter values but then we would like a learning rate small enough that we can explore the "deeper, but narrower parts of the loss function" [23]. Following this technique, we test three different learning rates: static learning rate, variable learning rate with one step, and variable learning rate with two steps. The results obtained are very similar (Table 8: Results Table, Figure 59: Static learning rate vs variable), it depends on the number of epochs we use, but varying the learning rate we achieve quickly “good” parameter values and then make a more accurate adjustment. Figure 58: Adam vs Adamax
51 4.2.4. Number of epochs The number of epochs is the parameter that controls the number of complete passes through the training dataset. One of the critical issues while training a neural network on the sample data is Overfitting. When the number of epochs used to train a neural network is more than necessary, the training model learns patterns that are specific to sample data to a great extent. This makes the model incapable to perform well on a new dataset [24]. In our case, we do not obtain overfitting, our system fits the data but the validation results do not get worse along the epochs, so this is not an overfitting problem. But the model converges towards a solution and the scores almost do not vary since certain epoch, so it does not make sense to extend the number of epochs if the optimization of the weights is not going to improve. Figure 59: Static learning rate vs variable Figure 60: IoU Score along 180 epochs
52 40, 60 and 80 epochs have been tested with different learning rates. 40 epochs seem to be too few, despite the network starts to remain stable, bests results can be obtained. Between 60 and 80 epochs the results vary very little, they depend more on the optimizer and the variations in learning rate. 4.2.5. Global and per Class IoU Score Looking at results (Table 8: Results Table) we can observe the global IoU score and IoU score per class computed by different network parametrizations. Global IoU score is a metric which defines how the network is working, and having scores of 70% approximately we consider them as good results in order to help for future dataset creation and development. In case of IoU score for each class we cannot say the same, they are lower as we expected in some classes more than in others. These results make us thing about the disparity in the IoU per class and the great difference in comparison with the global IoU. Knowing that the only difference between both is that the network computes the global IoU which takes into account the frequency of occurrence (at pixel level) of each class, we thought it could be a class imbalance problem. This is a problem that plagues most of the Machine Learning / Deep Learning Classification problems. It occurs when there are one or more classes (majority classes) that are more frequent occurring than the other classes (minority classes). Simply put, there is a skewness towards the majority class [25]. To analyse if our dataset suffers of imbalance, we compute how many pixels has each class in the whole dataset, and how this affects to the IoU score per class. Macrophages Lymphocytes Polymorphonuclears Eosinophiles Number of pixels in training images 248988 92217 337132 18326 Number of pixels in validation images 77262 28330 83141 5409 % of the total cell pixels in training 35,74 13,24 48,39 2,63 % of the total cell pixels in validation 39,80 14,59 42,82 2,79 IoU Score of a good parametrization 0,75 0,512 0,535 0 Avg IoU Score 0,742 0,425 0,54 0 Table 10: Correlation between class representation and its IoU
53 Results are clear, our dataset suffers of imbalance, the IoU score for the majority classes are clearly higher than for the minority classes (eosinophiles IoU = 0). This is because when training a model on an imbalanced dataset, the learning becomes biased towards the majority classes. With a greater number of examples available to learn from, the model learns to perform well on the majority classes, but due to the lack of enough examples, the model fails to learn meaningful patterns that could aid it in learning the minority classes [25]. Another important fact to highlight is that macrophages are the best detected cells despite not being the most representative class in the images. This is probably because it is, as we have seen previously in the maxtree, the most different class from the rest, and therefore the easiest to differentiate. These “low” IoU per class scores makes the results of this project limited. However, their analysis can help a lot for future development, so knowing this imbalance in the dataset, actions can be taken to improve results, as the proposed in “5.2. Future Development”. 4.2.6. Pixel detection IoU score Looking at results (Table 8: Results Table) we can observe the IoU score for the pixel detection in different parametrizations. This is one strong point in our results (80% approx.), because if we want to develop a tool to ease the creation of a big dataset, detect a high number of pixels that belong to any class we think that helps a lot. Because it provides the advantage of only have to change the label of some cells and not have to label them from zero. 4.2.7. Tricky solution Taking into account the explanation in “4.2.5. Global and per Class IoU score”, one possible “tricky” result for the CNN, which actually can give “acceptable” IoU global scores can be obtained assigning all small cells pixels to the polymorphonuclear class. Because it was the most representative class (48,4% of the cell pixels) and because they are very similar to lymphocytes and eosinophiles. As the loss is computed globally and not for each class, Figure 61: Correlation between class representation and its IoU
54 as IoU global score, it also takes into account the frequency of occurrence (at pixel level) of each class, making possible this kind of solution. In order to avoid them in future development; something we can do is to avoid the parametrizations that lead us to these solutions. But to fix it in a good way, we should improve the dataset in order to increase the labelled data and solve the class imbalance problem. 4.2.8. Maxtree Results Actually, results of the first part of the project were difficult to evaluate, because we did not have any labelled data to compare with, so we could not adjust or train the parameters based in a ground truth, because we did not have it. One possible solution could have been labelling manually some images to compute some scores and adjust our parameters before label the 56 images, but now it is too late, for future development I think I will implement it. However, now that we have the small dataset, we can compute the IoU score of the previous algorithm based on maxtree. Table 11: CNN vs Maxtree As it can be seen, performance is correct; the macrophage IoU is high, the lymphocyte IoU is very close to the CNN IoU and the IoU for pixel detection is higher than the obtained by the CNN. It is true that for polymorphonuclears, a very representative class, it does not provide good results. But taking into account that the goal for this algorithm was ease the manual labelling task, we can conclude that it probably does. One problem with this algorithm is that it was not intended to train it, so even if we improve and increase the dataset, results will not improve. So, if we want to continue facing the problem with this system, we should extract descriptors from the cuts made in maxtree to train them. But if the goal is to continue with CNN techniques, I think this maxtree based algorithm has fulfilled its objective, do as a launcher to start tackling the problem from machine learning.
55 5. Conclusions and future development 5.1. Conclusions This Project has been the first contact with the BAL image segmentation. Carrying it out different techniques have been studied and applied to face this problem. As first, using a segmentation algorithm based on maxtree and correcting by hand the masks computed by it (56 masks). And finally testing and training a CNN, to develop a better classifier and obtain valuable information for the future development of the problem in CNN area. We can conclude that, in a way, the objectives of the project have been accomplished, despite perhaps the scores are not the expected and the CNN cannot generate segmented dataset to modify only details. I think that carrying out this project we have learned and advanced a lot with the BAL segmentation. We have obtained many valuable information about our dataset, we have developed a maxtree-based algorithm that has made the masks correction easier, we have labelled and corrected 56 different images, we have tested and trained a CNN, analysed different parametrizations, studied and applied techniques to improve results in small datasets, and finally, this CNN was trained to segment new images achieving better results. So, taking all this into account, and considering that at first, we had nothing labelled, and for training the net we have used a very limited dataset, with imbalance problems, we consider this project a good starting point. 5.2. Future Development 5.2.1. New techniques to classify lymphocytes This was a proposed method but not tested, maybe it is useful for future development. Considering the last explanations of the doctor Jordi Temprana, who said that lymphocytes have to be very round and almost without cytoplasm, it makes sense to measure the circularity of the nuclei and the ratio nucleus / cytoplasm of the small cells and only if they are very round and their ratio is close to 1, classify the cell as lymphocyte. 5.2.2. Improve Transfer Learning As you know, we used a pre-trained models to initialize our CNN, applying transfer learning. But perhaps, images used to train these previous models are not the most similar to ours. ImageNet has 1000 classes. That’s why pretrained models have a lot of parameters in the Figure 62: Lymphocyte vs Polymorphonuclear