内存泄漏使用Python中的OpenCV调整linux上的映像numpy数组

时间:2012-04-19 22:43:12

标签: python linux image opencv numpy

我有以下代码,用于在Python中使用OpenCV调整图像numpy数组的大小。它在我的Windows桌面上运行良好,但在Linux(ubuntu)上有内存泄漏。处理了数百张图像(9000x9000像素)后,它会占用所有内存。任何提示?


import cv2.cv as cv
def resizeMemLeak(imArray, size=(1000,1000), interp=cv.CV_INTER_LINEAR):
    """
    Resize a numpy array to size given by rows and cols, the array is first 
    converted into cv.mat image to do the resize.   
    @param inArray: numpy array to be resized
    @param size: int   - Percentage of current size
                 float - Fraction of current size
                 tuple - Size of the output image
    @type size: {int, float, tuple}
    @param interp: {cv.CV_INTER_LINEAR [default], 
                    cv.CV_INTER_NN, 
                    cv.CV_INTER_AREA,
                    cv.CV_INTER_CUBIC }
    @return: the resized numpy array kept the same dtype.
    """
    # make a copy of the input array to avoid OpenCV step bug
    import copy
    imCopy = copy.deepcopy(imArray)
    mat = cv.fromarray(imCopy, allowND=False)
    if len(imCopy.shape) == 2:
        assert mat.channels == 1
    elif len(imCopy.shape) == 3:
        assert mat.channels == imArray.shape[2]
    else:
        raise TypeError("unknown image array")
    import numpy as np
    if imCopy.dtype == np.uint8:
        assert mat.step // mat.cols == mat.channels
    elif imCopy.dtype == np.uint16:
        assert mat.step // mat.cols == 2 * mat.channels
    elif imCopy.dtype == np.int32:
        assert mat.step // mat.cols == 4 * mat.channels
    else:
        raise TypeError("unknown image array")
    if type(size) is int:
        assert 0 < size
        rows = mat.rows * size // 100
        cols = mat.cols * size // 100
    elif type(size) is float:
        assert 0.0 < size
        rows = int( mat.rows * size )
        cols = int( mat.cols * size )
    elif type(size) is tuple:
        assert len(size) == 2
        rows = int(size[0])
        cols = int(size[1])
    else:
        raise TypeError("parameter size: wrong type.")
    imResized = cv.CreateMat(rows, cols, mat.type)
    cv.Resize(mat, imResized)
    resized = np.asarray(imResized)
    return resized

配置:

  • Linux,Ubuntu,8G内存,安装为虚拟机。
  • python2.7 / oneiric uptodate 2.7.2-5ubuntu1
  • python-opencv / oneiric uptodate 2.1.0-7build1
  • python-numpy / oneiric uptodate 1:1.5.1-2ubuntu2

谢谢!

0 个答案:

没有答案