• python opencv3 背景分割 mog2 knn


    git:https://github.com/linyi0604/Computer-Vision

    使用mog2算法进行背景分割

     1 # coding:utf-8
     2 
     3 import cv2
     4 
     5 # 获取摄像头对象
     6 cap = cv2.VideoCapture(0)
     7 # 背景分割器对象
     8 mog = cv2.createBackgroundSubtractorMOG2()
     9 
    10 while True:
    11     ret, frame = cap.read()
    12     fgmask = mog.apply(frame)
    13     cv2.imshow("frame", fgmask)
    14     if cv2.waitKey(5) & 0xff == ord("q"):
    15         break
    16 
    17 cap.release()
    18 cv2.destroyAllWindows()

     

    使用knn进行背景分割 顺便检测运动物体

     1 # coding:utf-8
     2 
     3 import cv2
     4 
     5 # 获取摄像头
     6 camera = cv2.VideoCapture(0)
     7 # 获取背景分割器对象
     8 bs = cv2.createBackgroundSubtractorKNN(detectShadows=True)
     9 
    10 while True:
    11     # 读取帧
    12     ret, frame = camera.read()
    13     # 获取前景
    14     fgmask = bs.apply(frame)
    15     # 对前景二值化
    16     th = cv2.threshold(fgmask.copy(), 244, 255, cv2.THRESH_BINARY)[1]
    17     # 膨胀运算
    18     dilated = cv2.dilate(th, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)), iterations=2)
    19     # 检测轮廓
    20     image, contours, hier = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    21     # 将轮廓画在原图像上
    22     for c in contours:
    23         x, y, w, h = cv2.boundingRect(c)
    24         cv2.rectangle(frame, (x, y), (x+w, y+h), (2555, 255, 0), 2)
    25     # 显示前景
    26     cv2.imshow("fgmask", fgmask)
    27     # 显示二值化
    28     cv2.imshow("thresh", th)
    29     # 显示带有轮廓的原图
    30     cv2.imshow("detection", frame)
    31     if cv2.waitKey(5) & 0xff == ord("q"):
    32         break
    33 
    34 cv2.destroyAllWindows()
    35 camera.release()

     

  • 相关阅读:
    【转】mapgis的一些实用方法和处理技巧
    mac osx 升级到10.10 软件无法打开的问题
    Oracle临时表
    增加表空间大小的三种办法
    哪些情况会记录Oracle Alert日志
    每日PDCA实践
    graphite积累(二)
    Graphite在centeros 6下安装
    linux screen命令
    linux环境中执行Mysql脚本
  • 原文地址:https://www.cnblogs.com/Lin-Yi/p/9450501.html
Copyright © 2020-2023  润新知