image-processing
Image Threshold and Region Labeling
Read an image, threshold it, label connected components — the 'hello world' of Image Processing Toolbox.
The Image Processing Toolbox functions `imread`, `rgb2gray`, `imbinarize`, and `bwlabel` map to scikit-image and scipy.ndimage equivalents. The mapping is straightforward; the main difference is that scikit-image returns float images in [0, 1] by default where MATLAB returns uint8 in [0, 255].
MATLAB source10 lines
% Threshold an image and count blobs
img = imread('cells.png');
gray = rgb2gray(img);
bw = imbinarize(gray);
[labeled, n] = bwlabel(bw);
figure
subplot(1, 3, 1); imshow(gray); title('grayscale');
subplot(1, 3, 2); imshow(bw); title('binary');
subplot(1, 3, 3); imshow(label2rgb(labeled)); title([num2str(n), ' regions']);Python output (converter-generated)20 lines · 6 flags
from skimage import io, color, measure
import matplotlib.pyplot as plt
# Threshold an image and count blobs
img = io.imread('cells.png')
gray = color.rgb2gray(img)
bw = imbinarize(gray)
labeled, n = measure.label(bw)
plt.figure()
plt.subplot(1, 3, 1)
plt.imshow(gray)
plt.title('grayscale')
plt.subplot(1, 3, 2)
plt.imshow(bw)
plt.title('binary')
plt.subplot(1, 3, 3)
plt.imshow(label2rgb(labeled))
plt.title([str(n), ' regions'])
Converter flags (6)
- TOOLBOXLine 2: imread → io.imread — MATLAB imread returns uint8 by default. skimage.io.imread returns uint8 too, but use img_as_float() if you need [0,1] range.
- TOOLBOXLine 3: rgb2gray → color.rgb2gray — MATLAB rgb2gray returns uint8. skimage.color.rgb2gray returns float64 in [0,1]. Multiply by 255 and cast to uint8 if needed.
- TOOLBOXLine 5: bwlabel → measure.label (Image Processing Toolbox) — check that arguments and return values match. Some functions have different default parameters or output formats.
- TOOLBOXLine 8: imshow → plt.imshow (Image Processing Toolbox) — check that arguments and return values match. Some functions have different default parameters or output formats.
- TOOLBOXLine 9: imshow → plt.imshow (Image Processing Toolbox) — check that arguments and return values match. Some functions have different default parameters or output formats.
- TOOLBOXLine 10: imshow → plt.imshow (Image Processing Toolbox) — check that arguments and return values match. Some functions have different default parameters or output formats.
Implementation notes
The output uses `skimage.io.imread` and `skimage.measure.label`. If you call it with a URL, you may need `skimage.io.imread(url, plugin="imageio")` depending on your scikit-image version.Try it on your own MATLAB
Free for 50 lines. Same converter that produced the Python above.
More examples like this, once a week
New canonical conversions and release notes from the converter. One email, no spam.