zoukankan      html  css  js  c++  java
  • 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()

     

  • 相关阅读:
    [Spring开发]获取上下文对象
    [Dubbo开发]Dubbo日志插件实现(打包)
    [Dubbo开发]Dubbo日志插件实现(未打包)
    [Java开发]打印当前路径到控制台
    [Dubbo开发]Dubbo拦截器(Filter)初探
    [Dubbo开发]配置简单的生产者和消费者
    [Dubbo开发]Zookeeper配置
    [Dubbo开发]Maven安装与配置
    EL表达式的特性
    oracle中rownum的使用
  • 原文地址:https://www.cnblogs.com/Lin-Yi/p/9450501.html
Copyright © 2011-2022 走看看