Skip to content

Commit c2e8214

Browse files
committed
官方samples
1 parent 7d74052 commit c2e8214

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

63 files changed

+5830
-0
lines changed

官方samples/CMakeLists.txt

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
if(INSTALL_PYTHON_EXAMPLES)
2+
file(GLOB install_list *.py )
3+
install(FILES ${install_list}
4+
DESTINATION ${OPENCV_SAMPLES_SRC_INSTALL_PATH}/python
5+
PERMISSIONS OWNER_READ GROUP_READ WORLD_READ COMPONENT samples)
6+
endif()

官方samples/_coverage.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#!/usr/bin/env python
2+
3+
'''
4+
Utility for measuring python opencv API coverage by samples.
5+
'''
6+
7+
# Python 2/3 compatibility
8+
from __future__ import print_function
9+
10+
from glob import glob
11+
import cv2
12+
import re
13+
14+
if __name__ == '__main__':
15+
cv2_callable = set(['cv2.'+name for name in dir(cv2) if callable( getattr(cv2, name) )])
16+
17+
found = set()
18+
for fn in glob('*.py'):
19+
print(' --- ', fn)
20+
code = open(fn).read()
21+
found |= set(re.findall('cv2?\.\w+', code))
22+
23+
cv2_used = found & cv2_callable
24+
cv2_unused = cv2_callable - cv2_used
25+
with open('unused_api.txt', 'w') as f:
26+
f.write('\n'.join(sorted(cv2_unused)))
27+
28+
r = 1.0 * len(cv2_used) / len(cv2_callable)
29+
print('\ncv2 api coverage: %d / %d (%.1f%%)' % ( len(cv2_used), len(cv2_callable), r*100 ))

官方samples/_doc.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
#!/usr/bin/env python
2+
3+
'''
4+
Scans current directory for *.py files and reports
5+
ones with missing __doc__ string.
6+
'''
7+
8+
# Python 2/3 compatibility
9+
from __future__ import print_function
10+
import sys
11+
PY3 = sys.version_info[0] == 3
12+
13+
from glob import glob
14+
15+
if __name__ == '__main__':
16+
print('--- undocumented files:')
17+
for fn in glob('*.py'):
18+
loc = {}
19+
try:
20+
if PY3:
21+
exec(open(fn).read(), loc)
22+
else:
23+
execfile(fn, loc)
24+
except:
25+
pass
26+
if '__doc__' not in loc:
27+
print(fn)
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
@echo off
2+
if NOT exist %CD%\..\..\..\build (
3+
echo ERROR: OpenCV Winpack installation is required
4+
pause
5+
exit
6+
)
7+
8+
:: Path to FFMPEG binary files
9+
set PATH=%PATH%;%CD%\..\..\..\build\bin\
10+
11+
:: Detect Python binary
12+
python -V
13+
if %ERRORLEVEL% EQU 0 (
14+
set PYTHON=python
15+
) else (
16+
if exist C:\Python27-x64\python.exe (
17+
set PYTHON=C:\Python27-x64\python.exe
18+
) else (
19+
if exist C:\Python27\python.exe (
20+
set PYTHON=C:\Python27\python.exe
21+
) else (
22+
echo ERROR: Python not found
23+
pause
24+
exit
25+
)
26+
)
27+
)
28+
echo Using python: %PYTHON%
29+
30+
:: Detect python architecture
31+
%PYTHON% -c "import platform; exit(64 if platform.architecture()[0] == '64bit' else 32)"
32+
if %ERRORLEVEL% EQU 32 (
33+
echo Detected: Python 32-bit
34+
set PYTHONPATH=%CD%\..\..\..\build\python\2.7\x86
35+
) else (
36+
if %ERRORLEVEL% EQU 64 (
37+
echo Detected: Python 64-bit
38+
set PYTHONPATH=%CD%\..\..\..\build\python\2.7\x64
39+
) else (
40+
echo ERROR: Unknown python arch
41+
pause
42+
exit
43+
)
44+
)
45+
46+
:: Launch demo
47+
%PYTHON% demo.py

官方samples/asift.py

Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
#!/usr/bin/env python
2+
3+
'''
4+
Affine invariant feature-based image matching sample.
5+
6+
This sample is similar to find_obj.py, but uses the affine transformation
7+
space sampling technique, called ASIFT [1]. While the original implementation
8+
is based on SIFT, you can try to use SURF or ORB detectors instead. Homography RANSAC
9+
is used to reject outliers. Threading is used for faster affine sampling.
10+
11+
[1] http://www.ipol.im/pub/algo/my_affine_sift/
12+
13+
USAGE
14+
asift.py [--feature=<sift|surf|orb|brisk>[-flann]] [ <image1> <image2> ]
15+
16+
--feature - Feature to use. Can be sift, surf, orb or brisk. Append '-flann'
17+
to feature name to use Flann-based matcher instead bruteforce.
18+
19+
Press left mouse button on a feature point to see its matching point.
20+
'''
21+
22+
# Python 2/3 compatibility
23+
from __future__ import print_function
24+
25+
import numpy as np
26+
import cv2
27+
28+
# built-in modules
29+
import itertools as it
30+
from multiprocessing.pool import ThreadPool
31+
32+
# local modules
33+
from common import Timer
34+
from find_obj import init_feature, filter_matches, explore_match
35+
36+
37+
def affine_skew(tilt, phi, img, mask=None):
38+
'''
39+
affine_skew(tilt, phi, img, mask=None) -> skew_img, skew_mask, Ai
40+
41+
Ai - is an affine transform matrix from skew_img to img
42+
'''
43+
h, w = img.shape[:2]
44+
if mask is None:
45+
mask = np.zeros((h, w), np.uint8)
46+
mask[:] = 255
47+
A = np.float32([[1, 0, 0], [0, 1, 0]])
48+
if phi != 0.0:
49+
phi = np.deg2rad(phi)
50+
s, c = np.sin(phi), np.cos(phi)
51+
A = np.float32([[c,-s], [ s, c]])
52+
corners = [[0, 0], [w, 0], [w, h], [0, h]]
53+
tcorners = np.int32( np.dot(corners, A.T) )
54+
x, y, w, h = cv2.boundingRect(tcorners.reshape(1,-1,2))
55+
A = np.hstack([A, [[-x], [-y]]])
56+
img = cv2.warpAffine(img, A, (w, h), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)
57+
if tilt != 1.0:
58+
s = 0.8*np.sqrt(tilt*tilt-1)
59+
img = cv2.GaussianBlur(img, (0, 0), sigmaX=s, sigmaY=0.01)
60+
img = cv2.resize(img, (0, 0), fx=1.0/tilt, fy=1.0, interpolation=cv2.INTER_NEAREST)
61+
A[0] /= tilt
62+
if phi != 0.0 or tilt != 1.0:
63+
h, w = img.shape[:2]
64+
mask = cv2.warpAffine(mask, A, (w, h), flags=cv2.INTER_NEAREST)
65+
Ai = cv2.invertAffineTransform(A)
66+
return img, mask, Ai
67+
68+
69+
def affine_detect(detector, img, mask=None, pool=None):
70+
'''
71+
affine_detect(detector, img, mask=None, pool=None) -> keypoints, descrs
72+
73+
Apply a set of affine transormations to the image, detect keypoints and
74+
reproject them into initial image coordinates.
75+
See http://www.ipol.im/pub/algo/my_affine_sift/ for the details.
76+
77+
ThreadPool object may be passed to speedup the computation.
78+
'''
79+
params = [(1.0, 0.0)]
80+
for t in 2**(0.5*np.arange(1,6)):
81+
for phi in np.arange(0, 180, 72.0 / t):
82+
params.append((t, phi))
83+
84+
def f(p):
85+
t, phi = p
86+
timg, tmask, Ai = affine_skew(t, phi, img)
87+
keypoints, descrs = detector.detectAndCompute(timg, tmask)
88+
for kp in keypoints:
89+
x, y = kp.pt
90+
kp.pt = tuple( np.dot(Ai, (x, y, 1)) )
91+
if descrs is None:
92+
descrs = []
93+
return keypoints, descrs
94+
95+
keypoints, descrs = [], []
96+
if pool is None:
97+
ires = it.imap(f, params)
98+
else:
99+
ires = pool.imap(f, params)
100+
101+
for i, (k, d) in enumerate(ires):
102+
print('affine sampling: %d / %d\r' % (i+1, len(params)), end='')
103+
keypoints.extend(k)
104+
descrs.extend(d)
105+
106+
print()
107+
return keypoints, np.array(descrs)
108+
109+
if __name__ == '__main__':
110+
print(__doc__)
111+
112+
import sys, getopt
113+
opts, args = getopt.getopt(sys.argv[1:], '', ['feature='])
114+
opts = dict(opts)
115+
feature_name = opts.get('--feature', 'brisk-flann')
116+
try:
117+
fn1, fn2 = args
118+
except:
119+
fn1 = '../data/aero1.jpg'
120+
fn2 = '../data/aero3.jpg'
121+
122+
img1 = cv2.imread(fn1, 0)
123+
img2 = cv2.imread(fn2, 0)
124+
detector, matcher = init_feature(feature_name)
125+
126+
if img1 is None:
127+
print('Failed to load fn1:', fn1)
128+
sys.exit(1)
129+
130+
if img2 is None:
131+
print('Failed to load fn2:', fn2)
132+
sys.exit(1)
133+
134+
if detector is None:
135+
print('unknown feature:', feature_name)
136+
sys.exit(1)
137+
138+
print('using', feature_name)
139+
140+
pool=ThreadPool(processes = cv2.getNumberOfCPUs())
141+
kp1, desc1 = affine_detect(detector, img1, pool=pool)
142+
kp2, desc2 = affine_detect(detector, img2, pool=pool)
143+
print('img1 - %d features, img2 - %d features' % (len(kp1), len(kp2)))
144+
145+
def match_and_draw(win):
146+
with Timer('matching'):
147+
raw_matches = matcher.knnMatch(desc1, trainDescriptors = desc2, k = 2) #2
148+
p1, p2, kp_pairs = filter_matches(kp1, kp2, raw_matches)
149+
if len(p1) >= 4:
150+
H, status = cv2.findHomography(p1, p2, cv2.RANSAC, 5.0)
151+
print('%d / %d inliers/matched' % (np.sum(status), len(status)))
152+
# do not draw outliers (there will be a lot of them)
153+
kp_pairs = [kpp for kpp, flag in zip(kp_pairs, status) if flag]
154+
else:
155+
H, status = None, None
156+
print('%d matches found, not enough for homography estimation' % len(p1))
157+
158+
vis = explore_match(win, img1, img2, kp_pairs, None, H)
159+
160+
161+
match_and_draw('affine find_obj')
162+
cv2.waitKey()
163+
cv2.destroyAllWindows()

官方samples/browse.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
#!/usr/bin/env python
2+
3+
'''
4+
browse.py
5+
=========
6+
7+
Sample shows how to implement a simple hi resolution image navigation
8+
9+
Usage
10+
-----
11+
browse.py [image filename]
12+
13+
'''
14+
15+
# Python 2/3 compatibility
16+
from __future__ import print_function
17+
import sys
18+
PY3 = sys.version_info[0] == 3
19+
20+
if PY3:
21+
xrange = range
22+
23+
import numpy as np
24+
import cv2
25+
26+
# built-in modules
27+
import sys
28+
29+
if __name__ == '__main__':
30+
print('This sample shows how to implement a simple hi resolution image navigation.')
31+
print('USAGE: browse.py [image filename]')
32+
print()
33+
34+
if len(sys.argv) > 1:
35+
fn = sys.argv[1]
36+
print('loading %s ...' % fn)
37+
img = cv2.imread(fn)
38+
if img is None:
39+
print('Failed to load fn:', fn)
40+
sys.exit(1)
41+
42+
else:
43+
sz = 4096
44+
print('generating %dx%d procedural image ...' % (sz, sz))
45+
img = np.zeros((sz, sz), np.uint8)
46+
track = np.cumsum(np.random.rand(500000, 2)-0.5, axis=0)
47+
track = np.int32(track*10 + (sz/2, sz/2))
48+
cv2.polylines(img, [track], 0, 255, 1, cv2.LINE_AA)
49+
50+
51+
small = img
52+
for i in xrange(3):
53+
small = cv2.pyrDown(small)
54+
55+
def onmouse(event, x, y, flags, param):
56+
h, w = img.shape[:2]
57+
h1, w1 = small.shape[:2]
58+
x, y = 1.0*x*h/h1, 1.0*y*h/h1
59+
zoom = cv2.getRectSubPix(img, (800, 600), (x+0.5, y+0.5))
60+
cv2.imshow('zoom', zoom)
61+
62+
cv2.imshow('preview', small)
63+
cv2.setMouseCallback('preview', onmouse)
64+
cv2.waitKey()
65+
cv2.destroyAllWindows()

0 commit comments

Comments
 (0)