Jkind9
Jkind9

Reputation: 740

Performance for pixel point transformations

So I'm using numpy and OpenCV to process a few videos. The problem I'm having is using a lookup table to do a point transformation on the pixel values:

def sig(x,factor):
    if x == 255:
        return 255
    elif x!=0:
        return int(255*(1- 1/(1+(255/x -1)**(-factor))))
    else:
        return 0

def Constrast(img):
    global LUT
    for x in range(len(img)):
        for y in range(len(img[0])):
            img[x,y] = LUT[img[x,y]]
    return img

 def Enhance(img):
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    #Some other functions here
    img = Constrast(img) # This one thing takes 0.3 seconds
    #Do more stuff here

factor = .8
LUT = []
for i in range(256):
    LUT.append(sig(i,factor))
Enhance(img) # Enhancing a greyscale image

The reason I am using a global variable is because my contrast function is nested in other functions. I have tested using LUT as an argument to these functions and it turned out slower. I have used numpy arrays, dictionaries, arrays from the array module and lists, with the latter being the fastest. So far I'm managing 0.3s on every image. Is there an obvious way of making the process of looping through pixels quicker?

Thanks in advance.

Upvotes: 0

Views: 104

Answers (1)

ypnos
ypnos

Reputation: 52337

Do not loop over the pixels. Use OpenCV functionality to perform the transformation in one call. As a general rule-of-thumb, always try to avoid looping over pixels with OpenCV, and with Python, and especially with both.

An example how your code could be adapted:

def Constrat(img):
    global LUT
    img = cv2.LUT(img, LUT)
    return img

See the answer here and relevant documentation.

Upvotes: 2

Related Questions