下面中cap的内容选的是0,表示启动摄像头0(如果只有一个摄像头的话,就直接找到对应的那个)。 注释部分,其实是背景提取后的效果,或者是提取之后的再做阈值的处理后的图片 import cv2 cap = cv2 .VideoCapture ( 0 ) bs = cv2 .createBackgroundSubtractorKNN (detectShadows=True) while True: ret , frame = cap .read () fgmask = bs .apply (frame) th = cv2 .threshold (fgmask .copy (), 244 , 255 , cv2 .THRESH _BINARY)[ 1 ] dilated = cv2 .dilate (th, cv2 .getStructuringElement (cv2 .MORPH _ELLIPSE, ( 3 , 3 )), iterations= 2 ) image, content, hier = cv2 .findContours (dilated, cv2 .RETR _EXTERNAL, cv2 .CHAIN _APPROX_SIMPLE) for c in content: if cv2 .contourArea (c) > 1600 : ( x , y , w, h) =