BackgroundSubtractorCNT: python/demo.py
BackgroundSubtractorCNT  1.1.3
python/demo.py

This is an example of python usage.

1 #!/usr/bin/env python
2 
3 import sys
4 import getopt
5 import cv2
6 import bgsubcnt
7 import numpy as np
8 
9  # A temporary solution to OpenCV 3.1.0 bug
10 cv2.ocl.setUseOpenCL(False)
11 
12 def usage():
13  print ("""BackgroundSubtractorCNT demo/benchmark/comparison
14 Usage: demo.py [params]
15 
16  -h, --help
17  print this message
18  --bg
19  calculate also the background
20  --file
21  use file (default is system camera)
22  --nogui
23  run without GUI to measure times
24  --type (default:CNT)
25  bg subtraction type from - CNT/MOG2/KNN
26 """)
27 
28 def getBGSubtractor(typeStr):
29  if typeStr == "KNN":
30  return cv2.createBackgroundSubtractorKNN()
31  if typeStr == "MOG2":
32  return cv2.createBackgroundSubtractorMOG2()
33  if typeStr == "CNT":
34  return bgsubcnt.createBackgroundSubtractor()
35  print ("Unknown createBackgroundSubtractor type")
36  sys.exit(1)
37 
38 def main(argv):
39  filePath = None
40  hasGui = True
41  bgImage = False
42  typeStr = "CNT"
43 
44  try:
45  opts, args = getopt.getopt(argv, "h", ["help", "bg", "file=", "nogui", "type="])
46  except getopt.GetoptError:
47  usage()
48  sys.exit(1)
49 
50  for opt, arg in opts:
51  if opt in ("-h", "--help"):
52  usage()
53  sys.exit()
54  elif opt == "--file":
55  filePath = arg
56  elif opt == "--bg":
57  bgImage = True
58  elif opt == "--nogui":
59  hasGui = False
60  elif opt == "--type":
61  typeStr = arg
62 
63  if (filePath):
64  cap = cv2.VideoCapture(filePath)
65  else:
66  cap = cv2.VideoCapture(0)
67 
68  if cap.isOpened() == False:
69  print ("Could not initialize capturing...");
70  sys.exit(2)
71 
72  fgbg = getBGSubtractor(typeStr)
73 
74  e1 = cv2.getTickCount()
75 
76  ret, frame = cap.read()
77  while(ret):
78  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
79  fg = fgbg.apply(gray)
80  if hasGui:
81  cv2.imshow('Orig',frame)
82  cv2.imshow('FG',fg)
83  if bgImage:
84  bg = fgbg.getBackgroundImage()
85  cv2.imshow('BG',bg)
86  k = cv2.waitKey(1)
87  if k == 27:
88  break
89  ret, frame = cap.read()
90 
91  e2 = cv2.getTickCount()
92 
93  t = (e2 - e1)/cv2.getTickFrequency()
94  print ("Execution took '%(val).3f' seconds." % {'val': t});
95 
96  cap.release()
97  if hasGui:
98  cv2.destroyAllWindows()
99 
100 if __name__ == "__main__":
101  main(sys.argv[1:])