Merge pull request #5802 from bastelflp:py3samples_docstr

This commit is contained in:
Vadim Pisarevsky 2015-12-18 07:20:53 +00:00
commit 2ecb48921b
12 changed files with 184 additions and 64 deletions

10
samples/python2/.gitignore vendored Normal file
View File

@ -0,0 +1,10 @@
# python binary files
*.pyc
__pycache__
# tmp files from examples
/output
*.dat
out.ply
svm_scores.npz
unused_api.txt

View File

@ -5,12 +5,23 @@ 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)
try:
if PY3:
exec(open(fn).read(), loc)
else:
execfile(fn, loc)
except:
pass
if '__doc__' not in loc:
print fn
print(fn)

View File

@ -1,5 +1,18 @@
#!/usr/bin/env python
'''
camera calibration for distorted images with chess board samples
reads distorted images, calculates the calibration and write undistorted images
usage:
calibrate.py [--debug <output path>] [--square_size] [<image mask>]
default values:
--debug: ./output/
--square_size: 1.0
<image mask> defaults to ../data/left*.jpg
'''
# Python 2/3 compatibility
from __future__ import print_function
@ -12,64 +25,88 @@ from common import splitfn
# built-in modules
import os
USAGE = '''
USAGE: calib.py [--save <filename>] [--debug <output path>] [--square_size] [<image mask>]
'''
if __name__ == '__main__':
import sys
import getopt
from glob import glob
args, img_mask = getopt.getopt(sys.argv[1:], '', ['save=', 'debug=', 'square_size='])
args, img_mask = getopt.getopt(sys.argv[1:], '', ['debug=', 'square_size='])
args = dict(args)
try:
args.setdefault('--debug', './output/')
args.setdefault('--square_size', 1.0)
if not img_mask:
img_mask = '../data/left*.jpg' # default
else:
img_mask = img_mask[0]
except:
img_mask = '../data/left*.jpg'
img_names = glob(img_mask)
debug_dir = args.get('--debug')
square_size = float(args.get('--square_size', 1.0))
if not os.path.isdir(debug_dir):
os.mkdir(debug_dir)
square_size = float(args.get('--square_size'))
pattern_size = (9, 6)
pattern_points = np.zeros( (np.prod(pattern_size), 3), np.float32 )
pattern_points[:,:2] = np.indices(pattern_size).T.reshape(-1, 2)
pattern_points = np.zeros((np.prod(pattern_size), 3), np.float32)
pattern_points[:, :2] = np.indices(pattern_size).T.reshape(-1, 2)
pattern_points *= square_size
obj_points = []
img_points = []
h, w = 0, 0
img_names_undistort = []
for fn in img_names:
print('processing %s...' % fn,)
print('processing %s... ' % fn, end='')
img = cv2.imread(fn, 0)
if img is None:
print("Failed to load", fn)
continue
print("Failed to load", fn)
continue
h, w = img.shape[:2]
found, corners = cv2.findChessboardCorners(img, pattern_size)
if found:
term = ( cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_COUNT, 30, 0.1 )
term = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_COUNT, 30, 0.1)
cv2.cornerSubPix(img, corners, (5, 5), (-1, -1), term)
if debug_dir:
vis = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
cv2.drawChessboardCorners(vis, pattern_size, corners, found)
path, name, ext = splitfn(fn)
cv2.imwrite('%s/%s_chess.bmp' % (debug_dir, name), vis)
outfile = debug_dir + name + '_chess.png'
cv2.imwrite(outfile, vis)
if found:
img_names_undistort.append(outfile)
if not found:
print('chessboard not found')
continue
img_points.append(corners.reshape(-1, 2))
obj_points.append(pattern_points)
print('ok')
# calculate camera distortion
rms, camera_matrix, dist_coefs, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, (w, h), None, None)
print("RMS:", rms)
print("\nRMS:", rms)
print("camera matrix:\n", camera_matrix)
print("distortion coefficients: ", dist_coefs.ravel())
# undistort the image with the calibration
print('')
for img_found in img_names_undistort:
img = cv2.imread(img_found)
h, w = img.shape[:2]
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(camera_matrix, dist_coefs, (w, h), 1, (w, h))
dst = cv2.undistort(img, camera_matrix, dist_coefs, None, newcameramtx)
# crop and save the image
x, y, w, h = roi
dst = dst[y:y+h, x:x+w]
outfile = img_found + '_undistorted.png'
print('Undistorted image written to: %s' % outfile)
cv2.imwrite(outfile, dst)
cv2.destroyAllWindows()

View File

@ -1,11 +1,18 @@
#!/usr/bin/env python
'''
Video histogram sample to show live histogram of video
Keys:
ESC - exit
'''
import numpy as np
import cv2
# built-in modules
import sys
from time import clock
# local modules
import video
@ -22,6 +29,7 @@ if __name__ == '__main__':
cv2.namedWindow('hist', 0)
hist_scale = 10
def set_scale(val):
global hist_scale
hist_scale = val
@ -42,8 +50,7 @@ if __name__ == '__main__':
hsv = cv2.cvtColor(small, cv2.COLOR_BGR2HSV)
dark = hsv[...,2] < 32
hsv[dark] = 0
h = cv2.calcHist( [hsv], [0, 1], None, [180, 256], [0, 180, 0, 256] )
h = cv2.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])
h = np.clip(h*0.005*hist_scale, 0, 1)
vis = hsv_map*h[:,:,np.newaxis] / 255.0

View File

@ -1,5 +1,13 @@
#!/usr/bin/env python
'''
sample for disctrete fourier transform (dft)
USAGE:
dft.py <image_file>
'''
# Python 2/3 compatibility
from __future__ import print_function
@ -56,9 +64,9 @@ def shift_dft(src, dst=None):
if __name__ == "__main__":
if len(sys.argv)>1:
if len(sys.argv) > 1:
im = cv2.imread(sys.argv[1])
else :
else:
im = cv2.imread('../data/baboon.jpg')
print("usage : python dft.py <image_file>")

View File

@ -1,5 +1,12 @@
#!/usr/bin/env python
'''
face detection using haar cascades
USAGE:
facedetect.py [--cascade <cascade_fn>] [--nested-cascade <cascade_fn>] [<video_source>]
'''
# Python 2/3 compatibility
from __future__ import print_function
@ -10,12 +17,10 @@ import cv2
from video import create_capture
from common import clock, draw_str
help_message = '''
USAGE: facedetect.py [--cascade <cascade_fn>] [--nested-cascade <cascade_fn>] [<video_source>]
'''
def detect(img, cascade):
rects = cascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30), flags = cv2.CASCADE_SCALE_IMAGE)
rects = cascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE)
if len(rects) == 0:
return []
rects[:,2:] += rects[:,:2]
@ -27,7 +32,7 @@ def draw_rects(img, rects, color):
if __name__ == '__main__':
import sys, getopt
print(help_message)
print(__doc__)
args, video_src = getopt.getopt(sys.argv[1:], '', ['cascade=', 'nested-cascade='])
try:

View File

@ -2,8 +2,10 @@
'''
This example illustrates how to use cv2.HoughCircles() function.
Usage: ./houghcircles.py [<image_name>]
image argument defaults to ../data/board.jpg
Usage:
houghcircles.py [<image_name>]
image argument defaults to ../data/board.jpg
'''
# Python 2/3 compatibility
@ -14,11 +16,11 @@ import numpy as np
import sys
if __name__ == '__main__':
print(__doc__)
try:
fn = sys.argv[1]
except:
except IndexError:
fn = "../data/board.jpg"
src = cv2.imread(fn, 1)
@ -30,7 +32,7 @@ if __name__ == '__main__':
a, b, c = circles.shape
for i in range(b):
cv2.circle(cimg, (circles[0][i][0], circles[0][i][1]), circles[0][i][2], (0, 0, 255), 3, cv2.LINE_AA)
cv2.circle(cimg, (circles[0][i][0], circles[0][i][1]), 2, (0, 255, 0), 3, cv2.LINE_AA) # draw center of circle
cv2.circle(cimg, (circles[0][i][0], circles[0][i][1]), 2, (0, 255, 0), 3, cv2.LINE_AA) # draw center of circle
cv2.imshow("source", src)
cv2.imshow("detected circles", cimg)

View File

@ -1,9 +1,13 @@
#!/usr/bin/python
'''
This example illustrates how to use Hough Transform to find lines
Usage: ./houghlines.py [<image_name>]
image argument defaults to ../data/pic1.png
Usage:
houghlines.py [<image_name>]
image argument defaults to ../data/pic1.png
'''
# Python 2/3 compatibility
from __future__ import print_function
@ -13,12 +17,13 @@ import sys
import math
if __name__ == '__main__':
print(__doc__)
try:
fn = sys.argv[1]
except:
except IndexError:
fn = "../data/pic1.png"
print(__doc__)
src = cv2.imread(fn)
dst = cv2.Canny(src, 50, 200)
cdst = cv2.cvtColor(dst, cv2.COLOR_GRAY2BGR)
@ -42,7 +47,6 @@ if __name__ == '__main__':
pt2 = ( int(x0-1000*(-b)), int(y0-1000*(a)) )
cv2.line(cdst, pt1, pt2, (0, 0, 255), 3, cv2.LINE_AA)
cv2.imshow("source", src)
cv2.imshow("detected lines", cdst)
cv2.waitKey(0)

View File

@ -1,15 +1,27 @@
#!/usr/bin/env python
'''
plots image as logPolar and linearPolar
Usage:
logpolar.py
Keys:
ESC - exit
'''
# Python 2/3 compatibility
from __future__ import print_function
import cv2
if __name__ == '__main__':
print(__doc__)
import sys
try:
fn = sys.argv[1]
except:
except IndexError:
fn = '../data/fruits.jpg'
img = cv2.imread(fn)

View File

@ -1,5 +1,15 @@
#!/usr/bin/env python
'''
prints OpenCV version
Usage:
opencv_version.py [<params>]
params:
--build: print complete build info
--help: print this help
'''
# Python 2/3 compatibility
from __future__ import print_function
@ -7,14 +17,16 @@ import cv2
if __name__ == '__main__':
import sys
print(__doc__)
try:
param = sys.argv[1]
except:
except IndexError:
param = ""
if ("--build" == param):
if "--build" == param:
print(cv2.getBuildInformation())
elif ("--help" == param):
elif "--help" == param:
print("\t--build\n\t\tprint complete build info")
print("\t--help\n\t\tprint this help")
else:

View File

@ -1,5 +1,18 @@
#!/usr/bin/env python
'''
example to show optical flow
USAGE: opt_flow.py [<video_source>]
Keys:
1 - toggle HSV flow visualization
2 - toggle glitch
Keys:
ESC - exit
'''
# Python 2/3 compatibility
from __future__ import print_function
@ -7,14 +20,6 @@ import numpy as np
import cv2
import video
help_message = '''
USAGE: opt_flow.py [<video_source>]
Keys:
1 - toggle HSV flow visualization
2 - toggle glitch
'''
def draw_flow(img, flow, step=16):
h, w = img.shape[:2]
@ -28,6 +33,7 @@ def draw_flow(img, flow, step=16):
cv2.circle(vis, (x1, y1), 1, (0, 255, 0), -1)
return vis
def draw_hsv(flow):
h, w = flow.shape[:2]
fx, fy = flow[:,:,0], flow[:,:,1]
@ -40,6 +46,7 @@ def draw_hsv(flow):
bgr = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
return bgr
def warp_flow(img, flow):
h, w = flow.shape[:2]
flow = -flow
@ -50,10 +57,10 @@ def warp_flow(img, flow):
if __name__ == '__main__':
import sys
print(help_message)
print(__doc__)
try:
fn = sys.argv[1]
except:
except IndexError:
fn = 0
cam = video.create_capture(fn)

View File

@ -1,22 +1,27 @@
#!/usr/bin/env python
'''
example to detect upright people in images using HOG features
Usage:
peopledetect.py <image_names>
Press any key to continue, ESC to stop.
'''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np
import cv2
help_message = '''
USAGE: peopledetect.py <image_names> ...
Press any key to continue, ESC to stop.
'''
def inside(r, q):
rx, ry, rw, rh = r
qx, qy, qw, qh = q
return rx > qx and ry > qy and rx + rw < qx + qw and ry + rh < qy + qh
def draw_detections(img, rects, thickness = 1):
for x, y, w, h in rects:
# the HOG detector returns slightly larger rectangles than the real objects.
@ -30,13 +35,13 @@ if __name__ == '__main__':
from glob import glob
import itertools as it
print(help_message)
print(__doc__)
hog = cv2.HOGDescriptor()
hog.setSVMDetector( cv2.HOGDescriptor_getDefaultPeopleDetector() )
default = ['../data/basketball2.png '] if len(sys.argv[1:]) == 0 else []
for fn in it.chain(*map(glob, default + sys.argv[1:])):
print(fn, ' - ',)
try: