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 0x2448a01e9d0>
../_images/9a8c839dc0acff2ba809f86a23468055d8bdd1640593ff51f6da4c23eaeaaa5e.png

Cropping images works exactly like cropping lists and tuples, by using indices to specify the range of elements to use:

cropped_image1 = image[0:128]

imshow(cropped_image1);
../_images/166eed5c1c0ee8fe248cd58b80a3ba6890fe8f13143de5e8c646a1a7a0ab4b6e.png
mylist = [1,2,2,3,4,5,78]

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);
../_images/6984d54e12d0cfc03d33deacd59308e9501822d4506d7273fd2bebfca85d82e3.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 for example in steps of 5:

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

imshow(sampled_image);
../_images/9acacd83d855db9ff4df52fe458641d10f4ceb657e208677466e538cfd68ad56.png

Flipping images#

Negative step sizes flip the image.

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

imshow(flipped_image);
../_images/9975815040af600d91ec3649a4a64b2ef821164b2b1d7babdd7702cfab6e38c0.png

Exercise#

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