首页 > 解决方案 > 像素点变换的性能

问题描述

所以我使用 numpy 和 OpenCV 来处理一些视频。我遇到的问题是使用查找表对像素值进行点转换:

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

我使用全局变量的原因是因为我的对比函数嵌套在其他函数中。我已经测试了使用LUT作为这些函数的参数,结果它变慢了。我使用了 numpy 数组、字典、数组模块中的数组和列表,后者是最快的。到目前为止,我在每张图像上管理 0.3 秒。有没有一种明显的方法可以更快地循环像素?

提前致谢。

标签: pythonpython-3.xperformanceopencvimage-processing

解决方案


不要在像素上循环。使用 OpenCV 功能在一次调用中执行转换。作为一般经验法则,始终尽量避免使用 OpenCV 和 Python 循环像素,尤其是两者。

如何调整您的代码的示例:

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

请参阅此处的答案相关文档


推荐阅读