Skip to content

Segmentation by ilastik

ilastik is an application for segmentation by machine learning (Nature Methods, 2019). It is designed so that biologists can operate without any knowledge of machine learning. iLastik seems to be suitable for processing full-color blockface images obtained by CoMBI. For installation, visit developer's site https://www.ilastik.org. Here is a simple procedure to do "Choosing regenerated area and damaged area in a certain organ". There is a detailed documentation in English in the official site (Documentation).

ilastikは、セグメンテーションを機械学習で行うアプリです(Nature Methods, 2019)。機械学習の知識がなくても、操作できるようにデザインされています。https://www.ilastik.orgからダウンロードしてインストールします。CoMBIで撮影したフルカラーのブロック面画像で特定の構造物(関心領域)をSegmentationするのに良さそうです。「とある臓器に正常部位と傷害部位がある。正常部位だけSegmentationしたい」、これをお題に、手順を記します。日本語の簡単な手順書です。本家のサイトには詳しい英語説明ページ(Documentation)があります。


Procedure

This is a simple procedure to do "Selecting only regenerated area, excluding damaged area in a certain organ". My computer environment is macOS11 or 12, ilastik v1.4.0b15 or 21, and Core i7, i9 or M1 max. According to official site, this versions of OS and app are not fully work yet. I found some commands which do not work. For example, in the Export Settings for Simple Segmentation, Label/Channel may not be specified, and conversion from 0,1 to 0,255 (renormalize) may not work.

例題として「とある臓器に再生部位と傷害残存部位がある。再生部位だけSegmentationしたい」、これの手順を簡潔に記します。作業環境は、macOS11 or 12, iLastik v1.4.0bで、公式にはフルサポートしていないバージョンの組み合わせです。Export設定において、Label/Channelの指定ができない場合があったり、0,1>0,255変換ができない場合があるようです。

0. Create New Project

  • In this example, select Pixel Classification
  • Processes is saved as "iLastik project file (.ilp)"
  • Later, follow steps 1 to 5 on the left colomn.

  • 今回は、Pixel Classification
  • プロジェクトファイル、拡張子ilpとして保存する。
  • この後は、右のカラムの1番から5番に従って進める。

1. Input Data

  • Open some images for machine learning. Drag and Drop or Add New> Add separate image(s). In Windows OS, path should contain only English, no local language such as Japanease.
  • CoMBI produces typcally 500-1000 serial images. Select representative images that shows the entire specimen and experimental group. 2 to 4 images are recommended. iMac (2017, 4 core CPU) can learn from 500x500 pixels, 5 images. MacBookPro (2021, M1 max) can learn from 1000x1000 pixels, 10 images.
  • Too much number of images slower the processing. Less images gives inacurate segments.
  • At first, no one knows which image is the best for lerning. Try once. In most cases, I successed at second or third trial.

  • 学習させるための画像を開く。Drag and Drop または、プルダウンメニューAdd New> Add separate image(s)。Windowsの場合、パスに日本語が入っていると、エラーになる場合があります。
  • CoMBIの連続画像(500-1000枚が典型的)のうち、標本全体や実験群全体を代表するような数枚を選ぶ。2〜4枚がおすすめ。(マシンパワーによる、iMac27-2017-4coreでは500x500x5枚まで。MBP16-2021-M1maxなら、1000x1000x10枚まで。)
  • 枚数は、多すぎると処理が遅くなり、少なすぎると正確性が劣る。
  • どの画像が良いか、最初は分からない。一度やってみて、結果に満足しなければ、もう一度やっている。2回目でたいてい成功する。

2. Feature selection

  • iLastik seems to recognize color, brightness, edges and textures (patterns and matrices).
  • Check all items, if your PC's CPU is good enough. "Core i9, HBM2-2GB, RAM32GB" and "M1 max" can check all. "Core i5, internal graphics, RAM8GB" can check a half of sigma. Sigma is a value that determines whether the structure to be recognized is small or large.
  • (In the left colomn, the list of images filtered. Click them to display larger.)
  • This is also a step that we have no idea how to do at first. At first, you can work lightly by checking half of items. After reviewing the results, consider whether to increase the number of checks, or whether to use the option in the next section "3. Training".

  • 全部にチェックするので良いが、マシンパワー(おもにCPU)による。色と明るさ、輪郭線、テクスチャ(模様、行列)を計算してくれるらしい。
  • 「Core i9, HBM2-2GB, メモリ32GB」や「M1 max」では全部にチェックした。「Core i5, 内蔵グラフィクス、メモリ8GB」では、チェック項目を減らした。σとびとびで半分にチェック。シグマは、認識させたい構造物が小さいか大きいかを決める設定値。
  • (左カラム下方に、各種フィルタがかかった画像リストがでてくる。クリックすると画像を確認できる。)
  • (これも、最初はどうすればいいのかさっぱり分からない作業である。とりあえず、とびとびで半数にチェックすれば軽快に作業できる。結果をみて、チェックを増やすか、もしくは、次の項目「3. Training」の中に、推奨チェックを探してくれるオプションがあるので、それを利用してみるか、検討する。)

3. Training

  • Paint in two types, Label1 and Label2. (Note: The default is two types. You can change the name of Label1, etc. by long-pressing on it.)
  • Mark the area to be selected with the yellow pen on Label1. (e.g., the area to be regenerated. Pen size from 1 to 7 is the best for lightweight operation. The thicker the pen, the longer the calculation time.)
  • Mark all other areas with Label2 blue pen. (e.g., both the injury site and the surrounding OCT)
  • It is not necessary to fill it completely. See the official video. The more carefully you mark, especially at the borders, the better the result.
  • When you turn the button Live Update ON, you can work with the results of Segmentation. However, the operation tends to be slow.
  • Optional: The button Suggest Features is not required. You can evaluate the previous section "2. Feature Selection" in three ways and decide if your check was good or not.
    • "Live OFF", then Suggest Features
    • Filter Method (recommended), Number of Feartures 0 (=auto), Run Feature Selection. If you change Number of Features, use 0=auto or 1〜10. For example, 3 will try 3 types of size. I have not tested Set Size Penalty yet, and use dafault 0.1. Find the right balance between segmentation accuracy and computation time. Suggest Features is optional.
    • Wait for a while, for a long time.
    • From the pull-down menu, you can compare/select one of three options: self-selected check, automatic check, or all checks. If you think it is better to change the check pattern, press the button Select Feature Set at the bottom. If you don't need to change, just click `Cancel'.
    • Find the right balance between segmentation accuracy and computation time.
  • (Note: Label1, Lable2, etc. are called Channel1, Channel2, etc. in the next "4. Prediction Export" and the notation is "c". If multiple channels are converted to TIFF or HDF and opened in ImageJ/FIJI, they may appear as Channel1, 2...)

  • Label1, Label2の二種類に塗り分ける。(メモ:デフォルトは2種類。追加して多種類できるがマシンパワーが必要。Label1などの名称は、長押しで変更できる。)
  • 選び出したい領域を、Label1の黄色いペンで印をいれる。(例:再生部位。ペンの太さは、1〜7くらいが動作が軽い。太くなると計算時間が長くなる。)
  • それ以外の領域をLabel2青いペンで印を入れる。(例:傷害部位と周辺OCTの両方)
  • 完全に塗りつぶす必要はない。公式動画参照。丁寧に印を入れれば入れるほど、結果が良くなる。とくに境界線で丁寧に。
  • ボタンLive UpdateをONにすると、Segmentationの結果を見ながら、作業できる。ただし、Live Update ONのままでは、動作が鈍くなりがちです。
  • オプション:ボタンSuggest Featuresは必須ではない。前項「2. Feature Selection」を3通り評価し、自身のチェックがよかったかどうか、判断できる。
    • いったん、Live OFFにして、ボタンSuggest Featuresで別ウィンドウが開く。
    • Filter Method (recommended), Number of Feartures 0 (=auto), Run Feature Selection。Number of Featuresを変更することもできる。0=自動チェック以外に、数値1〜10のどれかを入力する。例えば、3を入力するとsize 3通りなどを試してくれる。Set Size Penaltyは、まだ検証しておらず、デフォルトの0.1を利用している。セグメンテーションの正確さと計算時間との兼ね合い、落としどころを見つける。このオブションはやらなくても進められる。
    • しばらく待つ、けっこう待つ。
    • プルダウンから、「自身で選んだチェック、自動チェック、全チェック」の3通りを比較/選択できる。もし、2. Feature selectionにおいて自身でチェックしたパターンから、変更したほうが良さそうであれば、下段のボタンSelect Feature Setを押して変更を決定する。変更する必要がなければ、Cancelでよい。
    • (チェックが増えると、Segmentationの正確性が向上するが、処理に時間が掛かる。折り合いを付ける。)
  • (メモ:Label1, Lable2などは、次の項「4. Prediction Export」では、Channel1, Channel2などと呼ばれ、表記は「c」となる。複数のChannelをTIFFやHDFにすると、ImageJ/FIJIで開いたとき、Channel1, 2...となる、場合がある。)

4. Prediction Export

  • Source:. Probability (dafault) produces grayscale images. Simple Segmentation produces binary images.
  • Press button Choose Export Image Settings...

  • Source: デフォルトはProbabilityで、グレースケール画像になる。Simple Segmentationは、白黒ハッキリした画像(二値化、2階調、1 bitの画像)になる。
  • ボタンChoose Export Image Settingsより、下図の設定ウィンドウへ。Probalibiltyのcに関して:Label1 (yellow, Background)、Label2 (Blue, segment)として、Label2を書き出したい場合、cの数値は1,2と入力する(デフォルトは0,2)

    Probability Simple Segmentation
    (Purpose) (grayscale) (binary)
    "c" in yxc OFF
    input "1,2" to select label2(blue)
    (ON unstable)
    ON
    (OFF doesn't work)
    Convert to Data Type ON unsigned 8-bit ON unsigned 8-bit
    Renormalize ON
    input "from 0,1 to 0,255"
    (OFF creates binary images)
    OFF
    (ON unstable)
    Format TIFF or TIF TIFF or TIF
    File {dataset_dir}/{nickname}_{result_type}.tiff
    or selected folder/{nickname}_{result_type}.tiff
    {dataset_dir}/{nickname}_{result_type}.tiff
    or selected folder/{nickname}_{result_type}.tiff

    Table: Settigns of my favorite. Some are nessesory to avoid possible bugs, others are variable as you like.

    Export Settings

    Fig. Export Settings, Default (left) settings and settings for Probabiliry.


Verification Notes for myself

yxc: Label1だけ指定してExportするには、「c」のチェックを外して、start 0, stop 1にする。Label2指定なら、1,2とする。(ただし、このLabel指定はProbabilityでのみ有効。Simple Segmentatinでは効かない。OSとappのバージョンのせいかもしれない。「c」のチェックをONにすると、出力結果が不安定だった。3-labelsで検証したとき、ProbabilityではRGBになり、Simple Segmentationでは0,1,2になった。別の日には、Channelに入ったこともあった。Channelになると、PhotoshopではLayerになったり、開けなかったりする。)

Transformation, Convert to Data Type: unsigned 8-bit。TIFFで普通の階調数。16bitなどへ増やせるけど、Segmentationデータなので必要ないと思う。

Transformation, Renormalize...: Probabilityでは、チェックONが必須(OFFにすると二値化されてしまう)。Simple Segmentationでは、チェックOFFが必須(ONにすると真っ白になったり、ただ効かなかったりする。あとでPhotoshopかImageJ/FIJIで変換する)

Output File Info, Format: tifまたはtiffでいいだろう。JPEGでは境界がへんになりそう。

File: では、保存先を指定する。デフォルトの{dataset_dir}/{nickname}_{result_type}.tifを入力すると、出力Exportされるファイルは、「同じフォルダに保存され、同じファイル名プラス_Simple Segmentation.tif」などになる。もし、別のフォルダを指定したい場合、ボタンSelect...より、フォルダを指定し、\の後に、デフォルトのファイル名様式{nickname}_{result_type}.tifを入力する。アドレス指定後に、デフォルトのファイル名様式は全部消えてしまうので、改めてファイル名様式を手入力する必要がある。


  • If you want to apply the same segmentation process to a large number of consecutive images in CoMBI, do not use Export here. Go to the next step "5. Batch Processing".
    CoMBIの大量の連続画像に同一のセグメンテーション処理を施す場合は、ここのExportは使用しない。次の項目「5. Batch Processing」へ進む。

  • If you want to create a segmentation image from only a few images used for Training, you can save the segmentation image using the Export button in the upper column or the Export All button on the left.
    Trainingに使用した数枚の画像だけで、セグメンテーション画像が欲しい場合: 上カラムのExportボタンまたは左のExport Allボタンを押すと、セグメンテーション画像を保存できる。

  • The settings made in Export Image Settings may not be saved in the project file (.ilp). If you want to run the next step 5. Batch Processing on a different day, or on a different computer, check the settings again. (This may due to macOS 11, ilastik 1.4.0b, a version not officially supported???)
    Export Image Settingsで設定した条件はプロジェクトファイル(.ilp)には保存されないことがある。もし、次項「5. Batch Processing」を、別の日、別のパソコンで実行する場合は、設定を確認すること(macOS 11, ilastik 1.4.0b, 正式対応していないバージョンのせいか?)。

5. Batch Processing

  • Select RAW Data Files. Select multiple serial images by Shift+Click or Drag&drop.
  • In the left colomn, Process all files. Wait for a while. It takes for long time. When processing several hundred images at once, iLastik froze or dropped some images out. I do this process it little by little. In my experience, 100 images at a time never failed; 200, 250, 280 images were also fine; from 300 images, the dropouts appear.
  • Just after simple Segmentation, the output tif file is seems completely black. In Simple Segmentation, the image is binarized into 0s and 1s, which in 8bit are 00000000 and 0000000001. Each are Label1 - yellow and Label2 - blue. Opening the image in ImageJ/FIJI and looking at the value of the cursor position, you can confirm that the image consists of only Value1 and Value2. You may be surprised to see the icon displayed in the Finder as a black image, but that is fine for icons. Later, 0,1 can be converted to 0,255 (see below). There is a menu to Renormalize 0, 255 directly, but it did not work with SimpleSegmentation (see 4. Prediction Export above).

  • Select RAW Data Filesより、連続画像を選ぶ。Shiftを押しながら、複数画像を選択する。または、ドラッグ&ドロップ。
  • 左カラムのボタン、Process all files。しばらく待つ。結構時間が掛かる。数百枚を一気に行うと、途中でフリーズしたり、抜け落ちたりした。少しずつやっている。経験上、100枚ずつなら失敗なし。200, 250, 280枚でも大丈夫だった。300枚から抜け落ちが出始める。
  • Simple Segmentationの場合、出力されたtifファイルは、一見真っ黒である。一般の画像8bitでは、ピクセルは輝度0-255を持つ。Simple Segmentationでは、二値化され、画像は、0と1になっている。8bitで表記すると、00000000と00000001になっている。それぞれ、Training時のデフォルトLabelsのうち、Label1-黄色と、Label2-青色である。ImageJ/FIJIで開いて、カーソル位置の値をみると、Value1とValue2だけで構成された画像であることが確認できる。Finderで表示されるアイコンは真っ黒画像になるのでビックリするが、アイコンはそれでよい。のちに0,1を0,255に変換できる(下記)。直接Renormalize 0, 255するメニューはあるが、SimpleSegmentationでは効かなかった(上記 4.Prediction Export)。

Organize files and folders/ファイル・フォルダを整理する

  • (If you exported images to a different folder, you don't need to do this.)
  • For macOS, select mode as as List in the Finder.
  • Sort by Kind to separate original JPEG images and binarized TIFF images.、
  • Select binary images (.tif) then save in new foldet.

  • (別フォルダにExportしたなら、この作業は必要ない)
  • MacならFinderで、リスト表示as List
  • ファイルの種類Kindで並べ替えると、元画像(例 .jpeg)と、二値化した画像(例 ..._Simple Segmentation.tif)が分かれて並ぶ。
  • 二値化画像(.tif)だけ選んで、新しいフォルダに収める。

Convert binary image 0,1 to 0,255/二値化画像を0,1から0,255へ変換

Convert binary images (0, 1) into (0, 255). This is a preparation before import into 3D slicer. Images (0, 255) can be easily used for segmentation. Use ImageJ or Photoshop.
二値化画像0,1を、0,255に変換しておくと、3D slicerでsegmentationしやすい。ImageJまたはPhotoshopを使います。

ImageJ/FIJI

  • Image> Adjust> Threshold... This process is unstable. Try below setting till you success.
    • Check Dark Background, and input values 2, 255. Selected area in white, background in black.
    • (Uncheck and values 0, 1. Selection in black, background in white.)
    • (Uncheck and values 1, 1. Selection in white, background in black.)
    • (Press Set then input value.)
    • (Move slider a little, then input value.)
  • Press Apply.

    • Method:Default
    • Background: Dark
    • Uncheck on Calculate threshold for each image
    • Uncheck on Only convert current image
    • Check on Black background (of binary mask)
    • Uncheck on List thresholds
    • Check on Create new stack (my recommendation)
  • For converting one image, press Save as (If success, icon will changed from all black to black/white.

  • For converting serial images, make macro from Threshold to Apply, and batch process.

  • Image> Adjust> Threshold... (この作業は安定しない、数値入力ではじかれたり。下記のどれかうまくいくやつを探してください)
    • Dark Backgroundにチェックして、数値は2, 255。選択部位が白、背景が黒
    • (チェックなしで、数値を、0, 1とすると、選択部位が黒、背景白になり、反転した画像になる)
    • (チェックなしで、1, 1なら、選択部位が白、背景が黒)
    • Setを押して数値を入力し、確定させたらうまくいったことがある。)
    • (スライダーを動かしてから、数値入力したら、うまくいったことがある。)
  • Applyをおして、適用する。
    • Method:Default
    • Background: Dark
    • Uncheck on Calculate threshold for each image
    • Uncheck on Only convert current image
    • Check on Black background (of binary mask)
    • Uncheck on List thresholds
    • Check on Create new stack (my recommendation)
  • 一枚だけ変換したい場合は、ここでSave as(うまくいけば、まっ黒にしか見えなかった画像・アイコンが、白黒画像・白黒アイコンになる)
  • 連続画像を変換したい場合は、ThresholdからApplyまでを、Macroに記録し、Batch処理する)

Photoshop

  • Image> Adjustments> Threshold
  • Input value 2
  • Image> Adjustments> Invert, background in black.
  • Use action ant batch for converting serial images.

  • Image> Adjustments> Threshold
  • 指定する数値は、2
  • Image> Adjustments> Invert(黒バックになる。3D再構築用に)
  • (ActionとBatchを使って連続画像を処理する。)

Import into 3D slicer for segmantation

  • Load, Any data
  • (Optional): Segmentation (Threshold) mey be done, if you need to analyze values.
  • Volume Rendering for 3D reconstruction.
  • (I have tested binary images (0,1) in 3D slicer, but Volume rendering cannot assign colors. Convesion into 0, 255 is needed.)

  • Load, Any data
  • オプション: Segmentation(Threshold)してもよい。数値化などの目的があれば。
  • Volume Renderingで、3D画像を再構築する。
  • (Simple Segmentationを0,1のまま3D slicerにいれてみたけど、Volume renderingでは色の調節ができなかった。0-255への変換するのがよい。)

Verification Notes for myself

2021-8-26

  • Live Updateの動作が重い、500x700(20um/pix)を3-4枚。350x350に切り抜いて、Featureを3.5と5だけにしたらやっと動いた。おそらく、認識させたい構造が複雑になる(パターンが複雑、似ているけど異なる構造があるなど)。また、マークする筆を太くすると、動作が鈍くなる。単純なマシンパワー不足だけではなく、画像とSegmentation対象の性質にもよると思う。
  • どうやら2回(2プロジェクト、.ilp)は行うのがいいようだ。1回目:連続画像を代表するような数枚を、適当に選んで、Segmentationする。Export, Simple Segmentationを行い、画像を確認すると、かならず失敗作が含まれる。次に、2回目:失敗作だけをつかってSegmentationを行う。その結果、すべての連続切片でおおむねSegmentationが成功している。場合によっては、3回目:同様に。3回目でうまくいったことがある。
  • 学習させる画像は、3枚までが限度か。使っているのは、Core i7 4.2 GHz 4-cores、HT対応(iMac 2017)。もっとコア数があればいいのかもしれない。

2021-12-10

  • スムースに動いた。200x300pixelsの画像、1100枚の中から5枚選んでSegmentationし、1100枚にBatch。初めに3枚で行ったらキレイではなく、次に5枚にしたら成功した。MacBookPro2018 Core i9 6-cores。
  • Featureでは、Colorを重視し、EdgeとTextureは少なめに選択するなど、目的に合わせると同時に動作を軽くした。
  • 3D slicerで表示するとき、Segmentation by iLastikは200x300を使用し、MPRやVRは400x600などの高画質を使用した。解像度が異なっても、XYZサイズを入力すれば正確に重ねられる。iLastik作業を軽くすると同時に、VR, MPRは高画質で示せた。

2022-2-25 (下記のうちTIFFの症状は再現できず。2022-2-28、下記)

  • 「4. Prediction Export」で、Probabilityを出力した。Simple Segmentation(二値化した画像)とは異なり、グラデーションのあるグレースケール画像になる。画像形式では、tifかHDF5にする。
  • のちにPhotoshopを使う場合は、tifで、FIJIで開く場合はHDF5。
  • Convertでは、sign-8bit (0-255), sign-16bit (0-65535), unsign-16bit (-32768 - +32768), floating-32bitいろいろある。
  • Photoshop用のtifなら、floating-32bitを選ぶ。もしくは、チェックしない(デフォルトでfloating32bitになる)。Photoshopで開くと、レイヤーとしてProbabilityの像が表示される。ふつうの画像にする場合は、Layer>Flatten。(floating-32bit以外を選ぶと、空っぽの画像ファイルになり、Photoshopでは、なんにもなしのレイヤーができるだけ。)
  • FIJI用のHDF5なら、チェックなし(デフォルトのfloating-32bit)。
  • FIJIでHDF5を開く前に、iLastik提供のプラグインが必要。
    Help> ImageJ Updater
    Manage update sites、iLastikを選ぶ
    ImageJ Updaterウィンドウで、ボタンAdvanced Modeを押す。
    プルダウン、View uninstalled files onlyを選ぶと、plugins/ilastik4ij.jarがみえる。
    または、Searchでilastik。
    ボタンinstall, ボタンApply Change
    FIJIを再起動
  • FIJIでplug-in> ilastik> Import HDF5 より、画像を選んで開く。
    反転画像もあって、2枚として開いている。
    普通の画像に変換するには、まず、8bitに変換、TIFFででも保存。
    ただし、Save as TIFFからは、最初の一枚しか保存できない。白バックにグレーのProbabilityのみ。表示を変えていてもだめ。それで良ければ良い。もし、白バックも黒バック(反転像)も直接保存したい場合は、Save as
    Image Sequenceから、TIFFへ。末尾に01, 02がついて、2枚の画像が書き出される。

2022-2-28 上記の症状は再現できないが、TIFFでできることが分かった

  • Label1,2...が、Channel1,2...となることに気づいた。
  • Probabilityの場合。Exportで、Label (Channel)をひとつだけ指定できた。0,1を0,255へ変換できた。Channelを複数を指定すると適当な着色がなされる、Label3種はR,G,Bになった。
  • Simple Segmentationの場合。バグか。Exportで、Label(Channel)を指定できない。Renormal(0,1を0,255へ変換)できない、真っ白一辺倒の画像ができてしまう場合がある。できたのは、Label(Channel)指定しない(チェックON)、かつRenormalしない(チェックOFF)とき、Label2種から0,1へ、Label3種から0,1,2へExportできた。
  • いろいろTIFFでやってみて、PhotoshopでもFIJIでも素直に開けた。(Channelに入るという症状がなかった)

2022-3-4, 3-7

  • 快適に学習できる枚数。iMac2017-i7-4core: 500x500 pixels x 5枚。MacBookPro16-2021-M1mac-10core: 1000x1000 pixels x 10枚。
  • 手順案、1000枚の連続画像があるとき:学習5〜10枚、Exportテスト100枚、Export本番1000枚。段階的にやって、Segmentationの失敗箇所を確認・修正する。時間の節約になる。急がば回れ。

2022-7-22

  • Windowsの場合、画像のパスに日本語が入っていると、画像を読み込む細にエラーになる。(Thank you, S!)