python matplotlib.pyplot imread

user3284140 picture user3284140 · May 18, 2015 · Viewed 14.4k times · Source

I'm using plt.imread for reading big .tiff images. Because of the big dimensions, I would like to select just a part of the image to be loaded. I would like to do something like:

plt.imread(filename, [s1:s2, r1:r2])

choosing the initial and final pixel for both dimensions.

Is there a way to do this?

Many thanks

Answer

tmdavison picture tmdavison · May 19, 2015

I think you have to read the entire image, after which you can slice it before you do any processing on it:

import matplotlib.pyplot as plt
my_img = plt.imread('my_img.tiff')
my_clipped_img = my_img[s1:s2,r1:r2]

or, in one line:

import matplotlib.pyplot as plt
my_img = plt.imread('my_img.tiff')[s1:s2,r1:r2]

The latter has the benefit of not creating a full sized array, but just of the size you want.

Bear in mind that s1:s2 here should be your limits in the vertical direction, and r1:r2 in the horizontal direction.