.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "advanced/image_processing/auto_examples/plot_find_object.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code .. rst-class:: sphx-glr-example-title .. _sphx_glr_advanced_image_processing_auto_examples_plot_find_object.py: Find the bounding box of an object =================================== This example shows how to extract the bounding box of the largest object .. GENERATED FROM PYTHON SOURCE LINES 8-43 .. image-sg:: /advanced/image_processing/auto_examples/images/sphx_glr_plot_find_object_001.png :alt: plot find object :srcset: /advanced/image_processing/auto_examples/images/sphx_glr_plot_find_object_001.png :class: sphx-glr-single-img .. code-block:: default import numpy as np import scipy as sp import matplotlib.pyplot as plt np.random.seed(1) n = 10 l = 256 im = np.zeros((l, l)) points = l*np.random.random((2, n**2)) im[(points[0]).astype(int), (points[1]).astype(int)] = 1 im = sp.ndimage.gaussian_filter(im, sigma=l/(4.*n)) mask = im > im.mean() label_im, nb_labels = sp.ndimage.label(mask) # Find the largest connected component sizes = sp.ndimage.sum(mask, label_im, range(nb_labels + 1)) mask_size = sizes < 1000 remove_pixel = mask_size[label_im] label_im[remove_pixel] = 0 labels = np.unique(label_im) label_im = np.searchsorted(labels, label_im) # Now that we have only one connected component, extract it's bounding box slice_x, slice_y = sp.ndimage.find_objects(label_im==4)[0] roi = im[slice_x, slice_y] plt.figure(figsize=(4, 2)) plt.axes([0, 0, 1, 1]) plt.imshow(roi) plt.axis('off') plt.show() .. rst-class:: sphx-glr-timing **Total running time of the script:** ( 0 minutes 0.024 seconds) .. _sphx_glr_download_advanced_image_processing_auto_examples_plot_find_object.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_find_object.py ` .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_find_object.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_