Merge pull request #622 from moshekaplan:python2_cleanups

This commit is contained in:
Andrey Kamaev 2013-03-11 21:14:20 +04:00 committed by OpenCV Buildbot
commit fb04f3a58d
48 changed files with 310 additions and 129 deletions

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
Utility for measuring python opencv API coverage by samples.

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
Scans current directory for *.py files and reports

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
Affine invariant feature-based image matching sample.
@ -21,9 +21,12 @@ USAGE
import numpy as np
import cv2
# built-in modules
import itertools as it
from multiprocessing.pool import ThreadPool
# local modules
from common import Timer
from find_obj import init_feature, filter_matches, explore_match
@ -85,15 +88,18 @@ def affine_detect(detector, img, mask=None, pool=None):
if descrs is None:
descrs = []
return keypoints, descrs
keypoints, descrs = [], []
if pool is None:
ires = it.imap(f, params)
else:
ires = pool.imap(f, params)
for i, (k, d) in enumerate(ires):
print 'affine sampling: %d / %d\r' % (i+1, len(params)),
keypoints.extend(k)
descrs.extend(d)
print
return keypoints, np.array(descrs)
@ -104,7 +110,8 @@ if __name__ == '__main__':
opts, args = getopt.getopt(sys.argv[1:], '', ['feature='])
opts = dict(opts)
feature_name = opts.get('--feature', 'sift-flann')
try: fn1, fn2 = args
try:
fn1, fn2 = args
except:
fn1 = 'data/aero1.jpg'
fn2 = 'data/aero3.jpg'
@ -112,11 +119,20 @@ if __name__ == '__main__':
img1 = cv2.imread(fn1, 0)
img2 = cv2.imread(fn2, 0)
detector, matcher = init_feature(feature_name)
if detector != None:
print 'using', feature_name
else:
if img1 is None:
print 'Failed to load fn1:', fn1
sys.exit(1)
if img2 is None:
print 'Failed to load fn2:', fn2
sys.exit(1)
if detector is None:
print 'unknown feature:', feature_name
sys.exit(1)
print 'using', feature_name
pool=ThreadPool(processes = cv2.getNumberOfCPUs())
kp1, desc1 = affine_detect(detector, img1, pool=pool)

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
browse.py
@ -14,6 +14,8 @@ browse.py [image filename]
import numpy as np
import cv2
# built-in modules
import sys
if __name__ == '__main__':
@ -25,6 +27,10 @@ if __name__ == '__main__':
fn = sys.argv[1]
print 'loading %s ...' % fn
img = cv2.imread(fn)
if img is None:
print 'Failed to load fn:', fn
sys.exit(1)
else:
sz = 4096
print 'generating %dx%d procedural image ...' % (sz, sz)
@ -33,6 +39,7 @@ if __name__ == '__main__':
track = np.int32(track*10 + (sz/2, sz/2))
cv2.polylines(img, [track], 0, 255, 1, cv2.CV_AA)
small = img
for i in xrange(3):
small = cv2.pyrDown(small)

View File

@ -1,10 +1,15 @@
#/usr/bin/env python
#!/usr/bin/env python
import numpy as np
import cv2
import os
# local modules
from common import splitfn
# built-in modules
import os
USAGE = '''
USAGE: calib.py [--save <filename>] [--debug <output path>] [--square_size] [<image mask>]
'''
@ -12,13 +17,17 @@ USAGE: calib.py [--save <filename>] [--debug <output path>] [--square_size] [<im
if __name__ == '__main__':
import sys, getopt
import sys
import getopt
from glob import glob
args, img_mask = getopt.getopt(sys.argv[1:], '', ['save=', 'debug=', 'square_size='])
args = dict(args)
try: img_mask = img_mask[0]
except: img_mask = '../cpp/left*.jpg'
try:
img_mask = img_mask[0]
except:
img_mask = '../cpp/left*.jpg'
img_names = glob(img_mask)
debug_dir = args.get('--debug')
square_size = float(args.get('--square_size', 1.0))
@ -34,6 +43,10 @@ if __name__ == '__main__':
for fn in img_names:
print 'processing %s...' % fn,
img = cv2.imread(fn, 0)
if img is None:
print "Failed to load", fn
continue
h, w = img.shape[:2]
found, corners = cv2.findChessboardCorners(img, pattern_size)
if found:

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
Camshift tracker
@ -24,6 +24,8 @@ Keys:
import numpy as np
import cv2
# local module
import video
@ -98,8 +100,10 @@ class App(object):
if self.show_backproj:
vis[:] = prob[...,np.newaxis]
try: cv2.ellipse(vis, track_box, (0, 0, 255), 2)
except: print track_box
try:
cv2.ellipse(vis, track_box, (0, 0, 255), 2)
except:
print track_box
cv2.imshow('camshift', vis)
@ -113,8 +117,10 @@ class App(object):
if __name__ == '__main__':
import sys
try: video_src = sys.argv[1]
except: video_src = 0
try:
video_src = sys.argv[1]
except:
video_src = 0
print __doc__
App(video_src).run()

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
Coherence-enhancing filtering example
@ -40,8 +40,10 @@ def coherence_filter(img, sigma = 11, str_sigma = 11, blend = 0.5, iter_n = 4):
if __name__ == '__main__':
import sys
try: fn = sys.argv[1]
except: fn = '../cpp/baboon.jpg'
try:
fn = sys.argv[1]
except:
fn = '../cpp/baboon.jpg'
src = cv2.imread(fn)

View File

@ -1,10 +1,13 @@
#/usr/bin/env python
#!/usr/bin/env python
import numpy as np
import cv2
from time import clock
import sys
# built-in modules
import sys
from time import clock
# local modules
import video
if __name__ == '__main__':
@ -24,8 +27,10 @@ if __name__ == '__main__':
hist_scale = val
cv2.createTrackbar('scale', 'hist', hist_scale, 32, set_scale)
try: fn = sys.argv[1]
except: fn = 0
try:
fn = sys.argv[1]
except:
fn = 0
cam = video.create_capture(fn, fallback='synth:bg=../cpp/baboon.jpg:class=chess:noise=0.05')
while True:

View File

@ -1,14 +1,14 @@
#/usr/bin/env python
'''
This module contains some common routines used by other samples.
'''
import numpy as np
import cv2
# built-in modules
import os
from contextlib import contextmanager
import itertools as it
from contextlib import contextmanager
image_extensions = ['.bmp', '.jpg', '.jpeg', '.png', '.tif', '.tiff', '.pbm', '.pgm', '.ppm']

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
This program illustrates the use of findContours and drawContours.

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
Wiener deconvolution.
@ -32,6 +32,8 @@ Examples:
import numpy as np
import cv2
# local module
from common import nothing
@ -65,12 +67,18 @@ if __name__ == '__main__':
import sys, getopt
opts, args = getopt.getopt(sys.argv[1:], '', ['circle', 'angle=', 'd=', 'snr='])
opts = dict(opts)
try: fn = args[0]
except: fn = 'data/licenseplate_motion.jpg'
try:
fn = args[0]
except:
fn = 'data/licenseplate_motion.jpg'
win = 'deconvolution'
img = cv2.imread(fn, 0)
if img is None:
print 'Failed to load fn1:', fn1
sys.exit(1)
img = np.float32(img)/255.0
cv2.imshow('input', img)

View File

@ -1,15 +1,20 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
Sample-launcher application.
'''
import Tkinter as tk
from ScrolledText import ScrolledText
from glob import glob
# 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
#from IPython.Shell import IPShellEmbed
#ipshell = IPShellEmbed()
@ -136,7 +141,8 @@ class App:
count = tk.IntVar()
while True:
match_index = text.search(pattern, 'matchPos', count=count, regexp=regexp, stopindex='end')
if not match_index: break
if not match_index:
break
end_index = text.index( "%s+%sc" % (match_index, count.get()) )
text.mark_set('matchPos', end_index)
if callable(tag_proc):
@ -147,7 +153,7 @@ class App:
def on_run(self, *args):
cmd = self.cmd_entry.get()
print 'running:', cmd
Popen("python " + cmd, shell=True)
Popen(sys.executable + ' ' + cmd, shell=True)
def run(self):
tk.mainloop()

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
SVM and KNearest digit recognition.
@ -23,12 +23,19 @@ Usage:
digits.py
'''
import numpy as np
import cv2
# built-in modules
from multiprocessing.pool import ThreadPool
from common import clock, mosaic
import cv2
import numpy as np
from numpy.linalg import norm
# local modules
from common import clock, mosaic
SZ = 20 # size of each digit is SZ x SZ
CLASS_N = 10
DIGITS_FN = 'data/digits.png'

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
Digit recognition adjustment.

View File

@ -1,17 +1,23 @@
#/usr/bin/env python
#!/usr/bin/env python
import numpy as np
import cv2
# built-in modules
import os
import sys
# local modules
import video
from common import mosaic
from digits import *
def main():
try: src = sys.argv[1]
except: src = 0
try:
src = sys.argv[1]
except:
src = 0
cap = video.create_capture(src)
classifier_fn = 'digits_svm.dat'
@ -30,8 +36,10 @@ def main():
bin = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 31, 10)
bin = cv2.medianBlur(bin, 3)
contours, heirs = cv2.findContours( bin.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
try: heirs = heirs[0]
except: heirs = []
try:
heirs = heirs[0]
except:
heirs = []
for cnt, heir in zip(contours, heirs):
_, _, _, outer_i = heir

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
Distance transform sample.
@ -15,15 +15,22 @@ Keys:
import numpy as np
import cv2
import cv2.cv as cv
from common import make_cmap
if __name__ == '__main__':
import sys
try: fn = sys.argv[1]
except: fn = '../cpp/fruits.jpg'
try:
fn = sys.argv[1]
except:
fn = '../cpp/fruits.jpg'
print __doc__
img = cv2.imread(fn, 0)
if img is None:
print 'Failed to load fn:', fn
sys.exit(1)
cm = make_cmap('jet')
need_update = True
voronoi = False

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
This sample demonstrates Canny edge detection.
@ -11,15 +11,21 @@ Usage:
'''
import cv2
# relative module
import video
# built-in module
import sys
if __name__ == '__main__':
print __doc__
try: fn = sys.argv[1]
except: fn = 0
try:
fn = sys.argv[1]
except:
fn = 0
def nothing(*arg):
pass

View File

@ -1,8 +1,10 @@
#/usr/bin/env python
#!/usr/bin/env python
import numpy as np
import cv2
import cv2.cv as cv
# local modules
from video import create_capture
from common import clock, draw_str
@ -26,8 +28,10 @@ if __name__ == '__main__':
print help_message
args, video_src = getopt.getopt(sys.argv[1:], '', ['cascade=', 'nested-cascade='])
try: video_src = video_src[0]
except: video_src = 0
try:
video_src = video_src[0]
except:
video_src = 0
args = dict(args)
cascade_fn = args.get('--cascade', "../../data/haarcascades/haarcascade_frontalface_alt.xml")
nested_fn = args.get('--nested-cascade', "../../data/haarcascades/haarcascade_eye.xml")

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
Feature homography
@ -24,6 +24,8 @@ Select a textured planar object to track by drawing a box with a mouse.
import numpy as np
import cv2
# local modules
import video
import common
from common import getsize, draw_keypoints
@ -85,6 +87,8 @@ if __name__ == '__main__':
print __doc__
import sys
try: video_src = sys.argv[1]
except: video_src = 0
try:
video_src = sys.argv[1]
except:
video_src = 0
App(video_src).run()

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
Feature-based image matching sample.

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
Robust line fitting.
@ -24,7 +24,11 @@ ESC - exit
import numpy as np
import cv2
# built-in modules
import itertools as it
# local modules
from common import draw_str

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
Floodfill sample.
@ -19,11 +19,17 @@ import cv2
if __name__ == '__main__':
import sys
try: fn = sys.argv[1]
except: fn = '../cpp/fruits.jpg'
try:
fn = sys.argv[1]
except:
fn = '../cpp/fruits.jpg'
print __doc__
img = cv2.imread(fn, True)
if img is None:
print 'Failed to load image file:', fn
sys.exit(1)
h, w = img.shape[:2]
mask = np.zeros((h+2, w+2), np.uint8)
seed_pt = None

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
gabor_threads.py
@ -49,10 +49,16 @@ if __name__ == '__main__':
from common import Timer
print __doc__
try: img_fn = sys.argv[1]
except: img_fn = '../cpp/baboon.jpg'
try:
img_fn = sys.argv[1]
except:
img_fn = '../cpp/baboon.jpg'
img = cv2.imread(img_fn)
if img is None:
print 'Failed to load image file:', img_fn
sys.exit(1)
filters = build_filters()
with Timer('running single-threaded'):

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
import numpy as np
from numpy import random

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
''' This is a sample for histogram plotting for RGB images and grayscale images for better understanding of colour distribution
@ -55,11 +55,16 @@ if __name__ == '__main__':
import sys
if len(sys.argv)>1:
im = cv2.imread(sys.argv[1])
fname = sys.argv[1]
else :
im = cv2.imread('../cpp/lena.jpg')
fname = '../cpp/lena.jpg'
print "usage : python hist.py <image_file>"
im = cv2.imread(fname)
if im is None:
print 'Failed to load image file:', fname
sys.exit(1)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
Inpainting sample.
@ -21,11 +21,18 @@ from common import Sketcher
if __name__ == '__main__':
import sys
try: fn = sys.argv[1]
except: fn = '../cpp/fruits.jpg'
try:
fn = sys.argv[1]
except:
fn = '../cpp/fruits.jpg'
print __doc__
img = cv2.imread(fn)
if img is None:
print 'Failed to load image file:', fn
sys.exit(1)
img_mark = img.copy()
mark = np.zeros(img.shape[:2], np.uint8)
sketch = Sketcher('img', [img_mark, mark], lambda : ((255, 255, 255), 255))

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
K-means clusterization sample.

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
''' An example of Laplacian Pyramid construction and merging.
@ -40,8 +40,10 @@ if __name__ == '__main__':
import sys
print __doc__
try: fn = sys.argv[1]
except: fn = 0
try:
fn = sys.argv[1]
except:
fn = 0
cap = video.create_capture(fn)
leveln = 6

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
The sample demonstrates how to train Random Trees classifier

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
Lucas-Kanade homography tracker
@ -103,8 +103,10 @@ class App:
def main():
import sys
try: video_src = sys.argv[1]
except: video_src = 0
try:
video_src = sys.argv[1]
except:
video_src = 0
print __doc__
App(video_src).run()

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
Lucas-Kanade tracker
@ -88,8 +88,10 @@ class App:
def main():
import sys
try: video_src = sys.argv[1]
except: video_src = 0
try:
video_src = sys.argv[1]
except:
video_src = 0
print __doc__
App(video_src).run()

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
Morphology operations.
@ -23,9 +23,17 @@ if __name__ == '__main__':
from itertools import cycle
from common import draw_str
try: fn = sys.argv[1]
except: fn = '../cpp/baboon.jpg'
try:
fn = sys.argv[1]
except:
fn = '../cpp/baboon.jpg'
img = cv2.imread(fn)
if img is None:
print 'Failed to load image file:', fn
sys.exit(1)
cv2.imshow('original', img)
modes = cycle(['erode/dilate', 'open/close', 'blackhat/tophat', 'gradient'])

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
MOSSE tracking sample
@ -182,7 +182,9 @@ if __name__ == '__main__':
import sys, getopt
opts, args = getopt.getopt(sys.argv[1:], '', ['pause'])
opts = dict(opts)
try: video_src = args[0]
except: video_src = '0'
try:
video_src = args[0]
except:
video_src = '0'
App(video_src, paused = '--pause' in opts).run()

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
import numpy as np
import cv2
@ -20,8 +20,10 @@ def draw_motion_comp(vis, (x, y, w, h), angle, color):
if __name__ == '__main__':
import sys
try: video_src = sys.argv[1]
except: video_src = 0
try:
video_src = sys.argv[1]
except:
video_src = 0
cv2.namedWindow('motempl')
visuals = ['input', 'frame_diff', 'motion_hist', 'grad_orient']

View File

@ -1,5 +1,3 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
mouse_and_match.py [-i path | --input path: default ./]
@ -11,12 +9,15 @@ Demonstrate using a mouse to interact with an image:
ESC to exit
'''
import numpy as np
from math import *
import sys
import cv2 as cv
# built-in modules
import os
import sys
import glob
import argparse
import cv2 as cv
from math import *
drag_start = None
sel = (0,0,0,0)

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
MSER detector demo
@ -20,8 +20,10 @@ import video
if __name__ == '__main__':
import sys
try: video_src = sys.argv[1]
except: video_src = 0
try:
video_src = sys.argv[1]
except:
video_src = 0
cam = video.create_capture(video_src)
mser = cv2.MSER()

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
import numpy as np
import cv2
@ -48,8 +48,10 @@ def warp_flow(img, flow):
if __name__ == '__main__':
import sys
print help_message
try: fn = sys.argv[1]
except: fn = 0
try:
fn = sys.argv[1]
except:
fn = 0
cam = video.create_capture(fn)
ret, prev = cam.read()

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
import numpy as np
import cv2
@ -36,6 +36,9 @@ if __name__ == '__main__':
print fn, ' - ',
try:
img = cv2.imread(fn)
if img is None:
print 'Failed to load image file:', fn
continue
except:
print 'loading error'
continue

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
Planar augmented reality
@ -100,6 +100,8 @@ if __name__ == '__main__':
print __doc__
import sys
try: video_src = sys.argv[1]
except: video_src = 0
try:
video_src = sys.argv[1]
except:
video_src = 0
App(video_src).run()

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
Multitarget planar tracking
@ -23,7 +23,11 @@ Select a textured planar object to track by drawing a box with a mouse.
import numpy as np
import cv2
# built-in modules
from collections import namedtuple
# local modules
import video
import common
@ -168,6 +172,8 @@ if __name__ == '__main__':
print __doc__
import sys
try: video_src = sys.argv[1]
except: video_src = 0
try:
video_src = sys.argv[1]
except:
video_src = 0
App(video_src).run()

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
Simple "Square Detector" program.

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
Simple example of stereo image matching and point cloud generation.

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
Texture flow direction estimation.
@ -15,10 +15,16 @@ import cv2
if __name__ == '__main__':
import sys
try: fn = sys.argv[1]
except: fn = 'data/starry_night.jpg'
try:
fn = sys.argv[1]
except:
fn = 'data/starry_night.jpg'
img = cv2.imread(fn)
if img is None:
print 'Failed to load image file:', fn
sys.exit(1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
h, w = img.shape[:2]

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
Multiscale Turing Patterns generator

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
Video capture sample.
@ -30,9 +30,14 @@ Keys:
'''
import numpy as np
import cv2
from time import clock
from numpy import pi, sin, cos
import cv2
# built-in modules
from time import clock
# local modules
import common
class VideoSynthBase(object):

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
Data matrix detector sample.
@ -18,6 +18,8 @@ Keyboard shortcuts:
import cv2
import numpy as np
# built-in modules
import sys
def data_matrix_demo(cap):

View File

@ -1,4 +1,4 @@
#/usr/bin/env python
#!/usr/bin/env python
'''
Multithreaded video processing sample.
@ -39,8 +39,10 @@ if __name__ == '__main__':
print __doc__
try: fn = sys.argv[1]
except: fn = 0
try:
fn = sys.argv[1]
except:
fn = 0
cap = video.create_capture(fn)

View File

@ -31,6 +31,9 @@ from common import Sketcher
class App:
def __init__(self, fn):
self.img = cv2.imread(fn)
if self.img is None:
raise Exception('Failed to load image file: %s' % fn)
h, w = self.img.shape[:2]
self.markers = np.zeros((h, w), np.int32)
self.markers_vis = self.img.copy()
@ -73,7 +76,9 @@ class App:
if __name__ == '__main__':
import sys
try: fn = sys.argv[1]
except: fn = '../cpp/fruits.jpg'
try:
fn = sys.argv[1]
except:
fn = '../cpp/fruits.jpg'
print __doc__
App(fn).run()