haesleinhuepf / git-bob-bioimage-analysis-example

BSD 3-Clause "New" or "Revised" License
3 stars 0 forks source link

Segmenting images #4

Closed haesleinhuepf closed 2 months ago

haesleinhuepf commented 2 months ago

I have an RGB image that looks like this:

I would like to segment and count the objects in the blue channel. I need Python code for this, ideally using scikit-image.

haesleinhuepf commented 2 months ago

This message was generated by git-bob (version: 0.3.0, model: gpt-4o-2024-08-06), an experimental AI-based assistant. It can make mistakes and has limitations. Check its messages carefully.

To segment and count the objects in the blue channel, you can use the following Python code leveraging the scikit-image library:

import matplotlib.pyplot as plt
from skimage import io, filters, measure, morphology
from skimage.color import rgb2gray
from skimage.filters import threshold_otsu

# Load the image
image = io.imread('https://github.com/haesleinhuepf/git-bob-bioimage-analysis-example/blob/main/data/hela-cells-8bit.png?raw=true')

# Extract the blue channel
blue_channel = image[:, :, 2]

# Apply a threshold to separate the objects from the background
threshold_value = threshold_otsu(blue_channel)
binary_image = blue_channel > threshold_value

# Remove small objects and fill holes
cleaned_image = morphology.remove_small_objects(binary_image, min_size=30)
cleaned_image = morphology.remove_small_holes(cleaned_image, area_threshold=30)

# Label connected components
label_image = measure.label(cleaned_image)

# Count the objects
num_objects = label_image.max()

# Display results
plt.figure(figsize=(10, 5))

plt.subplot(1, 2, 1)
plt.title('Blue Channel')
plt.imshow(blue_channel, cmap='gray')

plt.subplot(1, 2, 2)
plt.title('Segmented Objects')
plt.imshow(label_image, cmap='nipy_spectral')

plt.suptitle(f'Number of objects detected: {num_objects}')
plt.tight_layout()
plt.show()

This code reads the image, extracts the blue channel, applies Otsu's threshold to create a binary image, cleans it by removing small objects and filling holes, labels the connected components, and finally counts the objects in the image.

haesleinhuepf commented 2 months ago

Awesome, please create a notebook for this with explanatory markdown cells in between to explain the workflow. Assume I'm a Python beginner.