Cropping images#

When working with microscopy images, it often makes limited sense to process the whole image. We typically crop out interesting regions and process them in detail.

from skimage.io import imread, imshow
image = imread("../../../data/blobs.tif")

Before we can crop an image, we may want to know its precise shape (dimensions):

image.shape
(254, 256)

Recap: Visualization using imshow:

imshow(image)
<matplotlib.image.AxesImage at 0x219cf257490>
../../_images/604b3fbfdd58c61b88f6ddf43119bbee141d7731b935a02a08cdae183c10f71b.png

Cropping images works exactly like cropping lists and tuples:

cropped_image1 = image[0:128]

imshow(cropped_image1)
<matplotlib.image.AxesImage at 0x219cf20e0e0>
../../_images/543e0e6a678a0cc69f9263670bf93b88ab7aafb500d894b11910194766fc3c47.png

To crop the image in the second dimension as well, we add a , in the square brackets:

cropped_image2 = image[0:128, 128:]

imshow(cropped_image2)
<matplotlib.image.AxesImage at 0x219d05257e0>
../../_images/438009afd5bdcfbcfbe59a845b8e2d28b27738bb8ec918a1bc204f68eb22a1b7.png

Sub-sampling images#

Also step sizes can be specified as if we would process lists and tuples. Technically, we are sub-sampling the image in this case. We sample a subset of the original pixels:

sampled_image = image[::5, ::5]

imshow(sampled_image)
<matplotlib.image.AxesImage at 0x219d0593490>
../../_images/d332c1588602573199ce090b26772a3648d1cca72aea5db9f6676128200e8b0d.png

Flipping images#

Negative step sizes flip the image.

flipped_image = image[::, ::-1]

imshow(flipped_image)
<matplotlib.image.AxesImage at 0x219d05f7cd0>
../../_images/6ba21ef23b12059fbf4dff5ab178792a1309480ffc878cd500e1290cec037690.png

Exercise#

Open the banana020.tif data set and crop out the region where the banana slice is located.