I am trying to crop a numpy array [width x height x color] to a predefined smaller dimension.
I found something that should do what I want but it works only for [width x height] arrays. I don't know how to make it work for a numpy array that has an extra dimension for color.
crop center portion of a numpy image
Numpy doesn't have a specific crop function for images, but if we utilize indexing, we can crop out whatever part of any image we want. This is usually in a square or rectangle shape. So in this article, we will read an image in using the OpenCV module, then we will use numpy to crop out a portion of the image.
Numpy is restricted to single-threading in many cases, it requires to manually vectorization of code which can become hard to read, and is much slower than the two alternatives. Fortran offers great performance with pretty simple code.
With numpy
you can use range indexes. Say you have a list x[]
(single dimension), you can index it as x[start:end]
this is called a slice.
Slices can be used with higher dimensions too like
x[start1:end1, start2:end2, start3:end3]
This might be what you are looking for.
Although remember this doesn't generate a new array (ie it doesn't copy). Changes to this will reflect into x
.
Thanks to @coderforlife for pointing out the error in the wrong notation I had put down before.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With