Search code examples
pythonnumpymatrixscipysubmatrix

Problems when extracting a submatrix


I am writing a piece of code to extract a submatrix from a matrix. As modules, I imported scipy and Image. When I run the script, I got the error

submatrix = im[x_min:x_max, y_min:y_max]
TypeError: an integer is required

I checked and the min and max values are effectively integers... do you have any suggestion on how to fix this?

x_min = int(x - 50)
x_max = int(x + 50)
y_min = int(y - 50)
y_max = int(y + 50)
if x_min < 0:
    x_min = 0
    continue
if y_min < 0:
    y_min = 0
    continue
if x_max > 2160:
    x_max = 2160
    continue
if y_max > 2592:
    y_max = 2592
    continue
submatrix = im[x_min:x_max, y_min:y_max]
figure(1)
imshow(submatrix)
break

Solution

  • If you use import Image then your im object is not an numpy array but a PixelAccess object.
    So if you really want a numpy array you could use imread instead of Image.open.

    A minimal example (with x_min etc. being int) would be

    import matplotlib.pyplot as plt
    im = plt.imread("/...image_%03i.tif" % (index))
    submatrix = im[x_min:x_max, y_min:y_max]
    plt.figure(1)
    plt.imshow(submatrix)
    plt.show()