Center clipping numpy array

I'm trying to trim a numpy array [width x height x color] to a predefined smaller size.

I found something that should do what I want, but it only works for [width x height] arrays. I don't know how to make it work for a numpy array that has an extra size for the color.

slice part in the middle of numpy image

+4


source to share


3 answers


With numpy

you can use range indices. Let's say you have a list x[]

(one dimension), you can index it as x[start:end]

a slice.

The slices can be used in higher sizes as

x[start1:end1, start2:end2, start3:end3]

      



This might be what you are looking for.

Though remember that this does not create a new array (i.e. it does not copy). Changes to this will be reflected in x

.

Thanks to @coderforlife for pointing out the bug in the wrong post I posted earlier.

+4


source


From the question you linked to, this is just a small change in the code:

def crop_center(img,cropx,cropy):
    y,x,c = img.shape
    startx = x//2 - cropx//2
    starty = y//2 - cropy//2    
    return img[starty:starty+cropy, startx:startx+cropx, :]

      



All that was added is one more :

to the end of the last line and (unused) c

for unpacking the form.

>>> img
array([[[ 18,   1,  17],
        [  1,  13,   3],
        [  2,  17,   2],
        [  5,   9,   3],
        [  0,   6,   0]],

       [[  1,   4,  11],
        [  7,   9,  24],
        [  5,   1,   5],
        [  7,   3,   0],
        [116,   1,  55]],

       [[  1,   4,   0],
        [  1,   1,   3],
        [  2,  11,   4],
        [ 20,   3,  33],
        [  2,   7,  10]],

       [[  3,   3,   6],
        [ 47,   5,   3],
        [  4,   0,  10],
        [  2,   1,  35],
        [  6,   0,   1]],

       [[  2,   9,   0],
        [ 17,  13,   4],
        [  3,   0,   1],
        [ 16,   1,   3],
        [ 19,   4,   0]],

       [[  8,  19,   3],
        [  9,  16,   7],
        [  0,  12,   2],
        [  4,  68,  10],
        [  4,  11,   1]],

       [[  0,   1,  14],
        [  0,   0,   4],
        [ 13,   1,   4],
        [ 11,  17,   5],
        [  7,   0,   0]]])
>>> crop_center(img,3,3)
array([[[ 1,  1,  3],
        [ 2, 11,  4],
        [20,  3, 33]],

       [[47,  5,  3],
        [ 4,  0, 10],
        [ 2,  1, 35]],

       [[17, 13,  4],
        [ 3,  0,  1],
        [16,  1,  3]]])

      

+2


source


numpy works for any dimension

import numpy as np
X = np.random.normal(0.1, 1., [10,10,10])
X1 = X[2:5, 2:5, 2:5]
print(X1.shape)

      

the last print statements result in the array [3,3,3].

0


source







All Articles