0

So my question is quite similar to this post: Most efficient way to map function over numpy array, but I have some additional questions to add along.

Right now, I'm taking in an image represented by a 2-D array, and for each pixel in the image, I am doing some computation that involves convolving the nxn neighboring pixels with a Gaussian kernel to find a "weight" for each pixel. My end goal is to return a 2-D array of the same size as the input, with the calculated weight in place of each pixel.

So what I did was to first create a function getWeight that, given a pixel, does the necessary computation using its neighbors and a Gaussian kernel to find its corresponding weight.

So my question is: given getWeight is using a for-loop, or the numpy.fromiter, to apply this function to every pixel in the 2-D array the best way to go about solving this problem?

Or could there be a way to use built-in np functions to apply this sort of operation on the entirety of the array at once? (This question is kind of vague, but what I am trying to get at is that since numpy operations on arrays are not actually done by "using a for loop for every pixel", whether there could be something I could use to optimize my problem).

chemo
  • 163
  • 2
  • 3
  • 9
  • 1
    SciPy comes with [functions for that kind of thing](https://docs.scipy.org/doc/scipy/reference/signal.html), and [scikit-image](http://scikit-image.org/docs/dev/api/skimage.html) probably has a bunch of relevant stuff too. – user2357112 Mar 28 '18 at 00:02
  • OpenCV also [supports convolutions](https://docs.opencv.org/2.4/doc/tutorials/imgproc/imgtrans/filter_2d/filter_2d.html), including custom kernels – Marat Mar 28 '18 at 00:22
  • Couldn't exactly find what I was looking for in the links given, but I think `scipy.ndimage.filters.convolve` is sort of what I was looking for. However, I still have another question in general–––if I am not convolving, but rather applying some function `x`, then would the fastest way to apply `x` to every pixel in the 2-D array be through a for-loop and/or `numpy.fromiter`? – chemo Mar 28 '18 at 00:44
  • Have a look at Numba. You can loop as much as you want and also call compiled function in an efficient way. eg. https://stackoverflow.com/a/49514666/4045774 or https://stackoverflow.com/a/49321971/4045774 – max9111 Mar 28 '18 at 13:21

0 Answers0