0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Pythonを使用した、免疫染色画像の自動解析について

Last updated at Posted at 2024-01-29

大量に撮影した、免疫染色画像(DABによる茶色)を認識し、面積比としてExcelファイルに出力するコード。
細胞をひとつひとつ認識する手法よりも処理が早く、標本の品質に左右されにくいためこちらの手法を採用することが多い。
Code for recognizing a large number of immunostained images (brown with DAB) and outputting the area ratio as an Excel file.
This method is often adopted because it processes faster than techniques that recognize each cell individually and is less affected by the quality of the specimen.

# Importing necessary libraries
import cv2
import numpy as np
import os
import pandas as pd

# Defining the HSV range for brown color
brown_lower = np.array([0, 100, 20])
brown_upper = np.array([30, 255, 200])

# Path to the folder containing sample images
sample_folder = 'sample'

# Retrieving image files from the folder, excluding files starting with 'mask_'
image_files = [f for f in os.listdir(sample_folder) if (f.endswith('.JPG') or f.endswith('.jpg')) and not f.startswith('mask_')]

# List to store the results
results = []

# Calculating the ratio of the brown area for each image
for image_file in image_files:
    # Loading the image
    image_path = os.path.join(sample_folder, image_file)
    image_cv = cv2.imread(image_path)

    # Converting to HSV color space
    hsv_image = cv2.cvtColor(image_cv, cv2.COLOR_BGR2HSV)

    # Creating a mask (extracting brown areas)
    brown_mask = cv2.inRange(hsv_image, brown_lower, brown_upper)

    # Calculating the area of the brown region
    brown_area = np.sum(brown_mask > 0)
    total_area = image_cv.shape[0] * image_cv.shape[1]
    brown_ratio = 100 * brown_area / total_area

    # Adding the result to the list
    results.append({
        "Image File": image_file,
        "Brown Area Ratio": brown_ratio
    })

# Converting the results to a DataFrame
results_df = pd.DataFrame(results)

# Outputting the results to an Excel file
output_excel_path = 'brown_area_ratios.xlsx'
results_df.to_excel(output_excel_path, index=False)

print(f"Results are saved to {output_excel_path}")

簡単な解説 Brief Explanation

中身についての解説。
An explanation of the contents.

1.ライブラリのインポート Importing Libraries

まずは必要なライブラリのインポートを行う。

  • OpenCV (cv2): 画像およびビデオ処理のためのツールを提供するライブラリ。
  • NumPy: 高性能な数学演算、特に配列操作に使用される。
  • os: ファイル名の読み取りなど、ファイルシステムとのやり取りを行う。
  • pandas: データの操作と分析に使用され、特に構造化されたデータの取り扱いに有用。
    Importing Libraries
    First, import the necessary libraries.
    OpenCV (cv2): Provides tools for image and video processing.
    NumPy: Used for high-performance mathematical operations, especially array manipulations.
    os: Interacts with the file system, like reading file names.
    pandas: Used for data manipulation and analysis, particularly useful for handling structured data.
import cv2
import numpy as np
import os
import pandas as pd

2.茶色の色空間を定義 Defining the Color Space for Brown

RGB空間より色検出に優れるHSV(色相、彩度、明度)色空間にて、今回必要な茶色を定義する。
Define the required brown color using the HSV (Hue, Saturation, Value) color space, which is superior for color detection compared to RGB space.

brown_lower = np.array([0, 100, 20])
brown_upper = np.array([30, 255, 200])

3.サンプル画像の処理 Processing Sample Images

コード実行場所と同階層にあるsampleフォルダに格納された、拡張子がJPGのファイルを認識する。
mask_で始まるファイルは次のカウントのため生成された画像なので、除外する。
Recognizes files with a JPG extension stored in the sample folder located at the same level as the code execution location. Excludes images starting with 'mask', which are generated for subsequent counts._

# Path to the folder containing sample images
sample_folder = 'sample'

# Retrieving image files from the folder, excluding files starting with 'mask_'
image_files = [f for f in os.listdir(sample_folder) if (f.endswith('.JPG') or f.endswith('.jpg')) and not f.startswith('mask_')]

# List to store the results
results = []

4.茶色を認識し面積を計算する Recognizing Brown and Calculating Area

各画像をHSV色空間に変換し、定義された茶色領域を分離するためのマスク画像を生成する。
画像の総面積に対し、茶色と認識された領域の割合を計算する。
Converts each image to the HSV color space and generates a mask image to separate the defined brown area. Calculates the ratio of the brown area recognized against the total area of the image.

# Calculating the ratio of the brown area for each image
for image_file in image_files:
    # Loading the image
    image_path = os.path.join(sample_folder, image_file)
    image_cv = cv2.imread(image_path)

    # Converting to HSV color space
    hsv_image = cv2.cvtColor(image_cv, cv2.COLOR_BGR2HSV)

    # Creating a mask (extracting brown areas)
    brown_mask = cv2.inRange(hsv_image, brown_lower, brown_upper)

    # Calculating the area of the brown region
    brown_area = np.sum(brown_mask > 0)
    total_area = image_cv.shape[0] * image_cv.shape[1]
    brown_ratio = 100 * brown_area / total_area

    # Adding the result to the list
    results.append({
        "Image File": image_file,
        "Brown Area Ratio": brown_ratio
    })

# Converting the results to a DataFrame
results_df = pd.DataFrame(results)

5.結果をExcelファイルに出力する Outputting Results to an Excel File

その後の統計解析を行うため、Excelファイルに結果をまとめ出力する。
For subsequent statistical analysis, the results are compiled and output as an Excel file.

# Outputting the results to an Excel file
output_excel_path = 'brown_area_ratios.xlsx'
results_df.to_excel(output_excel_path, index=False)

print(f"Results are saved to {output_excel_path}")

細胞を認識して陽性比率を計算する、バックグラウンドは除外し組織のみで面積比を計算するなど、改善点はいくらでもある。
しかし細胞認識やバックグラウンドの認識は、撮影された画像のクオリティに大きく左右されるため、簡便さを欠く。
このため、大量の免疫染色画像について解析する場合に私はこの手法を用いることとしている。
There are always improvements to be made, such as recognizing cells to calculate the positive ratio or excluding the background and calculating the area ratio for tissue only. However, cell recognition and background recognition are greatly influenced by the quality of the captured images, lacking simplicity. Therefore, I use this method for analyzing a large number of immunostained images.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?