Lenet Implementation For Cell Segmentation

Lenet Implementation For Cell Segmentation

I. IDEA

  1. Divide the preprocessed image into small patches (20*20 size)
  2. classify these patches as blank or cell border or nucleus
  3. use different colors to mark different types of patches
    • For example: blank: White; cell border: green; nucleus: red
result preview:
image

2. DATASET

  1. blank data

    • number: 714


      image-20210402083943177
  2. border data

    • number: 1658

      image-20210402084049242
  3. center data

    • number: 1208

      image-20210402084132724

3. IMPLEMENTATION

3.1) Data Augmentation

Transformations we have done:

  • horizontal and vertical shift
  • horizontal and vertical flip
  • random rotation
  • random zoom
  1. import libraries

    import tensorflow as tf
    from tensorflow.keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
    from numpy import expand_dims
    from matplotlib import pyplot
    from skimage import io
    from skimage.io import ImageCollection
    
  2. load original images

    blank_arr = ImageCollection('Blank/*.tif')
    border_arr = ImageCollection('Border/*.tif')
    center_arr = ImageCollection('Center/*.tif')
    
  3. Function for data augmentation

    def da(img,prefix,dest):
        data = img_to_array(img)
        samples = expand_dims(data, 0)
        
        # horizontal shift
        datagen = ImageDataGenerator(width_shift_range=[-1,1])
        it = datagen.flow(samples, batch_size=1)
        for i in range(9):
            batch = it.next()
            image = batch[0].astype('uint8')
            io.imsave(f'dest/{prefix}{i}.tif',image)
            
        # vertical shift
        datagen = ImageDataGenerator(width_shift_range=0.2)
        it = datagen.flow(samples, batch_size=1)
        for i in range(9,18):
            batch = it.next()
            image = batch[0].astype('uint8')
            io.imsave(f'dest/{prefix}{i}.tif',image)
            
        # random rotation
        datagen = ImageDataGenerator(rotation_range=90)
        it = datagen.flow(samples, batch_size=1)
        for i in range(18,27):
            batch = it.next()
            image = batch[0].astype('uint8')
            io.imsave(f'dest/{prefix}{i}.tif',image)
        
        # horizontal and vertical flip
        datagen = ImageDataGenerator(horizontal_flip=True, vertical_flip=True)
        it = datagen.flow(samples, batch_size=1)
        for i in range(27,36):
            batch = it.next()
            image = batch[0].astype('uint8')
            io.imsave(f'dest/{prefix}{i}.tif',image)
            
        # random zoom
        datagen = ImageDataGenerator(zoom_range=[0.5,1.0])
        it = datagen.flow(samples, batch_size=1)
        for i in range(36,45):
            batch = it.next()
            image = batch[0].astype('uint8')
            io.imsave(f'dest/{prefix}{i}.tif',image)
    
  1. generate the images

    for i in blank_arr:
        da(i,f'Blank_aug_{i}','Blank_aug')
    
    for i in border_arr:
        da(i,f'Border_aug_{i}','Border_aug')
    
    for i in center_arr:
        da(i,f'Center_aug_{i}','Center_aug')
    

3.2) Lenet

  1. import libraries

    import tensorflow as tf
    import matplotlib.pyplot as plt
    from tensorflow import keras
    from skimage.io import ImageCollection
    from pprint import pprint
    from skimage import io
    import numpy as np
    
  2. load the dataset

    • load the images as numpy arrays and stack them to a single numpy array
    • define the labels
    • split the dataset into training dataset and test dataset
    def readAllImages(path):
        img_arr = ImageCollection(path + '/*.tif')
        return img_arr,len(img_arr)
    
    # load the data
    blank = readAllImages('''dataset/Blank_aug''')
    border = readAllImages('''dataset/Border_aug''')
    center = readAllImages('''dataset/Center_aug''')
    
    '''
    border label = 0
    center label = 1
    blank label = 2
    '''
    
    arr1,len1 = blank[0],blank[1]   # 2
    arr2,len2 = border[0],border[1]  # 0
    arr3,len3 = center[0],center[1] # 1
    
    train_images = []
    test_images = []
    train_y = []
    test_y = []
    
    # also split the data into training data and test data
    for i in range(len1):
        if i >= 1000:
            test_images.append(arr1[i])
            test_y.append(2)
        else:
            train_images.append(arr1[i])
            train_y.append(2)
    
    for i in range(len2):
        if i >= 1000:
            test_images.append(arr2[i])
            test_y.append(0)
        else:
            train_images.append(arr2[i])
            train_y.append(0)
            
    for i in range(len3):
        if i >= 1000:
            test_images.append(arr3[i])
            test_y.append(1)
        else:
            train_images.append(arr3[i])
            train_y.append(1)
    
    # build the dataset
    y_train = np.array(train_y,dtype='int32')
    y_test = np.array(test_y,dtype='int32')
    x_train = np.stack(train_images,axis=0)
    x_test = np.stack(test_images,axis=0)
    
  3. preprocessing the data

    • the input image for lenet should be 32x32, whereas our patches have size of 20x20
      • padding the patches
    • normalize the data
    • using one-hot encoding for the labels
    # Fill 0s around the image (six 0s on the top, bottom, left and right respectively)
    # 20x20 => 32x32
    paddings = tf.constant([[0,0],[6, 6], [6, 6]])
    x_train = tf.pad(x_train, paddings)
    x_test = tf.pad(x_test, paddings)
    
    def preprocess(x, y):
        x = tf.cast(x, dtype=tf.float32) / 255.
        x = tf.reshape(x, [-1, 32, 32, 1])
        y = tf.one_hot(y, depth=3)  # one_hot encoding
        return x, y
    
    train_db = tf.data.Dataset.from_tensor_slices((x_train, y_train))
    train_db = train_db.shuffle(10000)  # randomly shuffle the dataset
    train_db = train_db.batch(128)
    train_db = train_db.map(preprocess)
    
    test_db = tf.data.Dataset.from_tensor_slices((x_test, y_test))
    test_db = test_db.shuffle(10000)  # randomly shuffle the dataset
    test_db = test_db.batch(128)
    test_db = test_db.map(preprocess)
    
  4. Model initialization

    • model summary: 3 constitutional layers and 2 fully connected layers

      image
      batch=32
      model = keras.Sequential([
          keras.layers.Conv2D(6, 5), 
          keras.layers.MaxPooling2D(pool_size=2, strides=2), 
          keras.layers.ReLU(),  
      
          keras.layers.Conv2D(16, 5), 
          keras.layers.MaxPooling2D(pool_size=2, strides=2),  
          keras.layers.ReLU(),  
          
          keras.layers.Conv2D(120, 5),  
          keras.layers.ReLU(), 
          
          keras.layers.Flatten(),
          keras.layers.Dense(84, activation='relu'),  
          keras.layers.Dense(3, activation='softmax') 
      ])
      model.build(input_shape=(batch, 32, 32, 1))
      
  1. compile and fit model

    model.compile(optimizer=keras.optimizers.Adam(), loss=keras.losses.CategoricalCrossentropy(), metrics=['categorical_accuracy'])
    # 训练
    history = model.fit(train_db, epochs=15)
    
    image-20210402092246241
  2. predict on test set

    model.evaluate(test_db)
    
    image-20210402092357088

3.3) Visualization

Use different colors to mark different types of patches

  • blank: White
  • cell border: green
  • nucleus: red

Input sample image:

image-20210402095244512
# 1. load the pretrained model
lenet_model = tf.keras.models.load_model('lenet-model.h5')

# 2. load the input image
input_image = io.imread(...)

# 3. crop the image to patches
delta = 20
results = []
for i in range(26):
    for j in range(26):
         cropped = input_image[i*delta:(i+1)*delta,j*delta:(j+1)*delta]
         results.append(cropped)

patches = np.stack(results,axis=0)

# 4. preprocessing the patches
'''
similar codes in lenet implementation
'''

# 5. predict the patches
results=lenet_model.predict(db,1,verbose =2)
label = [np.argmax(results[i]) for i in range(len(results))]
label_2d = np.array(label).reshape((26,26))
image-20210402100104890
# 6. mark the patches with colors
output_image = np.zeros((520,520,3))
for i in range(26):
    for j in range(26):
         v = labels_2d[i][j]
         
         # blank
         if v == 2:
            output_image[i*20:(i+1)*20,j*20:(j+1)*20] = [255,255,255] # white

         # center
         elif v == 1: output_image[i*20:(i+1)*20,j*20:(j+1)*20] = [255,0,0] # red

         # border
         else: output_image[i*20:(i+1)*20,j*20:(j+1)*20] = [0,128,0]       # green
                
                
# 7. show the image
'''
...
'''
image
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,793评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,567评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,342评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,825评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,814评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,680评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,033评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,687评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,175评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,668评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,775评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,419评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,020评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,978评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,206评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,092评论 2 351
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,510评论 2 343

推荐阅读更多精彩内容