【问题标题】:Construct a matrix in openCV based on a given matrix基于给定矩阵在openCV中构造一个矩阵
【发布时间】:2013-08-11 10:17:22
【问题描述】:

我正在使用 Python 中的 OpenCV 库编写一些代码。在这个过程中,我需要根据给定的另一个矩阵构造一个矩阵。现在我的代码如下所示:

for x in range(0, width):
    for y in range(0, height):
        if I_mat[x][y]>=0 and I_mat[x][y]<=c_low:
            w_mat[x][y] = float(I_mat[x][y])/c_low
        elif I_mat[x][y]>c_low and I_mat[x][y]<c_high:
            w_mat[x][y] = 1
        else:
            w_mat[x][y] = float((255-I_mat[x][y]))/float((255-c_high))

其中,I_mat 是输入矩阵,w_mat 是我要构建的矩阵。由于输入矩阵很大,所以这个算法很慢。我想知道是否还有其他方法可以更有效地构造 w_mat。非常感谢!

(无需在 Python 中显示解决方案。)

【问题讨论】:

    标签: c++ python opencv computer-vision


    【解决方案1】:

    编辑:你可能想使用 numba

    import numpy as np
    import timeit
    from numba import void,jit
    
    c_low = .3
    c_high = .6
    def func(val):
        if val>=0 and val<=c_low:
            return float(val)/c_low
        elif val>c_low and val<c_high:
            return 1.
        else:
            return (255.-val)/(255.-c_high)
    
    def npvectorize(): 
        global w_mat
        vfunc = np.vectorize(func)
        w_mat = vfunc(I_mat)
    
    def orig():
        for x in range(I_mat.shape[0]):
            for y in range(I_mat.shape[1]):
                if I_mat[x][y]>=0 and I_mat[x][y]<=c_low:
                    w_mat[x][y] = float(I_mat[x][y])/c_low
                elif I_mat[x][y]>c_low and I_mat[x][y]<c_high:
                    w_mat[x][y] = 1
                else:
                    w_mat[x][y] = float((255-I_mat[x][y]))/float((255-c_high))
    
    I_mat = np.array(np.random.random((1000,1000)), dtype = np.float)
    w_mat = np.empty_like(I_mat)
    
    fast = jit(void(),nopython=True)(orig)
    
    print timeit.Timer(fast).timeit(1)
    print timeit.Timer(npvectorize).timeit(1)
    print timeit.Timer(orig).timeit(1)    
    

    输出:

    0.0352660446331
    0.472590475098
    4.78634474265
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 2016-11-17
      • 1970-01-01
      相关资源
      最近更新 更多