如果cv2.findHomography中M中的值有时为None,如何在IF中给出正确的命令



因此,我已经使用ORB工作了2/3个月

我已经为实时凸轮检测对象编写了一个简单的代码,它可以精确定位对象的中点,并从源图像中生成有界形状但有时我为cv2.findHomography((得到的M为None

我已经预料到

if len(M)>0:

但它仍然无法处理none类型并给出错误

TypeError:类型为"NoneType"的对象没有len((

我应该对此做什么更改

ps:M值示例给出

M=[[-9.30240003e-01-1.71728582e+00 6.03724232e+02]
[6.08129496e-02-1.11204061e-01 3.90162374e+01]
[1.555375499e-03-2.83800942e-03 1.00000000 e+00]

这是完整的代码:

def LIVE_CAM_ORB(live_cam):
img = live_cam
#change the camera image and input image to black and white
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#search the keypoint of live cam
kp2, des2 = orb.detectAndCompute(img,None)
# Match descriptors.
matches = bf.knnMatch(des1,des2,k=2)
# Apply ratio test
good = []
for m,n in matches:
if m.distance < 0.75*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)
#(for debugging)
#matchesMask = mask.ravel().tolist() 
print( "M = {}".format(M))
if len(M)>0:
dst = cv2.perspectiveTransform(pts,M)
(tl, tr, br, bl) = dst
midpoint = (tl+bl+br+tr)/4
midpoint = (tl[0]+bl[0]+br[0]+tr[0])/4
#midpoint = np.rint(midpoint) //round the integer
midpoint = midpoint.astype(int)
live_cam = cv2.polylines(live_cam,[np.int32(dst)],True,255,3, cv2.LINE_AA)
live_cam = cv2.circle(live_cam,(midpoint[0],midpoint[1]),5,255,-1)

感谢Burak
我刚回家尝试

if M is not None

和它的工作,谢谢

最新更新