1
votes

I have a JPEG image and I need to calculate the average value of each raster (red, blue and green) as fast as possible. When I try to use two for loops to access each pixel and add the values, the process takes quite long (about 30 seconds). Is there a way to calculate the average raster values fast (maybe using numpy and OpenCV)? The code I'm using is given below:

for i in range(width):
        for j in range(height):
            pix = im.getpixel((i,j))
            redValues = redValues + pix[0]
            greenValues = greenValues + pix[1]
            blueValues = blueValues + pix[2]
1
Can you provide a minimum working example to test your code with? Before you try and optimise with different libraries you first need to determine what's actually taking the most time. My gut feel would be the im.getpixel((i,j)) call but I'm not sure. - m4p85r
I would try something like : redValues = sum(im[:,:][0]) but I´m not sure about the syntax - hackela
See this discussion - seems PIL is the fastest library tested. But test different strategies with current versions - the thread is pretty old. - Mr. T

1 Answers

0
votes
import cv2 

## Read the image into `BGR`: (H,W,3), [[B,G,R],...]
img = cv2.imread("test.png")

## Get shape
H,W = img.shape[:2]

## calculate 
avg = img.reshape(-1,3).sum(axis=0)/(H*W)
print(avg)