Various Python samples updated for Python 2/3 compatibility.

pull/5341/head
Adam Gibson 9 years ago
parent 190d00ea3e
commit b57be28920
  1. 7
      samples/python2/_coverage.py
  2. 14
      samples/python2/_doc.py
  3. 20
      samples/python2/browse.py
  4. 17
      samples/python2/calibrate.py
  5. 12
      samples/python2/camshift.py
  6. 16
      samples/python2/coherence.py
  7. 26
      samples/python2/common.py
  8. 7
      samples/python2/deconvolution.py
  9. 24
      samples/python2/demo.py
  10. 5
      samples/python2/dft.py
  11. 8
      samples/python2/distrans.py
  12. 5
      samples/python2/edge.py
  13. 5
      samples/python2/facedetect.py
  14. 18
      samples/python2/fitline.py
  15. 11
      samples/python2/floodfill.py
  16. 9
      samples/python2/gabor_threads.py
  17. 29
      samples/python2/grabcut.py
  18. 5
      samples/python2/houghcircles.py
  19. 5
      samples/python2/houghlines.py
  20. 7
      samples/python2/inpaint.py
  21. 9
      samples/python2/kalman.py
  22. 10
      samples/python2/lappyr.py
  23. 5
      samples/python2/lk_homography.py
  24. 5
      samples/python2/lk_track.py
  25. 6
      samples/python2/logpolar.py
  26. 28
      samples/python2/morphology.py
  27. 10
      samples/python2/mosse.py
  28. 8
      samples/python2/mouse_and_match.py
  29. 11
      samples/python2/opencv_version.py
  30. 13
      samples/python2/peopledetect.py
  31. 7
      samples/python2/squares.py
  32. 12
      samples/python2/turing.py
  33. 9
      samples/python2/video.py
  34. 4
      samples/python2/video_threaded.py

@ -4,6 +4,9 @@
Utility for measuring python opencv API coverage by samples. Utility for measuring python opencv API coverage by samples.
''' '''
# Python 2/3 compatibility
from __future__ import print_function
from glob import glob from glob import glob
import cv2 import cv2
import re import re
@ -13,7 +16,7 @@ if __name__ == '__main__':
found = set() found = set()
for fn in glob('*.py'): for fn in glob('*.py'):
print ' --- ', fn print(' --- ', fn)
code = open(fn).read() code = open(fn).read()
found |= set(re.findall('cv2?\.\w+', code)) found |= set(re.findall('cv2?\.\w+', code))
@ -23,4 +26,4 @@ if __name__ == '__main__':
f.write('\n'.join(sorted(cv2_unused))) f.write('\n'.join(sorted(cv2_unused)))
r = 1.0 * len(cv2_used) / len(cv2_callable) r = 1.0 * len(cv2_used) / len(cv2_callable)
print '\ncv2 api coverage: %d / %d (%.1f%%)' % ( len(cv2_used), len(cv2_callable), r*100 ) print('\ncv2 api coverage: %d / %d (%.1f%%)' % ( len(cv2_used), len(cv2_callable), r*100 ))

@ -5,12 +5,20 @@ Scans current directory for *.py files and reports
ones with missing __doc__ string. ones with missing __doc__ string.
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import sys
PY3 = sys.version_info[0] == 3
from glob import glob from glob import glob
if __name__ == '__main__': if __name__ == '__main__':
print '--- undocumented files:' print('--- undocumented files:')
for fn in glob('*.py'): for fn in glob('*.py'):
loc = {} loc = {}
execfile(fn, loc) if PY3:
exec(open(fn).read(), loc)
else:
execfile(fn, loc)
if '__doc__' not in loc: if '__doc__' not in loc:
print fn print(fn)

@ -12,6 +12,14 @@ browse.py [image filename]
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import sys
PY3 = sys.version_info[0] == 3
if PY3:
xrange = range
import numpy as np import numpy as np
import cv2 import cv2
@ -19,21 +27,21 @@ import cv2
import sys import sys
if __name__ == '__main__': if __name__ == '__main__':
print 'This sample shows how to implement a simple hi resolution image navigation.' print('This sample shows how to implement a simple hi resolution image navigation.')
print 'USAGE: browse.py [image filename]' print('USAGE: browse.py [image filename]')
print print()
if len(sys.argv) > 1: if len(sys.argv) > 1:
fn = sys.argv[1] fn = sys.argv[1]
print 'loading %s ...' % fn print('loading %s ...' % fn)
img = cv2.imread(fn) img = cv2.imread(fn)
if img is None: if img is None:
print 'Failed to load fn:', fn print('Failed to load fn:', fn)
sys.exit(1) sys.exit(1)
else: else:
sz = 4096 sz = 4096
print 'generating %dx%d procedural image ...' % (sz, sz) print('generating %dx%d procedural image ...' % (sz, sz))
img = np.zeros((sz, sz), np.uint8) img = np.zeros((sz, sz), np.uint8)
track = np.cumsum(np.random.rand(500000, 2)-0.5, axis=0) track = np.cumsum(np.random.rand(500000, 2)-0.5, axis=0)
track = np.int32(track*10 + (sz/2, sz/2)) track = np.int32(track*10 + (sz/2, sz/2))

@ -1,5 +1,8 @@
#!/usr/bin/env python #!/usr/bin/env python
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np import numpy as np
import cv2 import cv2
@ -41,10 +44,10 @@ if __name__ == '__main__':
img_points = [] img_points = []
h, w = 0, 0 h, w = 0, 0
for fn in img_names: for fn in img_names:
print 'processing %s...' % fn, print('processing %s...' % fn,)
img = cv2.imread(fn, 0) img = cv2.imread(fn, 0)
if img is None: if img is None:
print "Failed to load", fn print("Failed to load", fn)
continue continue
h, w = img.shape[:2] h, w = img.shape[:2]
@ -58,15 +61,15 @@ if __name__ == '__main__':
path, name, ext = splitfn(fn) path, name, ext = splitfn(fn)
cv2.imwrite('%s/%s_chess.bmp' % (debug_dir, name), vis) cv2.imwrite('%s/%s_chess.bmp' % (debug_dir, name), vis)
if not found: if not found:
print 'chessboard not found' print('chessboard not found')
continue continue
img_points.append(corners.reshape(-1, 2)) img_points.append(corners.reshape(-1, 2))
obj_points.append(pattern_points) obj_points.append(pattern_points)
print 'ok' print('ok')
rms, camera_matrix, dist_coefs, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, (w, h), None, None) rms, camera_matrix, dist_coefs, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, (w, h), None, None)
print "RMS:", rms print("RMS:", rms)
print "camera matrix:\n", camera_matrix print("camera matrix:\n", camera_matrix)
print "distortion coefficients: ", dist_coefs.ravel() print("distortion coefficients: ", dist_coefs.ravel())
cv2.destroyAllWindows() cv2.destroyAllWindows()

@ -22,6 +22,14 @@ Keys:
b - toggle back-projected probability visualization b - toggle back-projected probability visualization
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import sys
PY3 = sys.version_info[0] == 3
if PY3:
xrange = range
import numpy as np import numpy as np
import cv2 import cv2
@ -103,7 +111,7 @@ class App(object):
try: try:
cv2.ellipse(vis, track_box, (0, 0, 255), 2) cv2.ellipse(vis, track_box, (0, 0, 255), 2)
except: except:
print track_box print(track_box)
cv2.imshow('camshift', vis) cv2.imshow('camshift', vis)
@ -121,5 +129,5 @@ if __name__ == '__main__':
video_src = sys.argv[1] video_src = sys.argv[1]
except: except:
video_src = 0 video_src = 0
print __doc__ print(__doc__)
App(video_src).run() App(video_src).run()

@ -9,6 +9,14 @@ inspired by
http://www.mia.uni-saarland.de/Publications/weickert-dagm03.pdf http://www.mia.uni-saarland.de/Publications/weickert-dagm03.pdf
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import sys
PY3 = sys.version_info[0] == 3
if PY3:
xrange = range
import numpy as np import numpy as np
import cv2 import cv2
@ -16,7 +24,7 @@ def coherence_filter(img, sigma = 11, str_sigma = 11, blend = 0.5, iter_n = 4):
h, w = img.shape[:2] h, w = img.shape[:2]
for i in xrange(iter_n): for i in xrange(iter_n):
print i, print(i)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
eigen = cv2.cornerEigenValsAndVecs(gray, str_sigma, 3) eigen = cv2.cornerEigenValsAndVecs(gray, str_sigma, 3)
@ -34,7 +42,7 @@ def coherence_filter(img, sigma = 11, str_sigma = 11, blend = 0.5, iter_n = 4):
img1 = ero img1 = ero
img1[m] = dil[m] img1[m] = dil[m]
img = np.uint8(img*(1.0 - blend) + img1*blend) img = np.uint8(img*(1.0 - blend) + img1*blend)
print 'done' print('done')
return img return img
@ -54,7 +62,7 @@ if __name__ == '__main__':
sigma = cv2.getTrackbarPos('sigma', 'control')*2+1 sigma = cv2.getTrackbarPos('sigma', 'control')*2+1
str_sigma = cv2.getTrackbarPos('str_sigma', 'control')*2+1 str_sigma = cv2.getTrackbarPos('str_sigma', 'control')*2+1
blend = cv2.getTrackbarPos('blend', 'control') / 10.0 blend = cv2.getTrackbarPos('blend', 'control') / 10.0
print 'sigma: %d str_sigma: %d blend_coef: %f' % (sigma, str_sigma, blend) print('sigma: %d str_sigma: %d blend_coef: %f' % (sigma, str_sigma, blend))
dst = coherence_filter(src, sigma=sigma, str_sigma = str_sigma, blend = blend) dst = coherence_filter(src, sigma=sigma, str_sigma = str_sigma, blend = blend)
cv2.imshow('dst', dst) cv2.imshow('dst', dst)
@ -64,7 +72,7 @@ if __name__ == '__main__':
cv2.createTrackbar('str_sigma', 'control', 9, 15, nothing) cv2.createTrackbar('str_sigma', 'control', 9, 15, nothing)
print 'Press SPACE to update the image\n' print('Press SPACE to update the image\n')
cv2.imshow('src', src) cv2.imshow('src', src)
update() update()

@ -4,6 +4,14 @@
This module contains some common routines used by other samples. This module contains some common routines used by other samples.
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import sys
PY3 = sys.version_info[0] == 3
if PY3:
from functools import reduce
import numpy as np import numpy as np
import cv2 import cv2
@ -70,7 +78,8 @@ def mtx2rvec(R):
axis = np.cross(vt[0], vt[1]) axis = np.cross(vt[0], vt[1])
return axis * np.arctan2(s, c) return axis * np.arctan2(s, c)
def draw_str(dst, (x, y), s): def draw_str(dst, target, s):
x, y = target
cv2.putText(dst, s, (x+1, y+1), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 0), thickness = 2, lineType=cv2.LINE_AA) cv2.putText(dst, s, (x+1, y+1), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 0), thickness = 2, lineType=cv2.LINE_AA)
cv2.putText(dst, s, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.0, (255, 255, 255), lineType=cv2.LINE_AA) cv2.putText(dst, s, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.0, (255, 255, 255), lineType=cv2.LINE_AA)
@ -135,12 +144,12 @@ def clock():
@contextmanager @contextmanager
def Timer(msg): def Timer(msg):
print msg, '...', print(msg, '...',)
start = clock() start = clock()
try: try:
yield yield
finally: finally:
print "%.2f ms" % ((clock()-start)*1000) print("%.2f ms" % ((clock()-start)*1000))
class StatValue: class StatValue:
def __init__(self, smooth_coef = 0.5): def __init__(self, smooth_coef = 0.5):
@ -192,7 +201,11 @@ class RectSelector:
def grouper(n, iterable, fillvalue=None): def grouper(n, iterable, fillvalue=None):
'''grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx''' '''grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx'''
args = [iter(iterable)] * n args = [iter(iterable)] * n
return it.izip_longest(fillvalue=fillvalue, *args) if PY3:
output = it.zip_longest(fillvalue=fillvalue, *args)
else:
output = it.izip_longest(fillvalue=fillvalue, *args)
return output
def mosaic(w, imgs): def mosaic(w, imgs):
'''Make a grid from images. '''Make a grid from images.
@ -201,7 +214,10 @@ def mosaic(w, imgs):
imgs -- images (must have same size and format) imgs -- images (must have same size and format)
''' '''
imgs = iter(imgs) imgs = iter(imgs)
img0 = imgs.next() if PY3:
img0 = next(imgs)
else:
img0 = imgs.next()
pad = np.zeros_like(img0) pad = np.zeros_like(img0)
imgs = it.chain([img0], imgs) imgs = it.chain([img0], imgs)
rows = grouper(w, imgs, pad) rows = grouper(w, imgs, pad)

@ -30,6 +30,9 @@ Examples:
[1] http://en.wikipedia.org/wiki/Wiener_deconvolution [1] http://en.wikipedia.org/wiki/Wiener_deconvolution
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np import numpy as np
import cv2 import cv2
@ -63,7 +66,7 @@ def defocus_kernel(d, sz=65):
if __name__ == '__main__': if __name__ == '__main__':
print __doc__ print(__doc__)
import sys, getopt import sys, getopt
opts, args = getopt.getopt(sys.argv[1:], '', ['circle', 'angle=', 'd=', 'snr=']) opts, args = getopt.getopt(sys.argv[1:], '', ['circle', 'angle=', 'd=', 'snr='])
opts = dict(opts) opts = dict(opts)
@ -76,7 +79,7 @@ if __name__ == '__main__':
img = cv2.imread(fn, 0) img = cv2.imread(fn, 0)
if img is None: if img is None:
print 'Failed to load fn1:', fn1 print('Failed to load fn1:', fn1)
sys.exit(1) sys.exit(1)
img = np.float32(img)/255.0 img = np.float32(img)/255.0

@ -4,16 +4,25 @@
Sample-launcher application. Sample-launcher application.
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import sys
PY3 = sys.version_info[0] == 3
# local modules # local modules
from common import splitfn from common import splitfn
# built-in modules # built-in modules
import sys
import webbrowser import webbrowser
import Tkinter as tk
from glob import glob from glob import glob
from subprocess import Popen from subprocess import Popen
from ScrolledText import ScrolledText
if PY3:
import tkinter as tk
from tkinter.scrolledtext import ScrolledText
else:
import Tkinter as tk
from ScrolledText import ScrolledText
#from IPython.Shell import IPShellEmbed #from IPython.Shell import IPShellEmbed
@ -97,14 +106,17 @@ class App:
run_btn.pack() run_btn.pack()
def on_link(self, url): def on_link(self, url):
print url print(url)
webbrowser.open(url) webbrowser.open(url)
def on_demo_select(self, evt): def on_demo_select(self, evt):
name = self.demos_lb.get( self.demos_lb.curselection()[0] ) name = self.demos_lb.get( self.demos_lb.curselection()[0] )
fn = self.samples[name] fn = self.samples[name]
loc = {} loc = {}
execfile(fn, loc) if PY3:
exec(open(fn).read(), loc)
else:
execfile(fn, loc)
descr = loc.get('__doc__', 'no-description') descr = loc.get('__doc__', 'no-description')
self.linker.reset() self.linker.reset()
@ -152,7 +164,7 @@ class App:
def on_run(self, *args): def on_run(self, *args):
cmd = self.cmd_entry.get() cmd = self.cmd_entry.get()
print 'running:', cmd print('running:', cmd)
Popen(sys.executable + ' ' + cmd, shell=True) Popen(sys.executable + ' ' + cmd, shell=True)
def run(self): def run(self):

@ -1,5 +1,8 @@
#!/usr/bin/env python #!/usr/bin/env python
# Python 2/3 compatibility
from __future__ import print_function
import cv2 import cv2
import numpy as np import numpy as np
import sys import sys
@ -57,7 +60,7 @@ if __name__ == "__main__":
im = cv2.imread(sys.argv[1]) im = cv2.imread(sys.argv[1])
else : else :
im = cv2.imread('../data/baboon.jpg') im = cv2.imread('../data/baboon.jpg')
print "usage : python dft.py <image_file>" print("usage : python dft.py <image_file>")
# convert to grayscale # convert to grayscale
im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

@ -11,6 +11,8 @@ Keys:
v - toggle voronoi mode v - toggle voronoi mode
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np import numpy as np
import cv2 import cv2
@ -23,11 +25,11 @@ if __name__ == '__main__':
fn = sys.argv[1] fn = sys.argv[1]
except: except:
fn = '../data/fruits.jpg' fn = '../data/fruits.jpg'
print __doc__ print(__doc__)
img = cv2.imread(fn, 0) img = cv2.imread(fn, 0)
if img is None: if img is None:
print 'Failed to load fn:', fn print('Failed to load fn:', fn)
sys.exit(1) sys.exit(1)
cm = make_cmap('jet') cm = make_cmap('jet')
@ -62,7 +64,7 @@ if __name__ == '__main__':
break break
if ch == ord('v'): if ch == ord('v'):
voronoi = not voronoi voronoi = not voronoi
print 'showing', ['distance', 'voronoi'][voronoi] print('showing', ['distance', 'voronoi'][voronoi])
update() update()
if need_update: if need_update:
update() update()

@ -10,6 +10,9 @@ Usage:
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import cv2 import cv2
# relative module # relative module
@ -20,7 +23,7 @@ import sys
if __name__ == '__main__': if __name__ == '__main__':
print __doc__ print(__doc__)
try: try:
fn = sys.argv[1] fn = sys.argv[1]

@ -1,5 +1,8 @@
#!/usr/bin/env python #!/usr/bin/env python
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np import numpy as np
import cv2 import cv2
@ -24,7 +27,7 @@ def draw_rects(img, rects, color):
if __name__ == '__main__': if __name__ == '__main__':
import sys, getopt import sys, getopt
print help_message print(help_message)
args, video_src = getopt.getopt(sys.argv[1:], '', ['cascade=', 'nested-cascade=']) args, video_src = getopt.getopt(sys.argv[1:], '', ['cascade=', 'nested-cascade='])
try: try:

@ -22,6 +22,11 @@ f - change distance function
ESC - exit ESC - exit
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import sys
PY3 = sys.version_info[0] == 3
import numpy as np import numpy as np
import cv2 import cv2
@ -43,7 +48,11 @@ def sample_line(p1, p2, n, noise=0.0):
return p1 + (p2-p1)*t + np.random.normal(size=(n, 2))*noise return p1 + (p2-p1)*t + np.random.normal(size=(n, 2))*noise
dist_func_names = it.cycle('DIST_L2 DIST_L1 DIST_L12 DIST_FAIR DIST_WELSCH DIST_HUBER'.split()) dist_func_names = it.cycle('DIST_L2 DIST_L1 DIST_L12 DIST_FAIR DIST_WELSCH DIST_HUBER'.split())
cur_func_name = dist_func_names.next()
if PY3:
cur_func_name = next(dist_func_names)
else:
cur_func_name = dist_func_names.next()
def update(_=None): def update(_=None):
noise = cv2.getTrackbarPos('noise', 'fit line') noise = cv2.getTrackbarPos('noise', 'fit line')
@ -71,7 +80,7 @@ def update(_=None):
cv2.imshow('fit line', img) cv2.imshow('fit line', img)
if __name__ == '__main__': if __name__ == '__main__':
print __doc__ print(__doc__)
cv2.namedWindow('fit line') cv2.namedWindow('fit line')
cv2.createTrackbar('noise', 'fit line', 3, 50, update) cv2.createTrackbar('noise', 'fit line', 3, 50, update)
@ -81,6 +90,9 @@ if __name__ == '__main__':
update() update()
ch = cv2.waitKey(0) & 0xFF ch = cv2.waitKey(0) & 0xFF
if ch == ord('f'): if ch == ord('f'):
cur_func_name = dist_func_names.next() if PY3:
cur_func_name = next(dist_func_names)
else:
cur_func_name = dist_func_names.next()
if ch == 27: if ch == 27:
break break

@ -14,6 +14,9 @@ Keys:
ESC - exit ESC - exit
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np import numpy as np
import cv2 import cv2
@ -23,11 +26,11 @@ if __name__ == '__main__':
fn = sys.argv[1] fn = sys.argv[1]
except: except:
fn = '../data/fruits.jpg' fn = '../data/fruits.jpg'
print __doc__ print(__doc__)
img = cv2.imread(fn, True) img = cv2.imread(fn, True)
if img is None: if img is None:
print 'Failed to load image file:', fn print('Failed to load image file:', fn)
sys.exit(1) sys.exit(1)
h, w = img.shape[:2] h, w = img.shape[:2]
@ -68,10 +71,10 @@ if __name__ == '__main__':
break break
if ch == ord('f'): if ch == ord('f'):
fixed_range = not fixed_range fixed_range = not fixed_range
print 'using %s range' % ('floating', 'fixed')[fixed_range] print('using %s range' % ('floating', 'fixed')[fixed_range])
update() update()
if ch == ord('c'): if ch == ord('c'):
connectivity = 12-connectivity connectivity = 12-connectivity
print 'connectivity =', connectivity print('connectivity =', connectivity)
update() update()
cv2.destroyAllWindows() cv2.destroyAllWindows()

@ -14,6 +14,9 @@ gabor_threads.py [image filename]
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np import numpy as np
import cv2 import cv2
from multiprocessing.pool import ThreadPool from multiprocessing.pool import ThreadPool
@ -48,7 +51,7 @@ if __name__ == '__main__':
import sys import sys
from common import Timer from common import Timer
print __doc__ print(__doc__)
try: try:
img_fn = sys.argv[1] img_fn = sys.argv[1]
except: except:
@ -56,7 +59,7 @@ if __name__ == '__main__':
img = cv2.imread(img_fn) img = cv2.imread(img_fn)
if img is None: if img is None:
print 'Failed to load image file:', img_fn print('Failed to load image file:', img_fn)
sys.exit(1) sys.exit(1)
filters = build_filters() filters = build_filters()
@ -66,7 +69,7 @@ if __name__ == '__main__':
with Timer('running multi-threaded'): with Timer('running multi-threaded'):
res2 = process_threaded(img, filters) res2 = process_threaded(img, filters)
print 'res1 == res2: ', (res1 == res2).all() print('res1 == res2: ', (res1 == res2).all())
cv2.imshow('img', img) cv2.imshow('img', img)
cv2.imshow('result', res2) cv2.imshow('result', res2)
cv2.waitKey() cv2.waitKey()

@ -27,6 +27,9 @@ Key 's' - To save the results
=============================================================================== ===============================================================================
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np import numpy as np
import cv2 import cv2
import sys import sys
@ -72,13 +75,13 @@ def onmouse(event,x,y,flags,param):
cv2.rectangle(img,(ix,iy),(x,y),BLUE,2) cv2.rectangle(img,(ix,iy),(x,y),BLUE,2)
rect = (min(ix,x),min(iy,y),abs(ix-x),abs(iy-y)) rect = (min(ix,x),min(iy,y),abs(ix-x),abs(iy-y))
rect_or_mask = 0 rect_or_mask = 0
print " Now press the key 'n' a few times until no further change \n" print(" Now press the key 'n' a few times until no further change \n")
# draw touchup curves # draw touchup curves
if event == cv2.EVENT_LBUTTONDOWN: if event == cv2.EVENT_LBUTTONDOWN:
if rect_over == False: if rect_over == False:
print "first draw rectangle \n" print("first draw rectangle \n")
else: else:
drawing = True drawing = True
cv2.circle(img,(x,y),thickness,value['color'],-1) cv2.circle(img,(x,y),thickness,value['color'],-1)
@ -98,14 +101,14 @@ def onmouse(event,x,y,flags,param):
if __name__ == '__main__': if __name__ == '__main__':
# print documentation # print documentation
print __doc__ print(__doc__)
# Loading images # Loading images
if len(sys.argv) == 2: if len(sys.argv) == 2:
filename = sys.argv[1] # for drawing purposes filename = sys.argv[1] # for drawing purposes
else: else:
print "No input image given, so loading default image, ../data/lena.jpg \n" print("No input image given, so loading default image, ../data/lena.jpg \n")
print "Correct Usage: python grabcut.py <filename> \n" print("Correct Usage: python grabcut.py <filename> \n")
filename = '../data/lena.jpg' filename = '../data/lena.jpg'
img = cv2.imread(filename) img = cv2.imread(filename)
@ -119,8 +122,8 @@ if __name__ == '__main__':
cv2.setMouseCallback('input',onmouse) cv2.setMouseCallback('input',onmouse)
cv2.moveWindow('input',img.shape[1]+10,90) cv2.moveWindow('input',img.shape[1]+10,90)
print " Instructions: \n" print(" Instructions: \n")
print " Draw a rectangle around the object using right mouse button \n" print(" Draw a rectangle around the object using right mouse button \n")
while(1): while(1):
@ -132,10 +135,10 @@ if __name__ == '__main__':
if k == 27: # esc to exit if k == 27: # esc to exit
break break
elif k == ord('0'): # BG drawing elif k == ord('0'): # BG drawing
print " mark background regions with left mouse button \n" print(" mark background regions with left mouse button \n")
value = DRAW_BG value = DRAW_BG
elif k == ord('1'): # FG drawing elif k == ord('1'): # FG drawing
print " mark foreground regions with left mouse button \n" print(" mark foreground regions with left mouse button \n")
value = DRAW_FG value = DRAW_FG
elif k == ord('2'): # PR_BG drawing elif k == ord('2'): # PR_BG drawing
value = DRAW_PR_BG value = DRAW_PR_BG
@ -145,9 +148,9 @@ if __name__ == '__main__':
bar = np.zeros((img.shape[0],5,3),np.uint8) bar = np.zeros((img.shape[0],5,3),np.uint8)
res = np.hstack((img2,bar,img,bar,output)) res = np.hstack((img2,bar,img,bar,output))
cv2.imwrite('grabcut_output.png',res) cv2.imwrite('grabcut_output.png',res)
print " Result saved as image \n" print(" Result saved as image \n")
elif k == ord('r'): # reset everything elif k == ord('r'): # reset everything
print "resetting \n" print("resetting \n")
rect = (0,0,1,1) rect = (0,0,1,1)
drawing = False drawing = False
rectangle = False rectangle = False
@ -158,8 +161,8 @@ if __name__ == '__main__':
mask = np.zeros(img.shape[:2],dtype = np.uint8) # mask initialized to PR_BG mask = np.zeros(img.shape[:2],dtype = np.uint8) # mask initialized to PR_BG
output = np.zeros(img.shape,np.uint8) # output image to be shown output = np.zeros(img.shape,np.uint8) # output image to be shown
elif k == ord('n'): # segment the image elif k == ord('n'): # segment the image
print """ For finer touchups, mark foreground and background after pressing keys 0-3 print(""" For finer touchups, mark foreground and background after pressing keys 0-3
and again press 'n' \n""" and again press 'n' \n""")
if (rect_or_mask == 0): # grabcut with rect if (rect_or_mask == 0): # grabcut with rect
bgdmodel = np.zeros((1,65),np.float64) bgdmodel = np.zeros((1,65),np.float64)
fgdmodel = np.zeros((1,65),np.float64) fgdmodel = np.zeros((1,65),np.float64)

@ -6,13 +6,16 @@ Usage: ./houghcircles.py [<image_name>]
image argument defaults to ../data/board.jpg image argument defaults to ../data/board.jpg
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import cv2 import cv2
import numpy as np import numpy as np
import sys import sys
if __name__ == '__main__': if __name__ == '__main__':
print __doc__ print(__doc__)
try: try:
fn = sys.argv[1] fn = sys.argv[1]
except: except:

@ -4,6 +4,9 @@ This example illustrates how to use Hough Transform to find lines
Usage: ./houghlines.py [<image_name>] Usage: ./houghlines.py [<image_name>]
image argument defaults to ../data/pic1.png image argument defaults to ../data/pic1.png
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import cv2 import cv2
import numpy as np import numpy as np
import sys import sys
@ -15,7 +18,7 @@ if __name__ == '__main__':
fn = sys.argv[1] fn = sys.argv[1]
except: except:
fn = "../data/pic1.png" fn = "../data/pic1.png"
print __doc__ print(__doc__)
src = cv2.imread(fn) src = cv2.imread(fn)
dst = cv2.Canny(src, 50, 200) dst = cv2.Canny(src, 50, 200)
cdst = cv2.cvtColor(dst, cv2.COLOR_GRAY2BGR) cdst = cv2.cvtColor(dst, cv2.COLOR_GRAY2BGR)

@ -15,6 +15,9 @@ Keys:
ESC - exit ESC - exit
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np import numpy as np
import cv2 import cv2
from common import Sketcher from common import Sketcher
@ -26,11 +29,11 @@ if __name__ == '__main__':
except: except:
fn = '../data/fruits.jpg' fn = '../data/fruits.jpg'
print __doc__ print(__doc__)
img = cv2.imread(fn) img = cv2.imread(fn)
if img is None: if img is None:
print 'Failed to load image file:', fn print('Failed to load image file:', fn)
sys.exit(1) sys.exit(1)
img_mark = img.copy() img_mark = img.copy()

@ -11,6 +11,13 @@
Pressing any key (except ESC) will reset the tracking with a different speed. Pressing any key (except ESC) will reset the tracking with a different speed.
Pressing ESC will stop the program. Pressing ESC will stop the program.
""" """
# Python 2/3 compatibility
import sys
PY3 = sys.version_info[0] == 3
if PY3:
long = int
import cv2 import cv2
from math import cos, sin from math import cos, sin
import numpy as np import numpy as np
@ -21,7 +28,7 @@ if __name__ == "__main__":
img_width = 500 img_width = 500
kalman = cv2.KalmanFilter(2, 1, 0) kalman = cv2.KalmanFilter(2, 1, 0)
code = -1L code = long(-1)
cv2.namedWindow("Kalman") cv2.namedWindow("Kalman")

@ -12,6 +12,14 @@ References:
Alexander Mordvintsev 6/10/12 Alexander Mordvintsev 6/10/12
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import sys
PY3 = sys.version_info[0] == 3
if PY3:
xrange = range
import numpy as np import numpy as np
import cv2 import cv2
import video import video
@ -38,7 +46,7 @@ def merge_lappyr(levels):
if __name__ == '__main__': if __name__ == '__main__':
import sys import sys
print __doc__ print(__doc__)
try: try:
fn = sys.argv[1] fn = sys.argv[1]

@ -20,6 +20,9 @@ SPACE - start tracking
r - toggle RANSAC r - toggle RANSAC
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np import numpy as np
import cv2 import cv2
import video import video
@ -108,7 +111,7 @@ def main():
except: except:
video_src = 0 video_src = 0
print __doc__ print(__doc__)
App(video_src).run() App(video_src).run()
cv2.destroyAllWindows() cv2.destroyAllWindows()

@ -18,6 +18,9 @@ Keys
ESC - exit ESC - exit
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np import numpy as np
import cv2 import cv2
import video import video
@ -93,7 +96,7 @@ def main():
except: except:
video_src = 0 video_src = 0
print __doc__ print(__doc__)
App(video_src).run() App(video_src).run()
cv2.destroyAllWindows() cv2.destroyAllWindows()

@ -1,4 +1,8 @@
#!/usr/bin/env python #!/usr/bin/env python
# Python 2/3 compatibility
from __future__ import print_function
import cv2 import cv2
if __name__ == '__main__': if __name__ == '__main__':
@ -10,7 +14,7 @@ if __name__ == '__main__':
img = cv2.imread(fn) img = cv2.imread(fn)
if img is None: if img is None:
print 'Failed to load image file:', fn print('Failed to load image file:', fn)
sys.exit(1) sys.exit(1)
img2 = cv2.logPolar(img, (img.shape[0]/2, img.shape[1]/2), 40, cv2.WARP_FILL_OUTLIERS) img2 = cv2.logPolar(img, (img.shape[0]/2, img.shape[1]/2), 40, cv2.WARP_FILL_OUTLIERS)

@ -12,12 +12,17 @@ Keys:
ESC - exit ESC - exit
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import sys
PY3 = sys.version_info[0] == 3
import numpy as np import numpy as np
import cv2 import cv2
if __name__ == '__main__': if __name__ == '__main__':
print __doc__ print(__doc__)
import sys import sys
from itertools import cycle from itertools import cycle
@ -31,15 +36,20 @@ if __name__ == '__main__':
img = cv2.imread(fn) img = cv2.imread(fn)
if img is None: if img is None:
print 'Failed to load image file:', fn print('Failed to load image file:', fn)
sys.exit(1) sys.exit(1)
cv2.imshow('original', img) cv2.imshow('original', img)
modes = cycle(['erode/dilate', 'open/close', 'blackhat/tophat', 'gradient']) modes = cycle(['erode/dilate', 'open/close', 'blackhat/tophat', 'gradient'])
str_modes = cycle(['ellipse', 'rect', 'cross']) str_modes = cycle(['ellipse', 'rect', 'cross'])
cur_mode = modes.next()
cur_str_mode = str_modes.next() if PY3:
cur_mode = next(modes)
cur_str_mode = next(str_modes)
else:
cur_mode = modes.next()
cur_str_mode = str_modes.next()
def update(dummy=None): def update(dummy=None):
sz = cv2.getTrackbarPos('op/size', 'morphology') sz = cv2.getTrackbarPos('op/size', 'morphology')
@ -73,8 +83,14 @@ if __name__ == '__main__':
if ch == 27: if ch == 27:
break break
if ch == ord('1'): if ch == ord('1'):
cur_mode = modes.next() if PY3:
cur_mode = next(modes)
else:
cur_mode = modes.next()
if ch == ord('2'): if ch == ord('2'):
cur_str_mode = str_modes.next() if PY3:
cur_str_mode = next(str_modes)
else:
cur_str_mode = str_modes.next()
update() update()
cv2.destroyAllWindows() cv2.destroyAllWindows()

@ -21,6 +21,14 @@ Keys:
http://www.cs.colostate.edu/~bolme/publications/Bolme2010Tracking.pdf http://www.cs.colostate.edu/~bolme/publications/Bolme2010Tracking.pdf
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import sys
PY3 = sys.version_info[0] == 3
if PY3:
xrange = range
import numpy as np import numpy as np
import cv2 import cv2
from common import draw_str, RectSelector from common import draw_str, RectSelector
@ -178,7 +186,7 @@ class App:
if __name__ == '__main__': if __name__ == '__main__':
print __doc__ print (__doc__)
import sys, getopt import sys, getopt
opts, args = getopt.getopt(sys.argv[1:], '', ['pause']) opts, args = getopt.getopt(sys.argv[1:], '', ['pause'])
opts = dict(opts) opts = dict(opts)

@ -8,6 +8,10 @@ Demonstrate using a mouse to interact with an image:
When they let go of the mouse, it correlates (using matchTemplate) that patch with the image. When they let go of the mouse, it correlates (using matchTemplate) that patch with the image.
ESC to exit ESC to exit
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np import numpy as np
import cv2 import cv2
@ -46,7 +50,7 @@ def onmouse(event, x, y, flags, param):
cv2.rectangle(img, (sel[0], sel[1]), (sel[2], sel[3]), (0,255,255), 1) cv2.rectangle(img, (sel[0], sel[1]), (sel[2], sel[3]), (0,255,255), 1)
cv2.imshow("gray", img) cv2.imshow("gray", img)
else: else:
print "selection is complete" print("selection is complete")
drag_start = None drag_start = None
if __name__ == '__main__': if __name__ == '__main__':
@ -61,7 +65,7 @@ if __name__ == '__main__':
for infile in glob.glob( os.path.join(path, '*.*') ): for infile in glob.glob( os.path.join(path, '*.*') ):
ext = os.path.splitext(infile)[1][1:] #get the filename extenstion ext = os.path.splitext(infile)[1][1:] #get the filename extenstion
if ext == "png" or ext == "jpg" or ext == "bmp" or ext == "tiff" or ext == "pbm": if ext == "png" or ext == "jpg" or ext == "bmp" or ext == "tiff" or ext == "pbm":
print infile print(infile)
img=cv2.imread(infile,1) img=cv2.imread(infile,1)
if img == None: if img == None:

@ -1,5 +1,8 @@
#!/usr/bin/env python #!/usr/bin/env python
# Python 2/3 compatibility
from __future__ import print_function
import cv2 import cv2
if __name__ == '__main__': if __name__ == '__main__':
@ -10,9 +13,9 @@ if __name__ == '__main__':
param = "" param = ""
if ("--build" == param): if ("--build" == param):
print cv2.getBuildInformation() print(cv2.getBuildInformation())
elif ("--help" == param): elif ("--help" == param):
print "\t--build\n\t\tprint complete build info" print("\t--build\n\t\tprint complete build info")
print "\t--help\n\t\tprint this help" print("\t--help\n\t\tprint this help")
else: else:
print "Welcome to OpenCV" print("Welcome to OpenCV")

@ -1,5 +1,8 @@
#!/usr/bin/env python #!/usr/bin/env python
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np import numpy as np
import cv2 import cv2
@ -27,20 +30,20 @@ if __name__ == '__main__':
from glob import glob from glob import glob
import itertools as it import itertools as it
print help_message print(help_message)
hog = cv2.HOGDescriptor() hog = cv2.HOGDescriptor()
hog.setSVMDetector( cv2.HOGDescriptor_getDefaultPeopleDetector() ) hog.setSVMDetector( cv2.HOGDescriptor_getDefaultPeopleDetector() )
for fn in it.chain(*map(glob, sys.argv[1:])): for fn in it.chain(*map(glob, sys.argv[1:])):
print fn, ' - ', print(fn, ' - ',)
try: try:
img = cv2.imread(fn) img = cv2.imread(fn)
if img is None: if img is None:
print 'Failed to load image file:', fn print('Failed to load image file:', fn)
continue continue
except: except:
print 'loading error' print('loading error')
continue continue
found, w = hog.detectMultiScale(img, winStride=(8,8), padding=(32,32), scale=1.05) found, w = hog.detectMultiScale(img, winStride=(8,8), padding=(32,32), scale=1.05)
@ -53,7 +56,7 @@ if __name__ == '__main__':
found_filtered.append(r) found_filtered.append(r)
draw_detections(img, found) draw_detections(img, found)
draw_detections(img, found_filtered, 3) draw_detections(img, found_filtered, 3)
print '%d (%d) found' % (len(found_filtered), len(found)) print('%d (%d) found' % (len(found_filtered), len(found)))
cv2.imshow('img', img) cv2.imshow('img', img)
ch = 0xFF & cv2.waitKey() ch = 0xFF & cv2.waitKey()
if ch == 27: if ch == 27:

@ -6,6 +6,13 @@ Simple "Square Detector" program.
Loads several images sequentially and tries to find squares in each image. Loads several images sequentially and tries to find squares in each image.
''' '''
# Python 2/3 compatibility
import sys
PY3 = sys.version_info[0] == 3
if PY3:
xrange = range
import numpy as np import numpy as np
import cv2 import cv2

@ -7,6 +7,14 @@ Multiscale Turing Patterns generator
Inspired by http://www.jonathanmccabe.com/Cyclic_Symmetric_Multi-Scale_Turing_Patterns.pdf Inspired by http://www.jonathanmccabe.com/Cyclic_Symmetric_Multi-Scale_Turing_Patterns.pdf
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import sys
PY3 = sys.version_info[0] == 3
if PY3:
xrange = range
import numpy as np import numpy as np
import cv2 import cv2
from common import draw_str from common import draw_str
@ -20,7 +28,7 @@ Press ESC to stop.
''' '''
if __name__ == '__main__': if __name__ == '__main__':
print help_message print(help_message)
w, h = 512, 512 w, h = 512, 512
@ -30,7 +38,7 @@ if __name__ == '__main__':
if '-o' in args: if '-o' in args:
fn = args['-o'] fn = args['-o']
out = cv2.VideoWriter(args['-o'], cv2.VideoWriter_fourcc(*'DIB '), 30.0, (w, h), False) out = cv2.VideoWriter(args['-o'], cv2.VideoWriter_fourcc(*'DIB '), 30.0, (w, h), False)
print 'writing %s ...' % fn print('writing %s ...' % fn)
a = np.zeros((h, w), np.float32) a = np.zeros((h, w), np.float32)
cv2.randu(a, np.array([0]), np.array([1])) cv2.randu(a, np.array([0]), np.array([1]))

@ -29,6 +29,9 @@ Keys:
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np import numpy as np
from numpy import pi, sin, cos from numpy import pi, sin, cos
@ -162,7 +165,7 @@ def create_capture(source = 0, fallback = presets['chess']):
cap.set(cv2.CAP_PROP_FRAME_WIDTH, w) cap.set(cv2.CAP_PROP_FRAME_WIDTH, w)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, h) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, h)
if cap is None or not cap.isOpened(): if cap is None or not cap.isOpened():
print 'Warning: unable to open video source: ', source print('Warning: unable to open video source: ', source)
if fallback is not None: if fallback is not None:
return create_capture(fallback, None) return create_capture(fallback, None)
return cap return cap
@ -171,7 +174,7 @@ if __name__ == '__main__':
import sys import sys
import getopt import getopt
print __doc__ print(__doc__)
args, sources = getopt.getopt(sys.argv[1:], '', 'shotdir=') args, sources = getopt.getopt(sys.argv[1:], '', 'shotdir=')
args = dict(args) args = dict(args)
@ -194,6 +197,6 @@ if __name__ == '__main__':
for i, img in enumerate(imgs): for i, img in enumerate(imgs):
fn = '%s/shot_%d_%03d.bmp' % (shotdir, i, shot_idx) fn = '%s/shot_%d_%03d.bmp' % (shotdir, i, shot_idx)
cv2.imwrite(fn, img) cv2.imwrite(fn, img)
print fn, 'saved' print(fn, 'saved')
shot_idx += 1 shot_idx += 1
cv2.destroyAllWindows() cv2.destroyAllWindows()

@ -15,6 +15,8 @@ Keyboard shortcuts:
space - switch between multi and single threaded processing space - switch between multi and single threaded processing
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np import numpy as np
import cv2 import cv2
@ -37,7 +39,7 @@ class DummyTask:
if __name__ == '__main__': if __name__ == '__main__':
import sys import sys
print __doc__ print(__doc__)
try: try:
fn = sys.argv[1] fn = sys.argv[1]

Loading…
Cancel
Save