Commit 49f43b03 authored by Alexander Alekhin's avatar Alexander Alekhin

Merge pull request #14108 from alalek:fix_python_samples_3.4

parents 58835eeb 04fad57f
...@@ -106,9 +106,8 @@ def affine_detect(detector, img, mask=None, pool=None): ...@@ -106,9 +106,8 @@ def affine_detect(detector, img, mask=None, pool=None):
print() print()
return keypoints, np.array(descrs) return keypoints, np.array(descrs)
if __name__ == '__main__':
print(__doc__)
def main():
import sys, getopt import sys, getopt
opts, args = getopt.getopt(sys.argv[1:], '', ['feature=']) opts, args = getopt.getopt(sys.argv[1:], '', ['feature='])
opts = dict(opts) opts = dict(opts)
...@@ -160,4 +159,10 @@ if __name__ == '__main__': ...@@ -160,4 +159,10 @@ if __name__ == '__main__':
match_and_draw('affine find_obj') match_and_draw('affine find_obj')
cv.waitKey() cv.waitKey()
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()
...@@ -26,11 +26,7 @@ import cv2 as cv ...@@ -26,11 +26,7 @@ import cv2 as cv
# built-in modules # built-in modules
import sys import sys
if __name__ == '__main__': def main():
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: if len(sys.argv) > 1:
fn = cv.samples.findFile(sys.argv[1]) fn = cv.samples.findFile(sys.argv[1])
print('loading %s ...' % fn) print('loading %s ...' % fn)
...@@ -62,4 +58,10 @@ if __name__ == '__main__': ...@@ -62,4 +58,10 @@ if __name__ == '__main__':
cv.imshow('preview', small) cv.imshow('preview', small)
cv.setMouseCallback('preview', onmouse) cv.setMouseCallback('preview', onmouse)
cv.waitKey() cv.waitKey()
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()
...@@ -25,7 +25,7 @@ from common import splitfn ...@@ -25,7 +25,7 @@ from common import splitfn
# built-in modules # built-in modules
import os import os
if __name__ == '__main__': def main():
import sys import sys
import getopt import getopt
from glob import glob from glob import glob
...@@ -126,4 +126,10 @@ if __name__ == '__main__': ...@@ -126,4 +126,10 @@ if __name__ == '__main__':
print('Undistorted image written to: %s' % outfile) print('Undistorted image written to: %s' % outfile)
cv.imwrite(outfile, dst) cv.imwrite(outfile, dst)
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from mpl_toolkits.mplot3d import Axes3D # Python 2/3 compatibility
import matplotlib.pyplot as plt from __future__ import print_function
import numpy as np import numpy as np
from matplotlib import cm
from numpy import linspace
import argparse
import cv2 as cv import cv2 as cv
from numpy import linspace
def inverse_homogeneoux_matrix(M): def inverse_homogeneoux_matrix(M):
R = M[0:3, 0:3] R = M[0:3, 0:3]
T = M[0:3, 3] T = M[0:3, 3]
...@@ -119,6 +119,8 @@ def create_board_model(extrinsics, board_width, board_height, square_size, draw_ ...@@ -119,6 +119,8 @@ def create_board_model(extrinsics, board_width, board_height, square_size, draw_
def draw_camera_boards(ax, camera_matrix, cam_width, cam_height, scale_focal, def draw_camera_boards(ax, camera_matrix, cam_width, cam_height, scale_focal,
extrinsics, board_width, board_height, square_size, extrinsics, board_width, board_height, square_size,
patternCentric): patternCentric):
from matplotlib import cm
min_values = np.zeros((3,1)) min_values = np.zeros((3,1))
min_values = np.inf min_values = np.inf
max_values = np.zeros((3,1)) max_values = np.zeros((3,1))
...@@ -158,6 +160,8 @@ def draw_camera_boards(ax, camera_matrix, cam_width, cam_height, scale_focal, ...@@ -158,6 +160,8 @@ def draw_camera_boards(ax, camera_matrix, cam_width, cam_height, scale_focal,
return min_values, max_values return min_values, max_values
def main(): def main():
import argparse
parser = argparse.ArgumentParser(description='Plot camera calibration extrinsics.', parser = argparse.ArgumentParser(description='Plot camera calibration extrinsics.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter) formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--calibration', type=str, default='left_intrinsics.yml', parser.add_argument('--calibration', type=str, default='left_intrinsics.yml',
...@@ -179,6 +183,9 @@ def main(): ...@@ -179,6 +183,9 @@ def main():
camera_matrix = fs.getNode('camera_matrix').mat() camera_matrix = fs.getNode('camera_matrix').mat()
extrinsics = fs.getNode('extrinsic_parameters').mat() extrinsics = fs.getNode('extrinsic_parameters').mat()
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure() fig = plt.figure()
ax = fig.gca(projection='3d') ax = fig.gca(projection='3d')
ax.set_aspect("equal") ax.set_aspect("equal")
...@@ -211,6 +218,10 @@ def main(): ...@@ -211,6 +218,10 @@ def main():
ax.set_title('Extrinsic Parameters Visualization') ax.set_title('Extrinsic Parameters Visualization')
plt.show() plt.show()
print('Done')
if __name__ == "__main__": if __name__ == '__main__':
print(__doc__)
main() main()
cv.destroyAllWindows()
...@@ -119,10 +119,10 @@ class App(object): ...@@ -119,10 +119,10 @@ class App(object):
if __name__ == '__main__': if __name__ == '__main__':
print(__doc__)
import sys import sys
try: try:
video_src = sys.argv[1] video_src = sys.argv[1]
except: except:
video_src = 0 video_src = 0
print(__doc__)
App(video_src).run() App(video_src).run()
...@@ -46,7 +46,7 @@ def coherence_filter(img, sigma = 11, str_sigma = 11, blend = 0.5, iter_n = 4): ...@@ -46,7 +46,7 @@ def coherence_filter(img, sigma = 11, str_sigma = 11, blend = 0.5, iter_n = 4):
return img return img
if __name__ == '__main__': def main():
import sys import sys
try: try:
fn = sys.argv[1] fn = sys.argv[1]
...@@ -82,4 +82,11 @@ if __name__ == '__main__': ...@@ -82,4 +82,11 @@ if __name__ == '__main__':
update() update()
if ch == 27: if ch == 27:
break break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()
...@@ -8,6 +8,9 @@ Keys: ...@@ -8,6 +8,9 @@ Keys:
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np import numpy as np
import cv2 as cv import cv2 as cv
...@@ -17,46 +20,54 @@ import sys ...@@ -17,46 +20,54 @@ import sys
# local modules # local modules
import video import video
if __name__ == '__main__': class App():
def set_scale(self, val):
self.hist_scale = val
def run(self):
hsv_map = np.zeros((180, 256, 3), np.uint8)
h, s = np.indices(hsv_map.shape[:2])
hsv_map[:,:,0] = h
hsv_map[:,:,1] = s
hsv_map[:,:,2] = 255
hsv_map = cv.cvtColor(hsv_map, cv.COLOR_HSV2BGR)
cv.imshow('hsv_map', hsv_map)
cv.namedWindow('hist', 0)
self.hist_scale = 10
cv.createTrackbar('scale', 'hist', self.hist_scale, 32, self.set_scale)
try:
fn = sys.argv[1]
except:
fn = 0
cam = video.create_capture(fn, fallback='synth:bg=baboon.jpg:class=chess:noise=0.05')
while True:
flag, frame = cam.read()
cv.imshow('camera', frame)
hsv_map = np.zeros((180, 256, 3), np.uint8) small = cv.pyrDown(frame)
h, s = np.indices(hsv_map.shape[:2])
hsv_map[:,:,0] = h hsv = cv.cvtColor(small, cv.COLOR_BGR2HSV)
hsv_map[:,:,1] = s dark = hsv[...,2] < 32
hsv_map[:,:,2] = 255 hsv[dark] = 0
hsv_map = cv.cvtColor(hsv_map, cv.COLOR_HSV2BGR) h = cv.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])
cv.imshow('hsv_map', hsv_map)
h = np.clip(h*0.005*self.hist_scale, 0, 1)
cv.namedWindow('hist', 0) vis = hsv_map*h[:,:,np.newaxis] / 255.0
hist_scale = 10 cv.imshow('hist', vis)
def set_scale(val): ch = cv.waitKey(1)
global hist_scale if ch == 27:
hist_scale = val break
cv.createTrackbar('scale', 'hist', hist_scale, 32, set_scale)
print('Done')
try:
fn = sys.argv[1]
except: if __name__ == '__main__':
fn = 0 print(__doc__)
cam = video.create_capture(fn, fallback='synth:bg=baboon.jpg:class=chess:noise=0.05') App().run()
while True:
flag, frame = cam.read()
cv.imshow('camera', frame)
small = cv.pyrDown(frame)
hsv = cv.cvtColor(small, cv.COLOR_BGR2HSV)
dark = hsv[...,2] < 32
hsv[dark] = 0
h = cv.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
cv.imshow('hist', vis)
ch = cv.waitKey(1)
if ch == 27:
break
cv.destroyAllWindows() cv.destroyAllWindows()
...@@ -48,9 +48,7 @@ def make_image(): ...@@ -48,9 +48,7 @@ def make_image():
cv.ellipse( img, (dx+273, dy+100), (20,35), 0, 0, 360, white, -1 ) cv.ellipse( img, (dx+273, dy+100), (20,35), 0, 0, 360, white, -1 )
return img return img
if __name__ == '__main__': def main():
print(__doc__)
img = make_image() img = make_image()
h, w = img.shape[:2] h, w = img.shape[:2]
...@@ -67,4 +65,10 @@ if __name__ == '__main__': ...@@ -67,4 +65,10 @@ if __name__ == '__main__':
cv.createTrackbar( "levels+3", "contours", 3, 7, update ) cv.createTrackbar( "levels+3", "contours", 3, 7, update )
cv.imshow('image', img) cv.imshow('image', img)
cv.waitKey() cv.waitKey()
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()
...@@ -65,8 +65,7 @@ def defocus_kernel(d, sz=65): ...@@ -65,8 +65,7 @@ def defocus_kernel(d, sz=65):
return kern return kern
if __name__ == '__main__': def main():
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)
...@@ -128,3 +127,11 @@ if __name__ == '__main__': ...@@ -128,3 +127,11 @@ if __name__ == '__main__':
if ch == ord(' '): if ch == ord(' '):
defocus = not defocus defocus = not defocus
update(None) update(None)
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()
...@@ -11,8 +11,9 @@ USAGE: ...@@ -11,8 +11,9 @@ USAGE:
# Python 2/3 compatibility # Python 2/3 compatibility
from __future__ import print_function from __future__ import print_function
import cv2 as cv
import numpy as np import numpy as np
import cv2 as cv
import sys import sys
...@@ -62,8 +63,8 @@ def shift_dft(src, dst=None): ...@@ -62,8 +63,8 @@ def shift_dft(src, dst=None):
return dst return dst
if __name__ == "__main__":
def main():
if len(sys.argv) > 1: if len(sys.argv) > 1:
fname = sys.argv[1] fname = sys.argv[1]
else: else:
...@@ -110,4 +111,10 @@ if __name__ == "__main__": ...@@ -110,4 +111,10 @@ if __name__ == "__main__":
cv.imshow("magnitude", log_spectrum) cv.imshow("magnitude", log_spectrum)
cv.waitKey(0) cv.waitKey(0)
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()
...@@ -27,12 +27,12 @@ Usage: ...@@ -27,12 +27,12 @@ Usage:
# Python 2/3 compatibility # Python 2/3 compatibility
from __future__ import print_function from __future__ import print_function
import numpy as np
import cv2 as cv
# built-in modules # built-in modules
from multiprocessing.pool import ThreadPool from multiprocessing.pool import ThreadPool
import cv2 as cv
import numpy as np
from numpy.linalg import norm from numpy.linalg import norm
# local modules # local modules
......
...@@ -23,6 +23,7 @@ if PY3: ...@@ -23,6 +23,7 @@ if PY3:
import numpy as np import numpy as np
import cv2 as cv import cv2 as cv
from multiprocessing.pool import ThreadPool from multiprocessing.pool import ThreadPool
from digits import * from digits import *
......
...@@ -96,6 +96,10 @@ def main(): ...@@ -96,6 +96,10 @@ def main():
if ch == 27: if ch == 27:
break break
print('Done')
if __name__ == '__main__': if __name__ == '__main__':
print(__doc__)
main() main()
cv.destroyAllWindows() cv.destroyAllWindows()
...@@ -19,13 +19,12 @@ import cv2 as cv ...@@ -19,13 +19,12 @@ import cv2 as cv
from common import make_cmap from common import make_cmap
if __name__ == '__main__': def main():
import sys import sys
try: try:
fn = sys.argv[1] fn = sys.argv[1]
except: except:
fn = 'fruits.jpg' fn = 'fruits.jpg'
print(__doc__)
fn = cv.samples.findFile(fn) fn = cv.samples.findFile(fn)
img = cv.imread(fn, cv.IMREAD_GRAYSCALE) img = cv.imread(fn, cv.IMREAD_GRAYSCALE)
...@@ -69,4 +68,11 @@ if __name__ == '__main__': ...@@ -69,4 +68,11 @@ if __name__ == '__main__':
update() update()
if need_update: if need_update:
update() update()
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()
...@@ -23,9 +23,7 @@ import video ...@@ -23,9 +23,7 @@ import video
import sys import sys
if __name__ == '__main__': def main():
print(__doc__)
try: try:
fn = sys.argv[1] fn = sys.argv[1]
except: except:
...@@ -52,4 +50,11 @@ if __name__ == '__main__': ...@@ -52,4 +50,11 @@ if __name__ == '__main__':
ch = cv.waitKey(5) ch = cv.waitKey(5)
if ch == 27: if ch == 27:
break break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()
...@@ -30,9 +30,8 @@ def draw_rects(img, rects, color): ...@@ -30,9 +30,8 @@ def draw_rects(img, rects, color):
for x1, y1, x2, y2 in rects: for x1, y1, x2, y2 in rects:
cv.rectangle(img, (x1, y1), (x2, y2), color, 2) cv.rectangle(img, (x1, y1), (x2, y2), color, 2)
if __name__ == '__main__': def main():
import sys, getopt import sys, getopt
print(__doc__)
args, video_src = getopt.getopt(sys.argv[1:], '', ['cascade=', 'nested-cascade=']) args, video_src = getopt.getopt(sys.argv[1:], '', ['cascade=', 'nested-cascade='])
try: try:
...@@ -70,4 +69,11 @@ if __name__ == '__main__': ...@@ -70,4 +69,11 @@ if __name__ == '__main__':
if cv.waitKey(5) == 27: if cv.waitKey(5) == 27:
break break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()
...@@ -19,6 +19,7 @@ from __future__ import print_function ...@@ -19,6 +19,7 @@ from __future__ import print_function
import numpy as np import numpy as np
import cv2 as cv import cv2 as cv
from common import anorm, getsize from common import anorm, getsize
FLANN_INDEX_KDTREE = 1 # bug: flann enums are missing FLANN_INDEX_KDTREE = 1 # bug: flann enums are missing
...@@ -137,9 +138,7 @@ def explore_match(win, img1, img2, kp_pairs, status = None, H = None): ...@@ -137,9 +138,7 @@ def explore_match(win, img1, img2, kp_pairs, status = None, H = None):
return vis return vis
if __name__ == '__main__': def main():
print(__doc__)
import sys, getopt import sys, getopt
opts, args = getopt.getopt(sys.argv[1:], '', ['feature=']) opts, args = getopt.getopt(sys.argv[1:], '', ['feature='])
opts = dict(opts) opts = dict(opts)
...@@ -187,4 +186,11 @@ if __name__ == '__main__': ...@@ -187,4 +186,11 @@ if __name__ == '__main__':
match_and_draw('find_obj') match_and_draw('find_obj')
cv.waitKey() cv.waitKey()
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()
...@@ -79,9 +79,7 @@ def update(_=None): ...@@ -79,9 +79,7 @@ def update(_=None):
draw_str(img, (20, 20), cur_func_name) draw_str(img, (20, 20), cur_func_name)
cv.imshow('fit line', img) cv.imshow('fit line', img)
if __name__ == '__main__': def main():
print(__doc__)
cv.namedWindow('fit line') cv.namedWindow('fit line')
cv.createTrackbar('noise', 'fit line', 3, 50, update) cv.createTrackbar('noise', 'fit line', 3, 50, update)
cv.createTrackbar('point n', 'fit line', 100, 500, update) cv.createTrackbar('point n', 'fit line', 100, 500, update)
...@@ -96,3 +94,11 @@ if __name__ == '__main__': ...@@ -96,3 +94,11 @@ if __name__ == '__main__':
cur_func_name = dist_func_names.next() cur_func_name = dist_func_names.next()
if ch == 27: if ch == 27:
break break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()
...@@ -20,61 +20,69 @@ from __future__ import print_function ...@@ -20,61 +20,69 @@ from __future__ import print_function
import numpy as np import numpy as np
import cv2 as cv import cv2 as cv
if __name__ == '__main__': import sys
import sys
try:
fn = sys.argv[1]
except:
fn = 'fruits.jpg'
print(__doc__)
img = cv.imread(cv.samples.findFile(fn)) class App():
if img is None:
print('Failed to load image file:', fn)
sys.exit(1)
h, w = img.shape[:2] def update(self, dummy=None):
mask = np.zeros((h+2, w+2), np.uint8) if self.seed_pt is None:
seed_pt = None cv.imshow('floodfill', self.img)
fixed_range = True
connectivity = 4
def update(dummy=None):
if seed_pt is None:
cv.imshow('floodfill', img)
return return
flooded = img.copy() flooded = self.img.copy()
mask[:] = 0 self.mask[:] = 0
lo = cv.getTrackbarPos('lo', 'floodfill') lo = cv.getTrackbarPos('lo', 'floodfill')
hi = cv.getTrackbarPos('hi', 'floodfill') hi = cv.getTrackbarPos('hi', 'floodfill')
flags = connectivity flags = self.connectivity
if fixed_range: if self.fixed_range:
flags |= cv.FLOODFILL_FIXED_RANGE flags |= cv.FLOODFILL_FIXED_RANGE
cv.floodFill(flooded, mask, seed_pt, (255, 255, 255), (lo,)*3, (hi,)*3, flags) cv.floodFill(flooded, self.mask, self.seed_pt, (255, 255, 255), (lo,)*3, (hi,)*3, flags)
cv.circle(flooded, seed_pt, 2, (0, 0, 255), -1) cv.circle(flooded, self.seed_pt, 2, (0, 0, 255), -1)
cv.imshow('floodfill', flooded) cv.imshow('floodfill', flooded)
def onmouse(event, x, y, flags, param): def onmouse(self, event, x, y, flags, param):
global seed_pt
if flags & cv.EVENT_FLAG_LBUTTON: if flags & cv.EVENT_FLAG_LBUTTON:
seed_pt = x, y self.seed_pt = x, y
update() self.update()
update() def run(self):
cv.setMouseCallback('floodfill', onmouse) try:
cv.createTrackbar('lo', 'floodfill', 20, 255, update) fn = sys.argv[1]
cv.createTrackbar('hi', 'floodfill', 20, 255, update) except:
fn = 'fruits.jpg'
while True:
ch = cv.waitKey() self.img = cv.imread(cv.samples.findFile(fn))
if ch == 27: if self.img is None:
break print('Failed to load image file:', fn)
if ch == ord('f'): sys.exit(1)
fixed_range = not fixed_range
print('using %s range' % ('floating', 'fixed')[fixed_range]) h, w = self.img.shape[:2]
update() self.mask = np.zeros((h+2, w+2), np.uint8)
if ch == ord('c'): self.seed_pt = None
connectivity = 12-connectivity self.fixed_range = True
print('connectivity =', connectivity) self.connectivity = 4
update()
self.update()
cv.setMouseCallback('floodfill', self.onmouse)
cv.createTrackbar('lo', 'floodfill', 20, 255, self.update)
cv.createTrackbar('hi', 'floodfill', 20, 255, self.update)
while True:
ch = cv.waitKey()
if ch == 27:
break
if ch == ord('f'):
self.fixed_range = not self.fixed_range
print('using %s range' % ('floating', 'fixed')[self.fixed_range])
self.update()
if ch == ord('c'):
self.connectivity = 12-self.connectivity
print('connectivity =', self.connectivity)
self.update()
print('Done')
if __name__ == '__main__':
print(__doc__)
App().run()
cv.destroyAllWindows() cv.destroyAllWindows()
...@@ -19,6 +19,7 @@ from __future__ import print_function ...@@ -19,6 +19,7 @@ from __future__ import print_function
import numpy as np import numpy as np
import cv2 as cv import cv2 as cv
from multiprocessing.pool import ThreadPool from multiprocessing.pool import ThreadPool
...@@ -47,11 +48,10 @@ def process_threaded(img, filters, threadn = 8): ...@@ -47,11 +48,10 @@ def process_threaded(img, filters, threadn = 8):
np.maximum(accum, fimg, accum) np.maximum(accum, fimg, accum)
return accum return accum
if __name__ == '__main__': def main():
import sys import sys
from common import Timer from common import Timer
print(__doc__)
try: try:
img_fn = sys.argv[1] img_fn = sys.argv[1]
except: except:
...@@ -73,4 +73,10 @@ if __name__ == '__main__': ...@@ -73,4 +73,10 @@ if __name__ == '__main__':
cv.imshow('img', img) cv.imshow('img', img)
cv.imshow('result', res2) cv.imshow('result', res2)
cv.waitKey() cv.waitKey()
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()
...@@ -9,9 +9,10 @@ if PY3: ...@@ -9,9 +9,10 @@ if PY3:
xrange = range xrange = range
import numpy as np import numpy as np
from numpy import random
import cv2 as cv import cv2 as cv
from numpy import random
def make_gaussians(cluster_n, img_size): def make_gaussians(cluster_n, img_size):
points = [] points = []
ref_distrs = [] ref_distrs = []
...@@ -34,7 +35,7 @@ def draw_gaussain(img, mean, cov, color): ...@@ -34,7 +35,7 @@ def draw_gaussain(img, mean, cov, color):
cv.ellipse(img, (x, y), (s1, s2), ang, 0, 360, color, 1, cv.LINE_AA) cv.ellipse(img, (x, y), (s1, s2), ang, 0, 360, color, 1, cv.LINE_AA)
if __name__ == '__main__': def main():
cluster_n = 5 cluster_n = 5
img_size = 512 img_size = 512
...@@ -66,4 +67,11 @@ if __name__ == '__main__': ...@@ -66,4 +67,11 @@ if __name__ == '__main__':
ch = cv.waitKey(0) ch = cv.waitKey(0)
if ch == 27: if ch == 27:
break break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()
This diff is collapsed.
...@@ -18,8 +18,8 @@ Abid Rahman 3/14/12 debug Gary Bradski ...@@ -18,8 +18,8 @@ Abid Rahman 3/14/12 debug Gary Bradski
# Python 2/3 compatibility # Python 2/3 compatibility
from __future__ import print_function from __future__ import print_function
import cv2 as cv
import numpy as np import numpy as np
import cv2 as cv
bins = np.arange(256).reshape(256,1) bins = np.arange(256).reshape(256,1)
...@@ -53,8 +53,7 @@ def hist_lines(im): ...@@ -53,8 +53,7 @@ def hist_lines(im):
return y return y
if __name__ == '__main__': def main():
import sys import sys
if len(sys.argv)>1: if len(sys.argv)>1:
...@@ -116,4 +115,11 @@ if __name__ == '__main__': ...@@ -116,4 +115,11 @@ if __name__ == '__main__':
print('ESC') print('ESC')
cv.destroyAllWindows() cv.destroyAllWindows()
break break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()
...@@ -11,13 +11,12 @@ Usage: ...@@ -11,13 +11,12 @@ Usage:
# Python 2/3 compatibility # Python 2/3 compatibility
from __future__ import print_function from __future__ import print_function
import cv2 as cv
import numpy as np import numpy as np
import sys import cv2 as cv
if __name__ == '__main__': import sys
print(__doc__)
def main():
try: try:
fn = sys.argv[1] fn = sys.argv[1]
except IndexError: except IndexError:
...@@ -40,3 +39,10 @@ if __name__ == '__main__': ...@@ -40,3 +39,10 @@ if __name__ == '__main__':
cv.imshow("source", src) cv.imshow("source", src)
cv.waitKey(0) cv.waitKey(0)
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()
...@@ -13,12 +13,11 @@ from __future__ import print_function ...@@ -13,12 +13,11 @@ from __future__ import print_function
import cv2 as cv import cv2 as cv
import numpy as np import numpy as np
import sys import sys
import math import math
if __name__ == '__main__': def main():
print(__doc__)
try: try:
fn = sys.argv[1] fn = sys.argv[1]
except IndexError: except IndexError:
...@@ -52,3 +51,10 @@ if __name__ == '__main__': ...@@ -52,3 +51,10 @@ if __name__ == '__main__':
cv.imshow("source", src) cv.imshow("source", src)
cv.waitKey(0) cv.waitKey(0)
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()
...@@ -20,17 +20,16 @@ from __future__ import print_function ...@@ -20,17 +20,16 @@ from __future__ import print_function
import numpy as np import numpy as np
import cv2 as cv import cv2 as cv
from common import Sketcher from common import Sketcher
if __name__ == '__main__': def main():
import sys import sys
try: try:
fn = sys.argv[1] fn = sys.argv[1]
except: except:
fn = 'fruits.jpg' fn = 'fruits.jpg'
print(__doc__)
img = cv.imread(cv.samples.findFile(fn)) img = cv.imread(cv.samples.findFile(fn))
if img is None: if img is None:
print('Failed to load image file:', fn) print('Failed to load image file:', fn)
...@@ -51,4 +50,11 @@ if __name__ == '__main__': ...@@ -51,4 +50,11 @@ if __name__ == '__main__':
img_mark[:] = img img_mark[:] = img
mark[:] = 0 mark[:] = 0
sketch.show() sketch.show()
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()
...@@ -18,12 +18,13 @@ PY3 = sys.version_info[0] == 3 ...@@ -18,12 +18,13 @@ PY3 = sys.version_info[0] == 3
if PY3: if PY3:
long = int long = int
import numpy as np
import cv2 as cv import cv2 as cv
from math import cos, sin, sqrt from math import cos, sin, sqrt
import numpy as np import numpy as np
if __name__ == "__main__": def main():
img_height = 500 img_height = 500
img_width = 500 img_width = 500
kalman = cv.KalmanFilter(2, 1, 0) kalman = cv.KalmanFilter(2, 1, 0)
...@@ -93,4 +94,10 @@ if __name__ == "__main__": ...@@ -93,4 +94,10 @@ if __name__ == "__main__":
if code in [27, ord('q'), ord('Q')]: if code in [27, ord('q'), ord('Q')]:
break break
cv.destroyWindow("Kalman") print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()
...@@ -18,12 +18,10 @@ import cv2 as cv ...@@ -18,12 +18,10 @@ import cv2 as cv
from gaussian_mix import make_gaussians from gaussian_mix import make_gaussians
if __name__ == '__main__': def main():
cluster_n = 5 cluster_n = 5
img_size = 512 img_size = 512
print(__doc__)
# generating bright palette # generating bright palette
colors = np.zeros((1, cluster_n, 3), np.uint8) colors = np.zeros((1, cluster_n, 3), np.uint8)
colors[0,:] = 255 colors[0,:] = 255
...@@ -43,8 +41,15 @@ if __name__ == '__main__': ...@@ -43,8 +41,15 @@ if __name__ == '__main__':
cv.circle(img, (x, y), 1, c, -1) cv.circle(img, (x, y), 1, c, -1)
cv.imshow('gaussian mixture', img) cv.imshow('kmeans', img)
ch = cv.waitKey(0) ch = cv.waitKey(0)
if ch == 27: if ch == 27:
break break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()
...@@ -22,6 +22,7 @@ if PY3: ...@@ -22,6 +22,7 @@ if PY3:
import numpy as np import numpy as np
import cv2 as cv import cv2 as cv
import video import video
from common import nothing, getsize from common import nothing, getsize
...@@ -44,9 +45,8 @@ def merge_lappyr(levels): ...@@ -44,9 +45,8 @@ def merge_lappyr(levels):
return np.uint8(np.clip(img, 0, 255)) return np.uint8(np.clip(img, 0, 255))
if __name__ == '__main__': def main():
import sys import sys
print(__doc__)
try: try:
fn = sys.argv[1] fn = sys.argv[1]
...@@ -72,3 +72,11 @@ if __name__ == '__main__': ...@@ -72,3 +72,11 @@ if __name__ == '__main__':
if cv.waitKey(1) == 27: if cv.waitKey(1) == 27:
break break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()
...@@ -145,12 +145,10 @@ class MLP(LetterStatModel): ...@@ -145,12 +145,10 @@ class MLP(LetterStatModel):
if __name__ == '__main__': def main():
import getopt import getopt
import sys import sys
print(__doc__)
models = [RTrees, KNearest, Boost, SVM, MLP] # NBayes models = [RTrees, KNearest, Boost, SVM, MLP] # NBayes
models = dict( [(cls.__name__.lower(), cls) for cls in models] ) models = dict( [(cls.__name__.lower(), cls) for cls in models] )
...@@ -186,4 +184,11 @@ if __name__ == '__main__': ...@@ -186,4 +184,11 @@ if __name__ == '__main__':
fn = args['--save'] fn = args['--save']
print('saving model to %s ...' % fn) print('saving model to %s ...' % fn)
model.save(fn) model.save(fn)
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()
...@@ -25,6 +25,7 @@ from __future__ import print_function ...@@ -25,6 +25,7 @@ from __future__ import print_function
import numpy as np import numpy as np
import cv2 as cv import cv2 as cv
import video import video
from common import draw_str from common import draw_str
from video import presets from video import presets
...@@ -112,9 +113,11 @@ def main(): ...@@ -112,9 +113,11 @@ def main():
except: except:
video_src = 0 video_src = 0
print(__doc__)
App(video_src).run() App(video_src).run()
cv.destroyAllWindows() print('Done')
if __name__ == '__main__': if __name__ == '__main__':
print(__doc__)
main() main()
cv.destroyAllWindows()
...@@ -23,6 +23,7 @@ from __future__ import print_function ...@@ -23,6 +23,7 @@ from __future__ import print_function
import numpy as np import numpy as np
import cv2 as cv import cv2 as cv
import video import video
from common import anorm2, draw_str from common import anorm2, draw_str
from time import clock from time import clock
...@@ -96,9 +97,11 @@ def main(): ...@@ -96,9 +97,11 @@ def main():
except: except:
video_src = 0 video_src = 0
print(__doc__)
App(video_src).run() App(video_src).run()
cv.destroyAllWindows() print('Done')
if __name__ == '__main__': if __name__ == '__main__':
print(__doc__)
main() main()
cv.destroyAllWindows()
...@@ -13,11 +13,10 @@ Keys: ...@@ -13,11 +13,10 @@ Keys:
# Python 2/3 compatibility # Python 2/3 compatibility
from __future__ import print_function from __future__ import print_function
import numpy as np
import cv2 as cv import cv2 as cv
if __name__ == '__main__': def main():
print(__doc__)
import sys import sys
try: try:
fn = sys.argv[1] fn = sys.argv[1]
...@@ -37,3 +36,10 @@ if __name__ == '__main__': ...@@ -37,3 +36,10 @@ if __name__ == '__main__':
cv.imshow('linearpolar', img3) cv.imshow('linearpolar', img3)
cv.waitKey(0) cv.waitKey(0)
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()
...@@ -21,9 +21,7 @@ import numpy as np ...@@ -21,9 +21,7 @@ import numpy as np
import cv2 as cv import cv2 as cv
if __name__ == '__main__': def main():
print(__doc__)
import sys import sys
from itertools import cycle from itertools import cycle
from common import draw_str from common import draw_str
...@@ -93,4 +91,11 @@ if __name__ == '__main__': ...@@ -93,4 +91,11 @@ if __name__ == '__main__':
else: else:
cur_str_mode = str_modes.next() cur_str_mode = str_modes.next()
update() update()
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()
...@@ -25,59 +25,64 @@ import argparse ...@@ -25,59 +25,64 @@ import argparse
from math import * from math import *
drag_start = None class App():
sel = (0,0,0,0) drag_start = None
sel = (0,0,0,0)
def onmouse(event, x, y, flags, param): def onmouse(self, event, x, y, flags, param):
global drag_start, sel if event == cv.EVENT_LBUTTONDOWN:
if event == cv.EVENT_LBUTTONDOWN: self.drag_start = x, y
drag_start = x, y self.sel = (0,0,0,0)
sel = 0,0,0,0 elif event == cv.EVENT_LBUTTONUP:
elif event == cv.EVENT_LBUTTONUP: if self.sel[2] > self.sel[0] and self.sel[3] > self.sel[1]:
if sel[2] > sel[0] and sel[3] > sel[1]: patch = self.gray[self.sel[1]:self.sel[3], self.sel[0]:self.sel[2]]
patch = gray[sel[1]:sel[3],sel[0]:sel[2]] result = cv.matchTemplate(self.gray, patch, cv.TM_CCOEFF_NORMED)
result = cv.matchTemplate(gray,patch,cv.TM_CCOEFF_NORMED) result = np.abs(result)**3
result = np.abs(result)**3 _val, result = cv.threshold(result, 0.01, 0, cv.THRESH_TOZERO)
_val, result = cv.threshold(result, 0.01, 0, cv.THRESH_TOZERO) result8 = cv.normalize(result, None, 0, 255, cv.NORM_MINMAX, cv.CV_8U)
result8 = cv.normalize(result,None,0,255,cv.NORM_MINMAX,cv.CV_8U) cv.imshow("result", result8)
cv.imshow("result", result8) self.drag_start = None
drag_start = None elif self.drag_start:
elif drag_start: #print flags
#print flags if flags & cv.EVENT_FLAG_LBUTTON:
if flags & cv.EVENT_FLAG_LBUTTON: minpos = min(self.drag_start[0], x), min(self.drag_start[1], y)
minpos = min(drag_start[0], x), min(drag_start[1], y) maxpos = max(self.drag_start[0], x), max(self.drag_start[1], y)
maxpos = max(drag_start[0], x), max(drag_start[1], y) self.sel = (minpos[0], minpos[1], maxpos[0], maxpos[1])
sel = minpos[0], minpos[1], maxpos[0], maxpos[1] img = cv.cvtColor(self.gray, cv.COLOR_GRAY2BGR)
img = cv.cvtColor(gray, cv.COLOR_GRAY2BGR) cv.rectangle(img, (self.sel[0], self.sel[1]), (self.sel[2], self.sel[3]), (0,255,255), 1)
cv.rectangle(img, (sel[0], sel[1]), (sel[2], sel[3]), (0,255,255), 1) cv.imshow("gray", img)
cv.imshow("gray", img) else:
else: print("selection is complete")
print("selection is complete") self.drag_start = None
drag_start = None
if __name__ == '__main__': def run(self):
print(__doc__) parser = argparse.ArgumentParser(description='Demonstrate mouse interaction with images')
parser.add_argument("-i","--input", default='../data/', help="Input directory.")
args = parser.parse_args()
path = args.input
cv.namedWindow("gray",1)
cv.setMouseCallback("gray", self.onmouse)
'''Loop through all the images in the directory'''
for infile in glob.glob( os.path.join(path, '*.*') ):
ext = os.path.splitext(infile)[1][1:] #get the filename extension
if ext == "png" or ext == "jpg" or ext == "bmp" or ext == "tiff" or ext == "pbm":
print(infile)
parser = argparse.ArgumentParser(description='Demonstrate mouse interaction with images') img = cv.imread(infile,1)
parser.add_argument("-i","--input", default='../data/', help="Input directory.") if img is None:
args = parser.parse_args() continue
path = args.input self.sel = (0,0,0,0)
self.drag_start = None
self.gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.imshow("gray", self.gray)
if cv.waitKey() == 27:
break
cv.namedWindow("gray",1) print('Done')
cv.setMouseCallback("gray", onmouse)
'''Loop through all the images in the directory'''
for infile in glob.glob( os.path.join(path, '*.*') ):
ext = os.path.splitext(infile)[1][1:] #get the filename extension
if ext == "png" or ext == "jpg" or ext == "bmp" or ext == "tiff" or ext == "pbm":
print(infile)
img=cv.imread(infile,1)
if img is None: if __name__ == '__main__':
continue print(__doc__)
sel = (0,0,0,0) App().run()
drag_start = None
gray=cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.imshow("gray",gray)
if cv.waitKey() == 27:
break
cv.destroyAllWindows() cv.destroyAllWindows()
...@@ -14,12 +14,16 @@ Keys: ...@@ -14,12 +14,16 @@ Keys:
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np import numpy as np
import cv2 as cv import cv2 as cv
import video import video
import sys import sys
if __name__ == '__main__': def main():
try: try:
video_src = sys.argv[1] video_src = sys.argv[1]
except: except:
...@@ -42,4 +46,11 @@ if __name__ == '__main__': ...@@ -42,4 +46,11 @@ if __name__ == '__main__':
cv.imshow('img', vis) cv.imshow('img', vis)
if cv.waitKey(5) == 27: if cv.waitKey(5) == 27:
break break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()
...@@ -13,11 +13,11 @@ Usage: ...@@ -13,11 +13,11 @@ Usage:
# Python 2/3 compatibility # Python 2/3 compatibility
from __future__ import print_function from __future__ import print_function
import numpy as np
import cv2 as cv import cv2 as cv
if __name__ == '__main__': def main():
import sys import sys
print(__doc__)
try: try:
param = sys.argv[1] param = sys.argv[1]
...@@ -31,3 +31,11 @@ if __name__ == '__main__': ...@@ -31,3 +31,11 @@ if __name__ == '__main__':
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")
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()
...@@ -18,6 +18,7 @@ from __future__ import print_function ...@@ -18,6 +18,7 @@ from __future__ import print_function
import numpy as np import numpy as np
import cv2 as cv import cv2 as cv
import video import video
...@@ -55,9 +56,8 @@ def warp_flow(img, flow): ...@@ -55,9 +56,8 @@ def warp_flow(img, flow):
res = cv.remap(img, flow, None, cv.INTER_LINEAR) res = cv.remap(img, flow, None, cv.INTER_LINEAR)
return res return res
if __name__ == '__main__': def main():
import sys import sys
print(__doc__)
try: try:
fn = sys.argv[1] fn = sys.argv[1]
except IndexError: except IndexError:
...@@ -94,4 +94,11 @@ if __name__ == '__main__': ...@@ -94,4 +94,11 @@ if __name__ == '__main__':
if show_glitch: if show_glitch:
cur_glitch = img.copy() cur_glitch = img.copy()
print('glitch is', ['off', 'on'][show_glitch]) print('glitch is', ['off', 'on'][show_glitch])
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()
...@@ -30,13 +30,11 @@ def draw_detections(img, rects, thickness = 1): ...@@ -30,13 +30,11 @@ def draw_detections(img, rects, thickness = 1):
cv.rectangle(img, (x+pad_w, y+pad_h), (x+w-pad_w, y+h-pad_h), (0, 255, 0), thickness) cv.rectangle(img, (x+pad_w, y+pad_h), (x+w-pad_w, y+h-pad_h), (0, 255, 0), thickness)
if __name__ == '__main__': def main():
import sys import sys
from glob import glob from glob import glob
import itertools as it import itertools as it
print(__doc__)
hog = cv.HOGDescriptor() hog = cv.HOGDescriptor()
hog.setSVMDetector( cv.HOGDescriptor_getDefaultPeopleDetector() ) hog.setSVMDetector( cv.HOGDescriptor_getDefaultPeopleDetector() )
...@@ -68,4 +66,11 @@ if __name__ == '__main__': ...@@ -68,4 +66,11 @@ if __name__ == '__main__':
ch = cv.waitKey() ch = cv.waitKey()
if ch == 27: if ch == 27:
break break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()
...@@ -7,6 +7,7 @@ Loads several images sequentially and tries to find squares in each image. ...@@ -7,6 +7,7 @@ Loads several images sequentially and tries to find squares in each image.
''' '''
# Python 2/3 compatibility # Python 2/3 compatibility
from __future__ import print_function
import sys import sys
PY3 = sys.version_info[0] == 3 PY3 = sys.version_info[0] == 3
...@@ -42,7 +43,7 @@ def find_squares(img): ...@@ -42,7 +43,7 @@ def find_squares(img):
squares.append(cnt) squares.append(cnt)
return squares return squares
if __name__ == '__main__': def main():
from glob import glob from glob import glob
for fn in glob('../data/pic*.png'): for fn in glob('../data/pic*.png'):
img = cv.imread(fn) img = cv.imread(fn)
...@@ -52,4 +53,11 @@ if __name__ == '__main__': ...@@ -52,4 +53,11 @@ if __name__ == '__main__':
ch = cv.waitKey() ch = cv.waitKey()
if ch == 27: if ch == 27:
break break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()
...@@ -33,7 +33,7 @@ def write_ply(fn, verts, colors): ...@@ -33,7 +33,7 @@ def write_ply(fn, verts, colors):
np.savetxt(f, verts, fmt='%f %f %f %d %d %d ') np.savetxt(f, verts, fmt='%f %f %f %d %d %d ')
if __name__ == '__main__': def main():
print('loading images...') print('loading images...')
imgL = cv.pyrDown(cv.imread(cv.samples.findFile('aloeL.jpg'))) # downscale images for faster processing imgL = cv.pyrDown(cv.imread(cv.samples.findFile('aloeL.jpg'))) # downscale images for faster processing
imgR = cv.pyrDown(cv.imread(cv.samples.findFile('aloeR.jpg'))) imgR = cv.pyrDown(cv.imread(cv.samples.findFile('aloeR.jpg')))
...@@ -75,4 +75,11 @@ if __name__ == '__main__': ...@@ -75,4 +75,11 @@ if __name__ == '__main__':
cv.imshow('left', imgL) cv.imshow('left', imgL)
cv.imshow('disparity', (disp-min_disp)/num_disp) cv.imshow('disparity', (disp-min_disp)/num_disp)
cv.waitKey() cv.waitKey()
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()
...@@ -16,7 +16,7 @@ from __future__ import print_function ...@@ -16,7 +16,7 @@ from __future__ import print_function
import numpy as np import numpy as np
import cv2 as cv import cv2 as cv
if __name__ == '__main__': def main():
import sys import sys
try: try:
fn = sys.argv[1] fn = sys.argv[1]
...@@ -45,3 +45,11 @@ if __name__ == '__main__': ...@@ -45,3 +45,11 @@ if __name__ == '__main__':
cv.imshow('input', img) cv.imshow('input', img)
cv.imshow('flow', vis) cv.imshow('flow', vis)
cv.waitKey() cv.waitKey()
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()
...@@ -5,9 +5,10 @@ ...@@ -5,9 +5,10 @@
from __future__ import print_function from __future__ import print_function
import numpy as np import numpy as np
import cv2 as cv
from numpy import pi, sin, cos from numpy import pi, sin, cos
import cv2 as cv
defaultSize = 512 defaultSize = 512
...@@ -86,7 +87,7 @@ class TestSceneRender(): ...@@ -86,7 +87,7 @@ class TestSceneRender():
else: else:
self.currentRect = self.initialRect + np.int( 30*cos(self.time*self.speed) + 50*sin(self.time*self.speed)) self.currentRect = self.initialRect + np.int( 30*cos(self.time*self.speed) + 50*sin(self.time*self.speed))
if self.deformation: if self.deformation:
self.currentRect[1:3] += self.h/20*cos(self.time) self.currentRect[1:3] += int(self.h/20*cos(self.time))
cv.fillConvexPoly(img, self.currentRect, (0, 0, 255)) cv.fillConvexPoly(img, self.currentRect, (0, 0, 255))
self.time += self.timeStep self.time += self.timeStep
...@@ -96,8 +97,7 @@ class TestSceneRender(): ...@@ -96,8 +97,7 @@ class TestSceneRender():
self.time = 0.0 self.time = 0.0
if __name__ == '__main__': def main():
backGr = cv.imread(cv.samples.findFile('graf1.png')) backGr = cv.imread(cv.samples.findFile('graf1.png'))
fgr = cv.imread(cv.samples.findFile('box.png')) fgr = cv.imread(cv.samples.findFile('box.png'))
...@@ -111,6 +111,11 @@ if __name__ == '__main__': ...@@ -111,6 +111,11 @@ if __name__ == '__main__':
ch = cv.waitKey(3) ch = cv.waitKey(3)
if ch == 27: if ch == 27:
break break
#import os
#print (os.environ['PYTHONPATH']) print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()
...@@ -27,7 +27,7 @@ USAGE: turing.py [-o <output.avi>] ...@@ -27,7 +27,7 @@ USAGE: turing.py [-o <output.avi>]
Press ESC to stop. Press ESC to stop.
''' '''
if __name__ == '__main__': def main():
print(help_message) print(help_message)
w, h = 512, 512 w, h = 512, 512
...@@ -71,4 +71,11 @@ if __name__ == '__main__': ...@@ -71,4 +71,11 @@ if __name__ == '__main__':
cv.imshow('a', vis) cv.imshow('a', vis)
if cv.waitKey(5) == 27: if cv.waitKey(5) == 27:
break break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()
...@@ -32,13 +32,13 @@ Keys: ...@@ -32,13 +32,13 @@ Keys:
# Python 2/3 compatibility # Python 2/3 compatibility
from __future__ import print_function from __future__ import print_function
import numpy as np
import cv2 as cv
import re import re
import numpy as np
from numpy import pi, sin, cos from numpy import pi, sin, cos
import cv2 as cv
# built-in modules # built-in modules
from time import clock from time import clock
......
...@@ -36,11 +36,9 @@ class DummyTask: ...@@ -36,11 +36,9 @@ class DummyTask:
def get(self): def get(self):
return self.data return self.data
if __name__ == '__main__': def main():
import sys import sys
print(__doc__)
try: try:
fn = sys.argv[1] fn = sys.argv[1]
except: except:
...@@ -86,4 +84,11 @@ if __name__ == '__main__': ...@@ -86,4 +84,11 @@ if __name__ == '__main__':
threaded_mode = not threaded_mode threaded_mode = not threaded_mode
if ch == 27: if ch == 27:
break break
cv.destroyAllWindows()
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()
...@@ -17,51 +17,62 @@ Keys: ...@@ -17,51 +17,62 @@ Keys:
# Python 2/3 compatibility # Python 2/3 compatibility
from __future__ import print_function from __future__ import print_function
import numpy as np
import cv2 as cv import cv2 as cv
def decode_fourcc(v): def main():
v = int(v)
return "".join([chr((v >> 8 * i) & 0xFF) for i in range(4)])
font = cv.FONT_HERSHEY_SIMPLEX def decode_fourcc(v):
color = (0, 255, 0) v = int(v)
return "".join([chr((v >> 8 * i) & 0xFF) for i in range(4)])
cap = cv.VideoCapture(0) font = cv.FONT_HERSHEY_SIMPLEX
cap.set(cv.CAP_PROP_AUTOFOCUS, False) # Known bug: https://github.com/opencv/opencv/pull/5474 color = (0, 255, 0)
cv.namedWindow("Video") cap = cv.VideoCapture(0)
cap.set(cv.CAP_PROP_AUTOFOCUS, False) # Known bug: https://github.com/opencv/opencv/pull/5474
convert_rgb = True cv.namedWindow("Video")
fps = int(cap.get(cv.CAP_PROP_FPS))
focus = int(min(cap.get(cv.CAP_PROP_FOCUS) * 100, 2**31-1)) # ceil focus to C_LONG as Python3 int can go to +inf
cv.createTrackbar("FPS", "Video", fps, 30, lambda v: cap.set(cv.CAP_PROP_FPS, v)) convert_rgb = True
cv.createTrackbar("Focus", "Video", focus, 100, lambda v: cap.set(cv.CAP_PROP_FOCUS, v / 100)) fps = int(cap.get(cv.CAP_PROP_FPS))
focus = int(min(cap.get(cv.CAP_PROP_FOCUS) * 100, 2**31-1)) # ceil focus to C_LONG as Python3 int can go to +inf
while True: cv.createTrackbar("FPS", "Video", fps, 30, lambda v: cap.set(cv.CAP_PROP_FPS, v))
status, img = cap.read() cv.createTrackbar("Focus", "Video", focus, 100, lambda v: cap.set(cv.CAP_PROP_FOCUS, v / 100))
fourcc = decode_fourcc(cap.get(cv.CAP_PROP_FOURCC)) while True:
status, img = cap.read()
fps = cap.get(cv.CAP_PROP_FPS) fourcc = decode_fourcc(cap.get(cv.CAP_PROP_FOURCC))
if not bool(cap.get(cv.CAP_PROP_CONVERT_RGB)): fps = cap.get(cv.CAP_PROP_FPS)
if fourcc == "MJPG":
img = cv.imdecode(img, cv.IMREAD_GRAYSCALE) if not bool(cap.get(cv.CAP_PROP_CONVERT_RGB)):
elif fourcc == "YUYV": if fourcc == "MJPG":
img = cv.cvtColor(img, cv.COLOR_YUV2GRAY_YUYV) img = cv.imdecode(img, cv.IMREAD_GRAYSCALE)
else: elif fourcc == "YUYV":
print("unsupported format") img = cv.cvtColor(img, cv.COLOR_YUV2GRAY_YUYV)
else:
print("unsupported format")
break
cv.putText(img, "Mode: {}".format(fourcc), (15, 40), font, 1.0, color)
cv.putText(img, "FPS: {}".format(fps), (15, 80), font, 1.0, color)
cv.imshow("Video", img)
k = cv.waitKey(1)
if k == 27:
break break
elif k == ord('g'):
convert_rgb = not convert_rgb
cap.set(cv.CAP_PROP_CONVERT_RGB, convert_rgb)
cv.putText(img, "Mode: {}".format(fourcc), (15, 40), font, 1.0, color) print('Done')
cv.putText(img, "FPS: {}".format(fps), (15, 80), font, 1.0, color)
cv.imshow("Video", img)
k = cv.waitKey(1)
if k == 27: if __name__ == '__main__':
break print(__doc__)
elif k == ord('g'): main()
convert_rgb = not convert_rgb cv.destroyAllWindows()
cap.set(cv.CAP_PROP_CONVERT_RGB, convert_rgb)
...@@ -76,10 +76,10 @@ class App: ...@@ -76,10 +76,10 @@ class App:
if __name__ == '__main__': if __name__ == '__main__':
print(__doc__)
import sys import sys
try: try:
fn = sys.argv[1] fn = sys.argv[1]
except: except:
fn = 'fruits.jpg' fn = 'fruits.jpg'
print(__doc__)
App(cv.samples.findFile(fn)).run() App(cv.samples.findFile(fn)).run()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment