diff --git a/samples/python2/_coverage.py b/samples/python2/_coverage.py index 4b23370b50..5ec3e18a92 100755 --- a/samples/python2/_coverage.py +++ b/samples/python2/_coverage.py @@ -4,6 +4,9 @@ Utility for measuring python opencv API coverage by samples. ''' +# Python 2/3 compatibility +from __future__ import print_function + from glob import glob import cv2 import re @@ -13,7 +16,7 @@ if __name__ == '__main__': found = set() for fn in glob('*.py'): - print ' --- ', fn + print(' --- ', fn) code = open(fn).read() found |= set(re.findall('cv2?\.\w+', code)) @@ -23,4 +26,4 @@ if __name__ == '__main__': f.write('\n'.join(sorted(cv2_unused))) 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 )) diff --git a/samples/python2/_doc.py b/samples/python2/_doc.py index fe2b6f32be..eddf26fba3 100755 --- a/samples/python2/_doc.py +++ b/samples/python2/_doc.py @@ -5,12 +5,20 @@ Scans current directory for *.py files and reports 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 if __name__ == '__main__': - print '--- undocumented files:' + print('--- undocumented files:') for fn in glob('*.py'): loc = {} - execfile(fn, loc) + if PY3: + exec(open(fn).read(), loc) + else: + execfile(fn, loc) if '__doc__' not in loc: - print fn + print(fn) diff --git a/samples/python2/browse.py b/samples/python2/browse.py index 462cd17626..317a8db11b 100755 --- a/samples/python2/browse.py +++ b/samples/python2/browse.py @@ -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 cv2 @@ -19,21 +27,21 @@ import cv2 import sys if __name__ == '__main__': - print 'This sample shows how to implement a simple hi resolution image navigation.' - print 'USAGE: browse.py [image filename]' - print + print('This sample shows how to implement a simple hi resolution image navigation.') + print('USAGE: browse.py [image filename]') + print() if len(sys.argv) > 1: fn = sys.argv[1] - print 'loading %s ...' % fn + print('loading %s ...' % fn) img = cv2.imread(fn) if img is None: - print 'Failed to load fn:', fn + print('Failed to load fn:', fn) sys.exit(1) else: 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) track = np.cumsum(np.random.rand(500000, 2)-0.5, axis=0) track = np.int32(track*10 + (sz/2, sz/2)) diff --git a/samples/python2/calibrate.py b/samples/python2/calibrate.py index 9f6f60cb73..24e4aa7d0c 100755 --- a/samples/python2/calibrate.py +++ b/samples/python2/calibrate.py @@ -1,5 +1,8 @@ #!/usr/bin/env python +# Python 2/3 compatibility +from __future__ import print_function + import numpy as np import cv2 @@ -41,10 +44,10 @@ if __name__ == '__main__': img_points = [] h, w = 0, 0 for fn in img_names: - print 'processing %s...' % fn, + print('processing %s...' % fn,) img = cv2.imread(fn, 0) if img is None: - print "Failed to load", fn + print("Failed to load", fn) continue h, w = img.shape[:2] @@ -58,15 +61,15 @@ if __name__ == '__main__': path, name, ext = splitfn(fn) cv2.imwrite('%s/%s_chess.bmp' % (debug_dir, name), vis) if not found: - print 'chessboard not found' + print('chessboard not found') continue img_points.append(corners.reshape(-1, 2)) 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) - print "RMS:", rms - print "camera matrix:\n", camera_matrix - print "distortion coefficients: ", dist_coefs.ravel() + print("RMS:", rms) + print("camera matrix:\n", camera_matrix) + print("distortion coefficients: ", dist_coefs.ravel()) cv2.destroyAllWindows() diff --git a/samples/python2/camshift.py b/samples/python2/camshift.py index 72c790803f..862d5126a4 100755 --- a/samples/python2/camshift.py +++ b/samples/python2/camshift.py @@ -22,6 +22,14 @@ Keys: 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 cv2 @@ -103,7 +111,7 @@ class App(object): try: cv2.ellipse(vis, track_box, (0, 0, 255), 2) except: - print track_box + print(track_box) cv2.imshow('camshift', vis) @@ -121,5 +129,5 @@ if __name__ == '__main__': video_src = sys.argv[1] except: video_src = 0 - print __doc__ + print(__doc__) App(video_src).run() diff --git a/samples/python2/coherence.py b/samples/python2/coherence.py index 46d7414af5..8ca61fcb21 100755 --- a/samples/python2/coherence.py +++ b/samples/python2/coherence.py @@ -9,6 +9,14 @@ inspired by 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 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] for i in xrange(iter_n): - print i, + print(i) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 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[m] = dil[m] img = np.uint8(img*(1.0 - blend) + img1*blend) - print 'done' + print('done') return img @@ -54,7 +62,7 @@ if __name__ == '__main__': sigma = cv2.getTrackbarPos('sigma', 'control')*2+1 str_sigma = cv2.getTrackbarPos('str_sigma', 'control')*2+1 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) cv2.imshow('dst', dst) @@ -64,7 +72,7 @@ if __name__ == '__main__': 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) update() diff --git a/samples/python2/common.py b/samples/python2/common.py index 0ad811ae20..785fb6c8fb 100755 --- a/samples/python2/common.py +++ b/samples/python2/common.py @@ -4,6 +4,14 @@ 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 cv2 @@ -70,7 +78,8 @@ def mtx2rvec(R): axis = np.cross(vt[0], vt[1]) 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, y), cv2.FONT_HERSHEY_PLAIN, 1.0, (255, 255, 255), lineType=cv2.LINE_AA) @@ -135,12 +144,12 @@ def clock(): @contextmanager def Timer(msg): - print msg, '...', + print(msg, '...',) start = clock() try: yield finally: - print "%.2f ms" % ((clock()-start)*1000) + print("%.2f ms" % ((clock()-start)*1000)) class StatValue: def __init__(self, smooth_coef = 0.5): @@ -192,7 +201,11 @@ class RectSelector: def grouper(n, iterable, fillvalue=None): '''grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx''' 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): '''Make a grid from images. @@ -201,7 +214,10 @@ def mosaic(w, imgs): imgs -- images (must have same size and format) ''' imgs = iter(imgs) - img0 = imgs.next() + if PY3: + img0 = next(imgs) + else: + img0 = imgs.next() pad = np.zeros_like(img0) imgs = it.chain([img0], imgs) rows = grouper(w, imgs, pad) diff --git a/samples/python2/deconvolution.py b/samples/python2/deconvolution.py index bbb1567bd4..ce798538b8 100755 --- a/samples/python2/deconvolution.py +++ b/samples/python2/deconvolution.py @@ -30,6 +30,9 @@ Examples: [1] http://en.wikipedia.org/wiki/Wiener_deconvolution ''' +# Python 2/3 compatibility +from __future__ import print_function + import numpy as np import cv2 @@ -63,7 +66,7 @@ def defocus_kernel(d, sz=65): if __name__ == '__main__': - print __doc__ + print(__doc__) import sys, getopt opts, args = getopt.getopt(sys.argv[1:], '', ['circle', 'angle=', 'd=', 'snr=']) opts = dict(opts) @@ -76,7 +79,7 @@ if __name__ == '__main__': img = cv2.imread(fn, 0) if img is None: - print 'Failed to load fn1:', fn1 + print('Failed to load fn1:', fn1) sys.exit(1) img = np.float32(img)/255.0 diff --git a/samples/python2/demo.py b/samples/python2/demo.py index 03d624ddcf..864953a316 100755 --- a/samples/python2/demo.py +++ b/samples/python2/demo.py @@ -4,16 +4,25 @@ Sample-launcher application. ''' +# Python 2/3 compatibility +from __future__ import print_function +import sys +PY3 = sys.version_info[0] == 3 + # local modules from common import splitfn # built-in modules -import sys import webbrowser -import Tkinter as tk from glob import glob 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 @@ -97,14 +106,17 @@ class App: run_btn.pack() def on_link(self, url): - print url + print(url) webbrowser.open(url) def on_demo_select(self, evt): name = self.demos_lb.get( self.demos_lb.curselection()[0] ) fn = self.samples[name] loc = {} - execfile(fn, loc) + if PY3: + exec(open(fn).read(), loc) + else: + execfile(fn, loc) descr = loc.get('__doc__', 'no-description') self.linker.reset() @@ -152,7 +164,7 @@ class App: def on_run(self, *args): cmd = self.cmd_entry.get() - print 'running:', cmd + print('running:', cmd) Popen(sys.executable + ' ' + cmd, shell=True) def run(self): diff --git a/samples/python2/dft.py b/samples/python2/dft.py index a1622b53e2..d617438a88 100755 --- a/samples/python2/dft.py +++ b/samples/python2/dft.py @@ -1,5 +1,8 @@ #!/usr/bin/env python +# Python 2/3 compatibility +from __future__ import print_function + import cv2 import numpy as np import sys @@ -57,7 +60,7 @@ if __name__ == "__main__": im = cv2.imread(sys.argv[1]) else : im = cv2.imread('../data/baboon.jpg') - print "usage : python dft.py " + print("usage : python dft.py ") # convert to grayscale im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) diff --git a/samples/python2/distrans.py b/samples/python2/distrans.py index 819a06c9b4..00e173d523 100755 --- a/samples/python2/distrans.py +++ b/samples/python2/distrans.py @@ -11,6 +11,8 @@ Keys: v - toggle voronoi mode ''' +# Python 2/3 compatibility +from __future__ import print_function import numpy as np import cv2 @@ -23,11 +25,11 @@ if __name__ == '__main__': fn = sys.argv[1] except: fn = '../data/fruits.jpg' - print __doc__ + print(__doc__) img = cv2.imread(fn, 0) if img is None: - print 'Failed to load fn:', fn + print('Failed to load fn:', fn) sys.exit(1) cm = make_cmap('jet') @@ -62,7 +64,7 @@ if __name__ == '__main__': break if ch == ord('v'): voronoi = not voronoi - print 'showing', ['distance', 'voronoi'][voronoi] + print('showing', ['distance', 'voronoi'][voronoi]) update() if need_update: update() diff --git a/samples/python2/edge.py b/samples/python2/edge.py index 413bf8859b..61d8466bc6 100755 --- a/samples/python2/edge.py +++ b/samples/python2/edge.py @@ -10,6 +10,9 @@ Usage: ''' +# Python 2/3 compatibility +from __future__ import print_function + import cv2 # relative module @@ -20,7 +23,7 @@ import sys if __name__ == '__main__': - print __doc__ + print(__doc__) try: fn = sys.argv[1] diff --git a/samples/python2/facedetect.py b/samples/python2/facedetect.py index 8c6b27ab1b..2349087dc8 100755 --- a/samples/python2/facedetect.py +++ b/samples/python2/facedetect.py @@ -1,5 +1,8 @@ #!/usr/bin/env python +# Python 2/3 compatibility +from __future__ import print_function + import numpy as np import cv2 @@ -24,7 +27,7 @@ def draw_rects(img, rects, color): if __name__ == '__main__': import sys, getopt - print help_message + print(help_message) args, video_src = getopt.getopt(sys.argv[1:], '', ['cascade=', 'nested-cascade=']) try: diff --git a/samples/python2/fitline.py b/samples/python2/fitline.py index 1c0d9e7709..95fb2b8d10 100755 --- a/samples/python2/fitline.py +++ b/samples/python2/fitline.py @@ -22,6 +22,11 @@ f - change distance function ESC - exit ''' +# Python 2/3 compatibility +from __future__ import print_function +import sys +PY3 = sys.version_info[0] == 3 + import numpy as np 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 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): noise = cv2.getTrackbarPos('noise', 'fit line') @@ -71,7 +80,7 @@ def update(_=None): cv2.imshow('fit line', img) if __name__ == '__main__': - print __doc__ + print(__doc__) cv2.namedWindow('fit line') cv2.createTrackbar('noise', 'fit line', 3, 50, update) @@ -81,6 +90,9 @@ if __name__ == '__main__': update() ch = cv2.waitKey(0) & 0xFF 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: break diff --git a/samples/python2/floodfill.py b/samples/python2/floodfill.py index 5152f30c18..161c6323f4 100755 --- a/samples/python2/floodfill.py +++ b/samples/python2/floodfill.py @@ -14,6 +14,9 @@ Keys: ESC - exit ''' +# Python 2/3 compatibility +from __future__ import print_function + import numpy as np import cv2 @@ -23,11 +26,11 @@ if __name__ == '__main__': fn = sys.argv[1] except: fn = '../data/fruits.jpg' - print __doc__ + print(__doc__) img = cv2.imread(fn, True) if img is None: - print 'Failed to load image file:', fn + print('Failed to load image file:', fn) sys.exit(1) h, w = img.shape[:2] @@ -68,10 +71,10 @@ if __name__ == '__main__': break if ch == ord('f'): fixed_range = not fixed_range - print 'using %s range' % ('floating', 'fixed')[fixed_range] + print('using %s range' % ('floating', 'fixed')[fixed_range]) update() if ch == ord('c'): connectivity = 12-connectivity - print 'connectivity =', connectivity + print('connectivity =', connectivity) update() cv2.destroyAllWindows() diff --git a/samples/python2/gabor_threads.py b/samples/python2/gabor_threads.py index b004fb7582..f7d62c17e2 100755 --- a/samples/python2/gabor_threads.py +++ b/samples/python2/gabor_threads.py @@ -14,6 +14,9 @@ gabor_threads.py [image filename] ''' +# Python 2/3 compatibility +from __future__ import print_function + import numpy as np import cv2 from multiprocessing.pool import ThreadPool @@ -48,7 +51,7 @@ if __name__ == '__main__': import sys from common import Timer - print __doc__ + print(__doc__) try: img_fn = sys.argv[1] except: @@ -56,7 +59,7 @@ if __name__ == '__main__': img = cv2.imread(img_fn) if img is None: - print 'Failed to load image file:', img_fn + print('Failed to load image file:', img_fn) sys.exit(1) filters = build_filters() @@ -66,7 +69,7 @@ if __name__ == '__main__': with Timer('running multi-threaded'): res2 = process_threaded(img, filters) - print 'res1 == res2: ', (res1 == res2).all() + print('res1 == res2: ', (res1 == res2).all()) cv2.imshow('img', img) cv2.imshow('result', res2) cv2.waitKey() diff --git a/samples/python2/grabcut.py b/samples/python2/grabcut.py index 2c8aa1ef12..19378e6cce 100644 --- a/samples/python2/grabcut.py +++ b/samples/python2/grabcut.py @@ -27,6 +27,9 @@ Key 's' - To save the results =============================================================================== ''' +# Python 2/3 compatibility +from __future__ import print_function + import numpy as np import cv2 import sys @@ -72,13 +75,13 @@ def onmouse(event,x,y,flags,param): cv2.rectangle(img,(ix,iy),(x,y),BLUE,2) rect = (min(ix,x),min(iy,y),abs(ix-x),abs(iy-y)) 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 if event == cv2.EVENT_LBUTTONDOWN: if rect_over == False: - print "first draw rectangle \n" + print("first draw rectangle \n") else: drawing = True cv2.circle(img,(x,y),thickness,value['color'],-1) @@ -98,14 +101,14 @@ def onmouse(event,x,y,flags,param): if __name__ == '__main__': # print documentation - print __doc__ + print(__doc__) # Loading images if len(sys.argv) == 2: filename = sys.argv[1] # for drawing purposes else: - print "No input image given, so loading default image, ../data/lena.jpg \n" - print "Correct Usage: python grabcut.py \n" + print("No input image given, so loading default image, ../data/lena.jpg \n") + print("Correct Usage: python grabcut.py \n") filename = '../data/lena.jpg' img = cv2.imread(filename) @@ -119,8 +122,8 @@ if __name__ == '__main__': cv2.setMouseCallback('input',onmouse) cv2.moveWindow('input',img.shape[1]+10,90) - print " Instructions: \n" - print " Draw a rectangle around the object using right mouse button \n" + print(" Instructions: \n") + print(" Draw a rectangle around the object using right mouse button \n") while(1): @@ -132,10 +135,10 @@ if __name__ == '__main__': if k == 27: # esc to exit break 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 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 elif k == ord('2'): # PR_BG drawing value = DRAW_PR_BG @@ -145,9 +148,9 @@ if __name__ == '__main__': bar = np.zeros((img.shape[0],5,3),np.uint8) res = np.hstack((img2,bar,img,bar,output)) cv2.imwrite('grabcut_output.png',res) - print " Result saved as image \n" + print(" Result saved as image \n") elif k == ord('r'): # reset everything - print "resetting \n" + print("resetting \n") rect = (0,0,1,1) drawing = False rectangle = False @@ -158,8 +161,8 @@ if __name__ == '__main__': 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 elif k == ord('n'): # segment the image - print """ For finer touchups, mark foreground and background after pressing keys 0-3 - and again press 'n' \n""" + print(""" For finer touchups, mark foreground and background after pressing keys 0-3 + and again press 'n' \n""") if (rect_or_mask == 0): # grabcut with rect bgdmodel = np.zeros((1,65),np.float64) fgdmodel = np.zeros((1,65),np.float64) diff --git a/samples/python2/houghcircles.py b/samples/python2/houghcircles.py index 9d68c2ce8f..fe87d8f3e1 100755 --- a/samples/python2/houghcircles.py +++ b/samples/python2/houghcircles.py @@ -6,13 +6,16 @@ Usage: ./houghcircles.py [] image argument defaults to ../data/board.jpg ''' +# Python 2/3 compatibility +from __future__ import print_function + import cv2 import numpy as np import sys if __name__ == '__main__': - print __doc__ + print(__doc__) try: fn = sys.argv[1] except: diff --git a/samples/python2/houghlines.py b/samples/python2/houghlines.py index cd25a56f88..674b26ec70 100755 --- a/samples/python2/houghlines.py +++ b/samples/python2/houghlines.py @@ -4,6 +4,9 @@ This example illustrates how to use Hough Transform to find lines Usage: ./houghlines.py [] image argument defaults to ../data/pic1.png ''' +# Python 2/3 compatibility +from __future__ import print_function + import cv2 import numpy as np import sys @@ -15,7 +18,7 @@ if __name__ == '__main__': fn = sys.argv[1] except: fn = "../data/pic1.png" - print __doc__ + print(__doc__) src = cv2.imread(fn) dst = cv2.Canny(src, 50, 200) cdst = cv2.cvtColor(dst, cv2.COLOR_GRAY2BGR) diff --git a/samples/python2/inpaint.py b/samples/python2/inpaint.py index 4ff1ddb6e5..0ca72f1a25 100755 --- a/samples/python2/inpaint.py +++ b/samples/python2/inpaint.py @@ -15,6 +15,9 @@ Keys: ESC - exit ''' +# Python 2/3 compatibility +from __future__ import print_function + import numpy as np import cv2 from common import Sketcher @@ -26,11 +29,11 @@ if __name__ == '__main__': except: fn = '../data/fruits.jpg' - print __doc__ + print(__doc__) img = cv2.imread(fn) if img is None: - print 'Failed to load image file:', fn + print('Failed to load image file:', fn) sys.exit(1) img_mark = img.copy() diff --git a/samples/python2/kalman.py b/samples/python2/kalman.py index 101f1ea56a..8e3748b4de 100755 --- a/samples/python2/kalman.py +++ b/samples/python2/kalman.py @@ -11,6 +11,13 @@ Pressing any key (except ESC) will reset the tracking with a different speed. Pressing ESC will stop the program. """ +# Python 2/3 compatibility +import sys +PY3 = sys.version_info[0] == 3 + +if PY3: + long = int + import cv2 from math import cos, sin import numpy as np @@ -21,7 +28,7 @@ if __name__ == "__main__": img_width = 500 kalman = cv2.KalmanFilter(2, 1, 0) - code = -1L + code = long(-1) cv2.namedWindow("Kalman") diff --git a/samples/python2/lappyr.py b/samples/python2/lappyr.py index 3cf2679b08..19f5bd9183 100755 --- a/samples/python2/lappyr.py +++ b/samples/python2/lappyr.py @@ -12,6 +12,14 @@ References: 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 cv2 import video @@ -38,7 +46,7 @@ def merge_lappyr(levels): if __name__ == '__main__': import sys - print __doc__ + print(__doc__) try: fn = sys.argv[1] diff --git a/samples/python2/lk_homography.py b/samples/python2/lk_homography.py index ae8b2d49bd..a9e92546c0 100755 --- a/samples/python2/lk_homography.py +++ b/samples/python2/lk_homography.py @@ -20,6 +20,9 @@ SPACE - start tracking r - toggle RANSAC ''' +# Python 2/3 compatibility +from __future__ import print_function + import numpy as np import cv2 import video @@ -108,7 +111,7 @@ def main(): except: video_src = 0 - print __doc__ + print(__doc__) App(video_src).run() cv2.destroyAllWindows() diff --git a/samples/python2/lk_track.py b/samples/python2/lk_track.py index 1ff90ff7e3..8aa94fe642 100755 --- a/samples/python2/lk_track.py +++ b/samples/python2/lk_track.py @@ -18,6 +18,9 @@ Keys ESC - exit ''' +# Python 2/3 compatibility +from __future__ import print_function + import numpy as np import cv2 import video @@ -93,7 +96,7 @@ def main(): except: video_src = 0 - print __doc__ + print(__doc__) App(video_src).run() cv2.destroyAllWindows() diff --git a/samples/python2/logpolar.py b/samples/python2/logpolar.py index 783c7b81a0..60695bfd80 100644 --- a/samples/python2/logpolar.py +++ b/samples/python2/logpolar.py @@ -1,4 +1,8 @@ #!/usr/bin/env python + +# Python 2/3 compatibility +from __future__ import print_function + import cv2 if __name__ == '__main__': @@ -10,7 +14,7 @@ if __name__ == '__main__': img = cv2.imread(fn) if img is None: - print 'Failed to load image file:', fn + print('Failed to load image file:', fn) sys.exit(1) img2 = cv2.logPolar(img, (img.shape[0]/2, img.shape[1]/2), 40, cv2.WARP_FILL_OUTLIERS) diff --git a/samples/python2/morphology.py b/samples/python2/morphology.py index 76fa76c690..be287d33d4 100755 --- a/samples/python2/morphology.py +++ b/samples/python2/morphology.py @@ -12,12 +12,17 @@ Keys: ESC - exit ''' +# Python 2/3 compatibility +from __future__ import print_function +import sys +PY3 = sys.version_info[0] == 3 + import numpy as np import cv2 if __name__ == '__main__': - print __doc__ + print(__doc__) import sys from itertools import cycle @@ -31,15 +36,20 @@ if __name__ == '__main__': img = cv2.imread(fn) if img is None: - print 'Failed to load image file:', fn + print('Failed to load image file:', fn) sys.exit(1) cv2.imshow('original', img) modes = cycle(['erode/dilate', 'open/close', 'blackhat/tophat', 'gradient']) 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): sz = cv2.getTrackbarPos('op/size', 'morphology') @@ -73,8 +83,14 @@ if __name__ == '__main__': if ch == 27: break if ch == ord('1'): - cur_mode = modes.next() + if PY3: + cur_mode = next(modes) + else: + cur_mode = modes.next() 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() cv2.destroyAllWindows() diff --git a/samples/python2/mosse.py b/samples/python2/mosse.py index 81196dcc36..29a3a697f1 100755 --- a/samples/python2/mosse.py +++ b/samples/python2/mosse.py @@ -21,6 +21,14 @@ Keys: 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 cv2 from common import draw_str, RectSelector @@ -178,7 +186,7 @@ class App: if __name__ == '__main__': - print __doc__ + print (__doc__) import sys, getopt opts, args = getopt.getopt(sys.argv[1:], '', ['pause']) opts = dict(opts) diff --git a/samples/python2/mouse_and_match.py b/samples/python2/mouse_and_match.py index 7937140e38..c0b03d77e8 100755 --- a/samples/python2/mouse_and_match.py +++ b/samples/python2/mouse_and_match.py @@ -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. ESC to exit ''' + +# Python 2/3 compatibility +from __future__ import print_function + import numpy as np 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.imshow("gray", img) else: - print "selection is complete" + print("selection is complete") drag_start = None if __name__ == '__main__': @@ -61,7 +65,7 @@ if __name__ == '__main__': for infile in glob.glob( os.path.join(path, '*.*') ): 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": - print infile + print(infile) img=cv2.imread(infile,1) if img == None: diff --git a/samples/python2/opencv_version.py b/samples/python2/opencv_version.py index 8c966f18e7..44f1977362 100644 --- a/samples/python2/opencv_version.py +++ b/samples/python2/opencv_version.py @@ -1,5 +1,8 @@ #!/usr/bin/env python +# Python 2/3 compatibility +from __future__ import print_function + import cv2 if __name__ == '__main__': @@ -10,9 +13,9 @@ if __name__ == '__main__': param = "" if ("--build" == param): - print cv2.getBuildInformation() + print(cv2.getBuildInformation()) elif ("--help" == param): - print "\t--build\n\t\tprint complete build info" - print "\t--help\n\t\tprint this help" + print("\t--build\n\t\tprint complete build info") + print("\t--help\n\t\tprint this help") else: - print "Welcome to OpenCV" + print("Welcome to OpenCV") diff --git a/samples/python2/peopledetect.py b/samples/python2/peopledetect.py index 9d945dbcc8..c8843e05e0 100755 --- a/samples/python2/peopledetect.py +++ b/samples/python2/peopledetect.py @@ -1,5 +1,8 @@ #!/usr/bin/env python +# Python 2/3 compatibility +from __future__ import print_function + import numpy as np import cv2 @@ -27,20 +30,20 @@ if __name__ == '__main__': from glob import glob import itertools as it - print help_message + print(help_message) hog = cv2.HOGDescriptor() hog.setSVMDetector( cv2.HOGDescriptor_getDefaultPeopleDetector() ) for fn in it.chain(*map(glob, sys.argv[1:])): - print fn, ' - ', + print(fn, ' - ',) try: img = cv2.imread(fn) if img is None: - print 'Failed to load image file:', fn + print('Failed to load image file:', fn) continue except: - print 'loading error' + print('loading error') continue 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) draw_detections(img, found) 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) ch = 0xFF & cv2.waitKey() if ch == 27: diff --git a/samples/python2/squares.py b/samples/python2/squares.py index 84160a2919..512ad617dd 100755 --- a/samples/python2/squares.py +++ b/samples/python2/squares.py @@ -6,6 +6,13 @@ Simple "Square Detector" program. 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 cv2 diff --git a/samples/python2/turing.py b/samples/python2/turing.py index 94816e6c31..f9926ba909 100755 --- a/samples/python2/turing.py +++ b/samples/python2/turing.py @@ -7,6 +7,14 @@ Multiscale Turing Patterns generator 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 cv2 from common import draw_str @@ -20,7 +28,7 @@ Press ESC to stop. ''' if __name__ == '__main__': - print help_message + print(help_message) w, h = 512, 512 @@ -30,7 +38,7 @@ if __name__ == '__main__': if '-o' in args: fn = args['-o'] 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) cv2.randu(a, np.array([0]), np.array([1])) diff --git a/samples/python2/video.py b/samples/python2/video.py index 227b13f371..8bdec7440c 100755 --- a/samples/python2/video.py +++ b/samples/python2/video.py @@ -29,6 +29,9 @@ Keys: ''' +# Python 2/3 compatibility +from __future__ import print_function + import numpy as np 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_HEIGHT, h) 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: return create_capture(fallback, None) return cap @@ -171,7 +174,7 @@ if __name__ == '__main__': import sys import getopt - print __doc__ + print(__doc__) args, sources = getopt.getopt(sys.argv[1:], '', 'shotdir=') args = dict(args) @@ -194,6 +197,6 @@ if __name__ == '__main__': for i, img in enumerate(imgs): fn = '%s/shot_%d_%03d.bmp' % (shotdir, i, shot_idx) cv2.imwrite(fn, img) - print fn, 'saved' + print(fn, 'saved') shot_idx += 1 cv2.destroyAllWindows() diff --git a/samples/python2/video_threaded.py b/samples/python2/video_threaded.py index a638791c81..76d764b62d 100755 --- a/samples/python2/video_threaded.py +++ b/samples/python2/video_threaded.py @@ -15,6 +15,8 @@ Keyboard shortcuts: space - switch between multi and single threaded processing ''' +# Python 2/3 compatibility +from __future__ import print_function import numpy as np import cv2 @@ -37,7 +39,7 @@ class DummyTask: if __name__ == '__main__': import sys - print __doc__ + print(__doc__) try: fn = sys.argv[1]