1

Let's say I have a numpy array of shape (100, 100, 3), and that it represents an image in RGB encoding. How do I iterate over the individual pixels of this image.

Specifically I want to map this image with a function.

Note, I got that array from opencv.

saga
  • 1,933
  • 2
  • 17
  • 44
  • numpy has something called `np.nditer()`. You can look into that. When you say iterate over pixels what do you really mean, you mean iterating over the entire array over x and y using all 3 z? What are you passing to the function? – Alexis Drakopoulos Oct 23 '18 at 09:44
  • @AlexisDrakopoulos Yes, the function will get a 3-pair and return another one. – saga Oct 23 '18 at 09:46
  • not sure if there are any official methods, you could just run a zipped for loop? – Alexis Drakopoulos Oct 23 '18 at 09:46
  • @AlexisDrakopoulos That's quite slow, I'm processing a video and for loop takes 2 seconds for a frame. I think numpy provides some fast way to iterate over the arrays. – saga Oct 23 '18 at 09:48
  • yep it would be very inefficient, I was just offering a brute-force attempt, hence why I didn't post it as an answer, hopefully someone comes along with a proper solution – Alexis Drakopoulos Oct 23 '18 at 09:50
  • `for pix in img.reshape(-1, 3): print(pix)` – Kinght 金 Oct 23 '18 at 09:50
  • You should have a look at this : https://stackoverflow.com/questions/35215161/most-efficient-way-to-map-function-over-numpy-array – Tony Pellerin Oct 23 '18 at 09:50
  • 2
    You should avoid iterating over the numpy arrays in Python, there are a lot of in-built methods which can be used to apply an operation over the whole matrix. Can you please descrive what you actually want to achieve ? – ZdaR Oct 23 '18 at 09:59
  • @ZdaR I have a function and I want to map all the pixels in the image with it. – saga Oct 23 '18 at 10:05
  • @saga The point is, processing pixel by pixel in the interpreter will be slow. If you can show the exact function you want to apply, we can try to give you some concrete advice. – Dan Mašek Oct 23 '18 at 10:13
  • Please have a look at this [thread](https://stackoverflow.com/questions/35215161/most-efficient-way-to-map-function-over-numpy-array) – ZdaR Oct 23 '18 at 10:14
  • @Alexis, `nditer` would be a bad idea. It would iterate over array elements, not pixels. – hpaulj Oct 23 '18 at 15:20

0 Answers0