PyCharm中cv2函数无代码补全,OpenCV运动检测矩形不显示问题
问题解决:OpenCV运动检测系统的两个问题
问题1:PyCharm中cv2函数无代码补全提示
- 卸载当前
opencv-python,重新安装带类型提示的包:pip uninstall opencv-python pip install opencv-python-headless opencv-contrib-python - 若无效,打开PyCharm的
File > Settings > Project: [你的项目名] > Python Interpreter,确认opencv-python-headless或opencv-contrib-python已安装,重启PyCharm。 - 检查虚拟环境配置,确保PyCharm使用的解释器是安装了OpenCV的目标虚拟环境。
问题2:添加轮廓过滤后无矩形显示
你的代码核心问题是**continue语句的缩进错误**,continue会直接跳过当前循环的剩余代码,导致后续的矩形绘制逻辑永远无法执行。
修正后的完整代码:
import cv2 cam = cv2.VideoCapture(0) while True: ret, frame1 = cam.read() ret, frame2 = cam.read() diff = cv2.absdiff(frame1, frame2) gray = cv2.cvtColor(diff, cv2.COLOR_RGB2GRAY) blur = cv2.GaussianBlur(gray, (5, 5), 0) _, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY) dilated = cv2.dilate(thresh, None, iterations=3) contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # cv2.drawContours(frame1, contours, -1, (0, 255, 0), 2) for c in contours: if cv2.contourArea(c) < 5000: continue # 将矩形绘制代码移出continue的缩进块 x, y, w, h = cv2.boundingRect(c) cv2.rectangle(frame1, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.imshow('My came', frame1) if cv2.waitKey(10) == ord('t'): break # 补充释放资源代码,避免摄像头占用 cam.release() cv2.destroyAllWindows()
内容的提问来源于stack exchange,提问作者Tutai Koley
相关产品推荐
相关产品推荐

