简体   繁体   中英

Memory leak in opencv 2.x

I'm running a python script and it is giving insufficient memory error. I tried executing this script with both 2.4.9 and 2.4.11 and got the error. Is there any issue with these 2 versions of opencv?


import numpy as np
import cv2

MIN_MATCH_COUNT = 10

img1 = cv2.imread('./DSC_0022.jpg',0)          # queryImage
img2 = cv2.imread('./template.jpg',0) # trainImage

# Initiate SIFT detector
sift = cv2.SIFT()

# find the keypoints and descriptors with SIFT
kp1, des1 = sift.detectAndCompute(img1,None)
kp2, des2 = sift.detectAndCompute(img2,None)

FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
search_params = dict(checks = 50)

flann = cv2.FlannBasedMatcher(index_params, search_params)

matches = flann.knnMatch(des1,des2,k=2)

# store all the good matches as per Lowe's ratio test.
good = []
for m,n in matches:
if m.distance < 0.7*n.distance:
    good.append(m)

if len(good)>MIN_MATCH_COUNT:
   src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,1,2)
   dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1,1,2)

   M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC,5.0)
   matchesMask = mask.ravel().tolist()

   h,w = img1.shape
   pts = np.float32([ [0,0],[0,h-1],[w-1,h-1],[w-1,0] ]).reshape(-1,1,2)
   dst = cv2.perspectiveTransform(pts,M)

   img2 = cv2.polylines(img2,[np.int32(dst)],True,255,3, cv2.LINE_AA)

else:
   print "Not enough matches are found - %d/%d" % (len(good),MIN_MATCH_COUNT)
   matchesMask = None

Insufficient Memory Error:

C:\>fe.py
OpenCV Error: Insufficient memory (Failed to allocate 139253572 bytes) in cv::OutOfMemoryError, file ..\..\..\..\opencv\modules\core\src\alloc.cpp, line 52
Traceback (most recent call last):
File "C:\fe.py", line 15, in <module>
    kp2, des2 = sift.detectAndCompute(img2,None)
cv2.error: ..\..\..\..\opencv\modules\core\src\alloc.cpp:52: error: (-4) Failed to allocate 139253572 bytes in function cv::OutOfMemoryError

I was also getting the same error when I was trying to run a python script that was using OpenCV. My error was caused because there was no free memory left for the program and thus allocation of arrays wasn't possible - hence triggering the error.

Try seeing for what the memory is being used after running the python script and try optimizing the code so that RAM usage is reduced.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM