我正在运行python脚本,它给出的内存不足错误。我尝试同时使用2.4.9和2.4.11执行此脚本,但出现错误。这两个版本的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
内存不足错误:
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
最佳答案
当我尝试运行使用OpenCV的python脚本时,我也遇到了相同的错误。造成我的错误的原因是程序没有剩余的可用内存,因此无法分配数组-因此触发了错误。
运行python脚本后,尝试查看正在使用的内存,并尝试优化代码,以减少RAM使用量。
关于python - opencv 2.x中的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31447210/