基于给定的矩阵在openCV中构造一个矩阵

Construct a matrix in openCV based on a given matrix

本文关键字:一个 openCV      更新时间:2023-10-16

我正在使用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中显示解决方案。)

edit:您可能想要使用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