0

Explanation

I have a bunch of 450x450 images, and I am looking at each color channel individually. So what I have is a 1D numpy array of length 450*450*numImages. I want to take a box of some size, say 3x3 or 5x5 around each pixel and get the average of those pixel values. So by the end I will still have a 450*450*numImages array, it will just now hold those averages. Imagine something like this where we have one 14x14 image and we're just looking at one of the color channels and taking a 3x3 box average:

Box average

Current Implementation

iWidth=450
def boxAverage(imageArr, box_scale=1):
   avgs=[]
   for i in range(len(imageArr)):
      avg=0
      avgCount=0
      for j in range(-box_scale,box_scale):
         for k in range(-box_scale*iWidth,box_scale*iWidth,iWidth):
            try:
               temp = imageArr[i+k+j]
            except IndexError:
               temp = -1
            if temp != -1:
               avg+=temp
               avgCount+=1
      avg/=avgCount
      avgs.append(avg)

When box_scale = 1, it is a 3x3 box that I am taking the average of and when box_scale=2, it is 5x5, etc.

Problem

This does not scale very well and as I work with more and more images, this gets very slow. So I was wondering if there is a good way using something like numpy to do this in a way that can be done more efficiently. I appreciate any suggestions you might have!

  • 2
    Does this answer your question? [Numpy Two-Dimensional Moving Average](https://stackoverflow.com/questions/23000260/numpy-two-dimensional-moving-average) – Lydia van Dyke Apr 05 '20 at 19:39
  • Filtering and convolution go hand in hand. Wikipedia is your friend. I've been in your place before, and ended up making a career of diving down that particular rabbit hole. Enjoy. – Mad Physicist Apr 05 '20 at 22:42

0 Answers0