0

I have an image of shape (31278,25794,3). I would like to know how is possible to obtain MxN segment of the picture, using np functions. For example starting from: enter image description here

I would like to obtain:

enter image description here

domiziano
  • 440
  • 3
  • 13
  • Does this answer your question? [Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)?](https://stackoverflow.com/questions/4257394/slicing-of-a-numpy-2d-array-or-how-do-i-extract-an-mxm-submatrix-from-an-nxn-ar) – Random Davis Nov 18 '20 at 22:19
  • Making `M` and `N` both equal 2 surely isn't the best way of clarifying what you want! – Mark Setchell Nov 18 '20 at 22:55

1 Answers1

1

In numpy you can split a picture like you slice an array.

Here's an example with your image:

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image

img = np.array(Image.open("cat.jpg"))
plt.imshow(img)

enter image description here

xs = img.shape[0]//2  # division lines for the picture
ys = img.shape[1]//2
# now slice up the image (in a shape that works well with subplots)
splits = [[img[0:xs, 0:ys], img[0:xs, ys:]], [img[xs:, 0:ys], img[xs:, ys:]]]

fig, axs = plt.subplots(2, 2)
for i in range(2):
    for j in range(2):
        axs[i][j].imshow(splits[i][j])

enter image description here

Keep in mind that the splits here are views into the original array, not arrays with new data, so changes you make to the views will change the original data. If you don't want this, you can do something to copy the data after slice up the array.

tom10
  • 67,082
  • 10
  • 127
  • 137