print()
return keypoints, np.array(descrs)
-if __name__ == '__main__':
- print(__doc__)
+def main():
import sys, getopt
opts, args = getopt.getopt(sys.argv[1:], '', ['feature='])
opts = dict(opts)
match_and_draw('affine find_obj')
cv.waitKey()
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
cv.destroyAllWindows()
# built-in modules
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()
-
+def main():
if len(sys.argv) > 1:
fn = cv.samples.findFile(sys.argv[1])
print('loading %s ...' % fn)
cv.imshow('preview', small)
cv.setMouseCallback('preview', onmouse)
cv.waitKey()
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
cv.destroyAllWindows()
# built-in modules
import os
-if __name__ == '__main__':
+def main():
import sys
import getopt
from glob import glob
print('Undistorted image written to: %s' % outfile)
cv.imwrite(outfile, dst)
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
cv.destroyAllWindows()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
-from mpl_toolkits.mplot3d import Axes3D
-import matplotlib.pyplot as plt
+# Python 2/3 compatibility
+from __future__ import print_function
+
import numpy as np
-from matplotlib import cm
-from numpy import linspace
-import argparse
import cv2 as cv
+from numpy import linspace
+
def inverse_homogeneoux_matrix(M):
R = M[0:3, 0:3]
T = M[0:3, 3]
def draw_camera_boards(ax, camera_matrix, cam_width, cam_height, scale_focal,
extrinsics, board_width, board_height, square_size,
patternCentric):
+ from matplotlib import cm
+
min_values = np.zeros((3,1))
min_values = np.inf
max_values = np.zeros((3,1))
return min_values, max_values
def main():
+ import argparse
+
parser = argparse.ArgumentParser(description='Plot camera calibration extrinsics.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--calibration', type=str, default='left_intrinsics.yml',
camera_matrix = fs.getNode('camera_matrix').mat()
extrinsics = fs.getNode('extrinsic_parameters').mat()
+ import matplotlib.pyplot as plt
+ from mpl_toolkits.mplot3d import Axes3D
+
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")
ax.set_title('Extrinsic Parameters Visualization')
plt.show()
+ print('Done')
+
-if __name__ == "__main__":
+if __name__ == '__main__':
+ print(__doc__)
main()
+ cv.destroyAllWindows()
if __name__ == '__main__':
+ print(__doc__)
import sys
try:
video_src = sys.argv[1]
except:
video_src = 0
- print(__doc__)
App(video_src).run()
return img
-if __name__ == '__main__':
+def main():
import sys
try:
fn = sys.argv[1]
update()
if ch == 27:
break
+
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
cv.destroyAllWindows()
'''
+# Python 2/3 compatibility
+from __future__ import print_function
+
import numpy as np
import cv2 as cv
# local modules
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)
- 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)
- hist_scale = 10
-
- def set_scale(val):
- global hist_scale
- hist_scale = val
- cv.createTrackbar('scale', 'hist', hist_scale, 32, 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)
-
- 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
+ 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*self.hist_scale, 0, 1)
+ vis = hsv_map*h[:,:,np.newaxis] / 255.0
+ cv.imshow('hist', vis)
+
+ ch = cv.waitKey(1)
+ if ch == 27:
+ break
+
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ App().run()
cv.destroyAllWindows()
cv.ellipse( img, (dx+273, dy+100), (20,35), 0, 0, 360, white, -1 )
return img
-if __name__ == '__main__':
- print(__doc__)
-
+def main():
img = make_image()
h, w = img.shape[:2]
cv.createTrackbar( "levels+3", "contours", 3, 7, update )
cv.imshow('image', img)
cv.waitKey()
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
cv.destroyAllWindows()
return kern
-if __name__ == '__main__':
- print(__doc__)
+def main():
import sys, getopt
opts, args = getopt.getopt(sys.argv[1:], '', ['circle', 'angle=', 'd=', 'snr='])
opts = dict(opts)
if ch == ord(' '):
defocus = not defocus
update(None)
+
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
+ cv.destroyAllWindows()
# Python 2/3 compatibility
from __future__ import print_function
-import cv2 as cv
import numpy as np
+import cv2 as cv
+
import sys
return dst
-if __name__ == "__main__":
+def main():
if len(sys.argv) > 1:
fname = sys.argv[1]
else:
cv.imshow("magnitude", log_spectrum)
cv.waitKey(0)
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
cv.destroyAllWindows()
# Python 2/3 compatibility
from __future__ import print_function
+import numpy as np
+import cv2 as cv
+
# built-in modules
from multiprocessing.pool import ThreadPool
-import cv2 as cv
-
-import numpy as np
from numpy.linalg import norm
# local modules
import numpy as np
import cv2 as cv
+
from multiprocessing.pool import ThreadPool
from digits import *
if ch == 27:
break
+ print('Done')
+
+
if __name__ == '__main__':
+ print(__doc__)
main()
cv.destroyAllWindows()
from common import make_cmap
-if __name__ == '__main__':
+def main():
import sys
try:
fn = sys.argv[1]
except:
fn = 'fruits.jpg'
- print(__doc__)
fn = cv.samples.findFile(fn)
img = cv.imread(fn, cv.IMREAD_GRAYSCALE)
update()
if need_update:
update()
+
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
cv.destroyAllWindows()
import sys
-if __name__ == '__main__':
- print(__doc__)
-
+def main():
try:
fn = sys.argv[1]
except:
ch = cv.waitKey(5)
if ch == 27:
break
+
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
cv.destroyAllWindows()
for x1, y1, x2, y2 in rects:
cv.rectangle(img, (x1, y1), (x2, y2), color, 2)
-if __name__ == '__main__':
+def main():
import sys, getopt
- print(__doc__)
args, video_src = getopt.getopt(sys.argv[1:], '', ['cascade=', 'nested-cascade='])
try:
if cv.waitKey(5) == 27:
break
+
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
cv.destroyAllWindows()
import numpy as np
import cv2 as cv
+
from common import anorm, getsize
FLANN_INDEX_KDTREE = 1 # bug: flann enums are missing
return vis
-if __name__ == '__main__':
- print(__doc__)
-
+def main():
import sys, getopt
opts, args = getopt.getopt(sys.argv[1:], '', ['feature='])
opts = dict(opts)
match_and_draw('find_obj')
cv.waitKey()
+
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
cv.destroyAllWindows()
draw_str(img, (20, 20), cur_func_name)
cv.imshow('fit line', img)
-if __name__ == '__main__':
- print(__doc__)
-
+def main():
cv.namedWindow('fit line')
cv.createTrackbar('noise', 'fit line', 3, 50, update)
cv.createTrackbar('point n', 'fit line', 100, 500, update)
cur_func_name = dist_func_names.next()
if ch == 27:
break
+
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
+ cv.destroyAllWindows()
import numpy as np
import cv2 as cv
-if __name__ == '__main__':
- import sys
- try:
- fn = sys.argv[1]
- except:
- fn = 'fruits.jpg'
- print(__doc__)
+import sys
- img = cv.imread(cv.samples.findFile(fn))
- if img is None:
- print('Failed to load image file:', fn)
- sys.exit(1)
+class App():
- h, w = img.shape[:2]
- mask = np.zeros((h+2, w+2), np.uint8)
- seed_pt = None
- fixed_range = True
- connectivity = 4
-
- def update(dummy=None):
- if seed_pt is None:
- cv.imshow('floodfill', img)
+ def update(self, dummy=None):
+ if self.seed_pt is None:
+ cv.imshow('floodfill', self.img)
return
- flooded = img.copy()
- mask[:] = 0
+ flooded = self.img.copy()
+ self.mask[:] = 0
lo = cv.getTrackbarPos('lo', 'floodfill')
hi = cv.getTrackbarPos('hi', 'floodfill')
- flags = connectivity
- if fixed_range:
+ flags = self.connectivity
+ if self.fixed_range:
flags |= cv.FLOODFILL_FIXED_RANGE
- cv.floodFill(flooded, mask, seed_pt, (255, 255, 255), (lo,)*3, (hi,)*3, flags)
- cv.circle(flooded, seed_pt, 2, (0, 0, 255), -1)
+ cv.floodFill(flooded, self.mask, self.seed_pt, (255, 255, 255), (lo,)*3, (hi,)*3, flags)
+ cv.circle(flooded, self.seed_pt, 2, (0, 0, 255), -1)
cv.imshow('floodfill', flooded)
- def onmouse(event, x, y, flags, param):
- global seed_pt
+ def onmouse(self, event, x, y, flags, param):
if flags & cv.EVENT_FLAG_LBUTTON:
- seed_pt = x, y
- update()
-
- update()
- cv.setMouseCallback('floodfill', onmouse)
- cv.createTrackbar('lo', 'floodfill', 20, 255, update)
- cv.createTrackbar('hi', 'floodfill', 20, 255, update)
-
- while True:
- ch = cv.waitKey()
- if ch == 27:
- break
- if ch == ord('f'):
- fixed_range = not fixed_range
- print('using %s range' % ('floating', 'fixed')[fixed_range])
- update()
- if ch == ord('c'):
- connectivity = 12-connectivity
- print('connectivity =', connectivity)
- update()
+ self.seed_pt = x, y
+ self.update()
+
+ def run(self):
+ try:
+ fn = sys.argv[1]
+ except:
+ fn = 'fruits.jpg'
+
+ self.img = cv.imread(cv.samples.findFile(fn))
+ if self.img is None:
+ print('Failed to load image file:', fn)
+ sys.exit(1)
+
+ h, w = self.img.shape[:2]
+ self.mask = np.zeros((h+2, w+2), np.uint8)
+ self.seed_pt = None
+ self.fixed_range = True
+ self.connectivity = 4
+
+ 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()
import numpy as np
import cv2 as cv
+
from multiprocessing.pool import ThreadPool
np.maximum(accum, fimg, accum)
return accum
-if __name__ == '__main__':
+def main():
import sys
from common import Timer
- print(__doc__)
try:
img_fn = sys.argv[1]
except:
cv.imshow('img', img)
cv.imshow('result', res2)
cv.waitKey()
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
cv.destroyAllWindows()
xrange = range
import numpy as np
-from numpy import random
import cv2 as cv
+from numpy import random
+
def make_gaussians(cluster_n, img_size):
points = []
ref_distrs = []
cv.ellipse(img, (x, y), (s1, s2), ang, 0, 360, color, 1, cv.LINE_AA)
-if __name__ == '__main__':
+def main():
cluster_n = 5
img_size = 512
ch = cv.waitKey(0)
if ch == 27:
break
+
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
cv.destroyAllWindows()
import numpy as np
import cv2 as cv
+
import sys
-BLUE = [255,0,0] # rectangle color
-RED = [0,0,255] # PR BG
-GREEN = [0,255,0] # PR FG
-BLACK = [0,0,0] # sure BG
-WHITE = [255,255,255] # sure FG
-
-DRAW_BG = {'color' : BLACK, 'val' : 0}
-DRAW_FG = {'color' : WHITE, 'val' : 1}
-DRAW_PR_FG = {'color' : GREEN, 'val' : 3}
-DRAW_PR_BG = {'color' : RED, 'val' : 2}
-
-# setting up flags
-rect = (0,0,1,1)
-drawing = False # flag for drawing curves
-rectangle = False # flag for drawing rect
-rect_over = False # flag to check if rect drawn
-rect_or_mask = 100 # flag for selecting rect or mask mode
-value = DRAW_FG # drawing initialized to FG
-thickness = 3 # brush thickness
-
-def onmouse(event,x,y,flags,param):
- global img,img2,drawing,value,mask,rectangle,rect,rect_or_mask,ix,iy,rect_over
-
- # Draw Rectangle
- if event == cv.EVENT_RBUTTONDOWN:
- rectangle = True
- ix,iy = x,y
-
- elif event == cv.EVENT_MOUSEMOVE:
- if rectangle == True:
- img = img2.copy()
- cv.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
-
- elif event == cv.EVENT_RBUTTONUP:
- rectangle = False
- rect_over = True
- cv.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")
-
- # draw touchup curves
-
- if event == cv.EVENT_LBUTTONDOWN:
- if rect_over == False:
- print("first draw rectangle \n")
+class App():
+ BLUE = [255,0,0] # rectangle color
+ RED = [0,0,255] # PR BG
+ GREEN = [0,255,0] # PR FG
+ BLACK = [0,0,0] # sure BG
+ WHITE = [255,255,255] # sure FG
+
+ DRAW_BG = {'color' : BLACK, 'val' : 0}
+ DRAW_FG = {'color' : WHITE, 'val' : 1}
+ DRAW_PR_FG = {'color' : GREEN, 'val' : 3}
+ DRAW_PR_BG = {'color' : RED, 'val' : 2}
+
+ # setting up flags
+ rect = (0,0,1,1)
+ drawing = False # flag for drawing curves
+ rectangle = False # flag for drawing rect
+ rect_over = False # flag to check if rect drawn
+ rect_or_mask = 100 # flag for selecting rect or mask mode
+ value = DRAW_FG # drawing initialized to FG
+ thickness = 3 # brush thickness
+
+ def onmouse(self, event, x, y, flags, param):
+ # Draw Rectangle
+ if event == cv.EVENT_RBUTTONDOWN:
+ self.rectangle = True
+ self.ix, self.iy = x,y
+
+ elif event == cv.EVENT_MOUSEMOVE:
+ if self.rectangle == True:
+ self.img = self.img2.copy()
+ cv.rectangle(self.img, (self.ix, self.iy), (x, y), self.BLUE, 2)
+ self.rect = (min(self.ix, x), min(self.iy, y), abs(self.ix - x), abs(self.iy - y))
+ self.rect_or_mask = 0
+
+ elif event == cv.EVENT_RBUTTONUP:
+ self.rectangle = False
+ self.rect_over = True
+ cv.rectangle(self.img, (self.ix, self.iy), (x, y), self.BLUE, 2)
+ self.rect = (min(self.ix, x), min(self.iy, y), abs(self.ix - x), abs(self.iy - y))
+ self.rect_or_mask = 0
+ print(" Now press the key 'n' a few times until no further change \n")
+
+ # draw touchup curves
+
+ if event == cv.EVENT_LBUTTONDOWN:
+ if self.rect_over == False:
+ print("first draw rectangle \n")
+ else:
+ self.drawing = True
+ cv.circle(self.img, (x,y), self.thickness, self.value['color'], -1)
+ cv.circle(self.mask, (x,y), self.thickness, self.value['val'], -1)
+
+ elif event == cv.EVENT_MOUSEMOVE:
+ if self.drawing == True:
+ cv.circle(self.img, (x, y), self.thickness, self.value['color'], -1)
+ cv.circle(self.mask, (x, y), self.thickness, self.value['val'], -1)
+
+ elif event == cv.EVENT_LBUTTONUP:
+ if self.drawing == True:
+ self.drawing = False
+ cv.circle(self.img, (x, y), self.thickness, self.value['color'], -1)
+ cv.circle(self.mask, (x, y), self.thickness, self.value['val'], -1)
+
+ def run(self):
+ # Loading images
+ if len(sys.argv) == 2:
+ filename = sys.argv[1] # for drawing purposes
else:
- drawing = True
- cv.circle(img,(x,y),thickness,value['color'],-1)
- cv.circle(mask,(x,y),thickness,value['val'],-1)
-
- elif event == cv.EVENT_MOUSEMOVE:
- if drawing == True:
- cv.circle(img,(x,y),thickness,value['color'],-1)
- cv.circle(mask,(x,y),thickness,value['val'],-1)
+ print("No input image given, so loading default image, lena.jpg \n")
+ print("Correct Usage: python grabcut.py <filename> \n")
+ filename = 'lena.jpg'
+
+ self.img = cv.imread(cv.samples.findFile(filename))
+ self.img2 = self.img.copy() # a copy of original image
+ self.mask = np.zeros(self.img.shape[:2], dtype = np.uint8) # mask initialized to PR_BG
+ self.output = np.zeros(self.img.shape, np.uint8) # output image to be shown
+
+ # input and output windows
+ cv.namedWindow('output')
+ cv.namedWindow('input')
+ cv.setMouseCallback('input', self.onmouse)
+ cv.moveWindow('input', self.img.shape[1]+10,90)
+
+ print(" Instructions: \n")
+ print(" Draw a rectangle around the object using right mouse button \n")
+
+ while(1):
+
+ cv.imshow('output', self.output)
+ cv.imshow('input', self.img)
+ k = cv.waitKey(1)
+
+ # key bindings
+ if k == 27: # esc to exit
+ break
+ elif k == ord('0'): # BG drawing
+ print(" mark background regions with left mouse button \n")
+ self.value = self.DRAW_BG
+ elif k == ord('1'): # FG drawing
+ print(" mark foreground regions with left mouse button \n")
+ self.value = self.DRAW_FG
+ elif k == ord('2'): # PR_BG drawing
+ self.value = self.DRAW_PR_BG
+ elif k == ord('3'): # PR_FG drawing
+ self.value = self.DRAW_PR_FG
+ elif k == ord('s'): # save image
+ bar = np.zeros((self.img.shape[0], 5, 3), np.uint8)
+ res = np.hstack((self.img2, bar, self.img, bar, self.output))
+ cv.imwrite('grabcut_output.png', res)
+ print(" Result saved as image \n")
+ elif k == ord('r'): # reset everything
+ print("resetting \n")
+ self.rect = (0,0,1,1)
+ self.drawing = False
+ self.rectangle = False
+ self.rect_or_mask = 100
+ self.rect_over = False
+ self.value = self.DRAW_FG
+ self.img = self.img2.copy()
+ self.mask = np.zeros(self.img.shape[:2], dtype = np.uint8) # mask initialized to PR_BG
+ self.output = np.zeros(self.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""")
+ try:
+ if (self.rect_or_mask == 0): # grabcut with rect
+ bgdmodel = np.zeros((1, 65), np.float64)
+ fgdmodel = np.zeros((1, 65), np.float64)
+ cv.grabCut(self.img2, self.mask, self.rect, bgdmodel, fgdmodel, 1, cv.GC_INIT_WITH_RECT)
+ self.rect_or_mask = 1
+ elif self.rect_or_mask == 1: # grabcut with mask
+ bgdmodel = np.zeros((1, 65), np.float64)
+ fgdmodel = np.zeros((1, 65), np.float64)
+ cv.grabCut(self.img2, self.mask, self.rect, bgdmodel, fgdmodel, 1, cv.GC_INIT_WITH_MASK)
+ except:
+ import traceback
+ traceback.print_exc()
+
+ mask2 = np.where((self.mask==1) + (self.mask==3), 255, 0).astype('uint8')
+ self.output = cv.bitwise_and(self.img2, self.img2, mask=mask2)
+
+ print('Done')
- elif event == cv.EVENT_LBUTTONUP:
- if drawing == True:
- drawing = False
- cv.circle(img,(x,y),thickness,value['color'],-1)
- cv.circle(mask,(x,y),thickness,value['val'],-1)
if __name__ == '__main__':
-
- # print documentation
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, lena.jpg \n")
- print("Correct Usage: python grabcut.py <filename> \n")
- filename = 'lena.jpg'
-
- img = cv.imread(cv.samples.findFile(filename))
- img2 = img.copy() # a copy of original image
- 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
-
- # input and output windows
- cv.namedWindow('output')
- cv.namedWindow('input')
- cv.setMouseCallback('input',onmouse)
- cv.moveWindow('input',img.shape[1]+10,90)
-
- print(" Instructions: \n")
- print(" Draw a rectangle around the object using right mouse button \n")
-
- while(1):
-
- cv.imshow('output',output)
- cv.imshow('input',img)
- k = cv.waitKey(1)
-
- # key bindings
- if k == 27: # esc to exit
- break
- elif k == ord('0'): # BG drawing
- 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")
- value = DRAW_FG
- elif k == ord('2'): # PR_BG drawing
- value = DRAW_PR_BG
- elif k == ord('3'): # PR_FG drawing
- value = DRAW_PR_FG
- elif k == ord('s'): # save image
- bar = np.zeros((img.shape[0],5,3),np.uint8)
- res = np.hstack((img2,bar,img,bar,output))
- cv.imwrite('grabcut_output.png',res)
- print(" Result saved as image \n")
- elif k == ord('r'): # reset everything
- print("resetting \n")
- rect = (0,0,1,1)
- drawing = False
- rectangle = False
- rect_or_mask = 100
- rect_over = False
- value = DRAW_FG
- img = img2.copy()
- 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""")
- if (rect_or_mask == 0): # grabcut with rect
- bgdmodel = np.zeros((1,65),np.float64)
- fgdmodel = np.zeros((1,65),np.float64)
- cv.grabCut(img2,mask,rect,bgdmodel,fgdmodel,1,cv.GC_INIT_WITH_RECT)
- rect_or_mask = 1
- elif rect_or_mask == 1: # grabcut with mask
- bgdmodel = np.zeros((1,65),np.float64)
- fgdmodel = np.zeros((1,65),np.float64)
- cv.grabCut(img2,mask,rect,bgdmodel,fgdmodel,1,cv.GC_INIT_WITH_MASK)
-
- mask2 = np.where((mask==1) + (mask==3),255,0).astype('uint8')
- output = cv.bitwise_and(img2,img2,mask=mask2)
-
+ App().run()
cv.destroyAllWindows()
# Python 2/3 compatibility
from __future__ import print_function
-import cv2 as cv
import numpy as np
+import cv2 as cv
bins = np.arange(256).reshape(256,1)
return y
-if __name__ == '__main__':
-
+def main():
import sys
if len(sys.argv)>1:
print('ESC')
cv.destroyAllWindows()
break
+
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
cv.destroyAllWindows()
# Python 2/3 compatibility
from __future__ import print_function
-import cv2 as cv
import numpy as np
-import sys
+import cv2 as cv
-if __name__ == '__main__':
- print(__doc__)
+import sys
+def main():
try:
fn = sys.argv[1]
except IndexError:
cv.imshow("source", src)
cv.waitKey(0)
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
+ cv.destroyAllWindows()
import cv2 as cv
import numpy as np
+
import sys
import math
-if __name__ == '__main__':
- print(__doc__)
-
+def main():
try:
fn = sys.argv[1]
except IndexError:
cv.imshow("source", src)
cv.waitKey(0)
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
+ cv.destroyAllWindows()
import numpy as np
import cv2 as cv
+
from common import Sketcher
-if __name__ == '__main__':
+def main():
import sys
try:
fn = sys.argv[1]
except:
fn = 'fruits.jpg'
- print(__doc__)
-
img = cv.imread(cv.samples.findFile(fn))
if img is None:
print('Failed to load image file:', fn)
img_mark[:] = img
mark[:] = 0
sketch.show()
+
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
cv.destroyAllWindows()
if PY3:
long = int
+import numpy as np
import cv2 as cv
+
from math import cos, sin, sqrt
import numpy as np
-if __name__ == "__main__":
-
+def main():
img_height = 500
img_width = 500
kalman = cv.KalmanFilter(2, 1, 0)
if code in [27, ord('q'), ord('Q')]:
break
- cv.destroyWindow("Kalman")
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
+ cv.destroyAllWindows()
from gaussian_mix import make_gaussians
-if __name__ == '__main__':
+def main():
cluster_n = 5
img_size = 512
- print(__doc__)
-
# generating bright palette
colors = np.zeros((1, cluster_n, 3), np.uint8)
colors[0,:] = 255
cv.circle(img, (x, y), 1, c, -1)
- cv.imshow('gaussian mixture', img)
+ cv.imshow('kmeans', img)
ch = cv.waitKey(0)
if ch == 27:
break
+
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
cv.destroyAllWindows()
import numpy as np
import cv2 as cv
+
import video
from common import nothing, getsize
return np.uint8(np.clip(img, 0, 255))
-if __name__ == '__main__':
+def main():
import sys
- print(__doc__)
try:
fn = sys.argv[1]
if cv.waitKey(1) == 27:
break
+
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
+ cv.destroyAllWindows()
-if __name__ == '__main__':
+def main():
import getopt
import sys
- print(__doc__)
-
models = [RTrees, KNearest, Boost, SVM, MLP] # NBayes
models = dict( [(cls.__name__.lower(), cls) for cls in models] )
fn = args['--save']
print('saving model to %s ...' % fn)
model.save(fn)
+
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
cv.destroyAllWindows()
import numpy as np
import cv2 as cv
+
import video
from common import draw_str
from video import presets
except:
video_src = 0
- print(__doc__)
App(video_src).run()
- cv.destroyAllWindows()
+ print('Done')
+
if __name__ == '__main__':
+ print(__doc__)
main()
+ cv.destroyAllWindows()
import numpy as np
import cv2 as cv
+
import video
from common import anorm2, draw_str
from time import clock
except:
video_src = 0
- print(__doc__)
App(video_src).run()
- cv.destroyAllWindows()
+ print('Done')
+
if __name__ == '__main__':
+ print(__doc__)
main()
+ cv.destroyAllWindows()
# Python 2/3 compatibility
from __future__ import print_function
+import numpy as np
import cv2 as cv
-if __name__ == '__main__':
- print(__doc__)
-
+def main():
import sys
try:
fn = sys.argv[1]
cv.imshow('linearpolar', img3)
cv.waitKey(0)
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
+ cv.destroyAllWindows()
import cv2 as cv
-if __name__ == '__main__':
- print(__doc__)
-
+def main():
import sys
from itertools import cycle
from common import draw_str
else:
cur_str_mode = str_modes.next()
update()
+
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
cv.destroyAllWindows()
from math import *
-drag_start = None
-sel = (0,0,0,0)
+class App():
+ drag_start = None
+ sel = (0,0,0,0)
-def onmouse(event, x, y, flags, param):
- global drag_start, sel
- if event == cv.EVENT_LBUTTONDOWN:
- drag_start = x, y
- sel = 0,0,0,0
- elif event == cv.EVENT_LBUTTONUP:
- if sel[2] > sel[0] and sel[3] > sel[1]:
- patch = gray[sel[1]:sel[3],sel[0]:sel[2]]
- result = cv.matchTemplate(gray,patch,cv.TM_CCOEFF_NORMED)
- result = np.abs(result)**3
- _val, result = cv.threshold(result, 0.01, 0, cv.THRESH_TOZERO)
- result8 = cv.normalize(result,None,0,255,cv.NORM_MINMAX,cv.CV_8U)
- cv.imshow("result", result8)
- drag_start = None
- elif drag_start:
- #print flags
- if flags & cv.EVENT_FLAG_LBUTTON:
- minpos = min(drag_start[0], x), min(drag_start[1], y)
- maxpos = max(drag_start[0], x), max(drag_start[1], y)
- sel = minpos[0], minpos[1], maxpos[0], maxpos[1]
- img = cv.cvtColor(gray, cv.COLOR_GRAY2BGR)
- cv.rectangle(img, (sel[0], sel[1]), (sel[2], sel[3]), (0,255,255), 1)
- cv.imshow("gray", img)
- else:
- print("selection is complete")
- drag_start = None
+ def onmouse(self, event, x, y, flags, param):
+ if event == cv.EVENT_LBUTTONDOWN:
+ self.drag_start = x, y
+ self.sel = (0,0,0,0)
+ elif event == cv.EVENT_LBUTTONUP:
+ if self.sel[2] > self.sel[0] and self.sel[3] > self.sel[1]:
+ patch = self.gray[self.sel[1]:self.sel[3], self.sel[0]:self.sel[2]]
+ result = cv.matchTemplate(self.gray, patch, cv.TM_CCOEFF_NORMED)
+ result = np.abs(result)**3
+ _val, result = cv.threshold(result, 0.01, 0, cv.THRESH_TOZERO)
+ result8 = cv.normalize(result, None, 0, 255, cv.NORM_MINMAX, cv.CV_8U)
+ cv.imshow("result", result8)
+ self.drag_start = None
+ elif self.drag_start:
+ #print flags
+ if flags & cv.EVENT_FLAG_LBUTTON:
+ minpos = min(self.drag_start[0], x), min(self.drag_start[1], y)
+ maxpos = max(self.drag_start[0], x), max(self.drag_start[1], y)
+ self.sel = (minpos[0], minpos[1], maxpos[0], maxpos[1])
+ img = cv.cvtColor(self.gray, cv.COLOR_GRAY2BGR)
+ cv.rectangle(img, (self.sel[0], self.sel[1]), (self.sel[2], self.sel[3]), (0,255,255), 1)
+ cv.imshow("gray", img)
+ else:
+ print("selection is complete")
+ self.drag_start = None
-if __name__ == '__main__':
- print(__doc__)
+ def run(self):
+ 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')
- parser.add_argument("-i","--input", default='../data/', help="Input directory.")
- args = parser.parse_args()
- path = args.input
+ img = cv.imread(infile,1)
+ if img is None:
+ continue
+ 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)
- 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)
+ print('Done')
- img=cv.imread(infile,1)
- if img is None:
- continue
- sel = (0,0,0,0)
- drag_start = None
- gray=cv.cvtColor(img, cv.COLOR_BGR2GRAY)
- cv.imshow("gray",gray)
- if cv.waitKey() == 27:
- break
+
+if __name__ == '__main__':
+ print(__doc__)
+ App().run()
cv.destroyAllWindows()
'''
+# Python 2/3 compatibility
+from __future__ import print_function
+
import numpy as np
import cv2 as cv
+
import video
import sys
-if __name__ == '__main__':
+def main():
try:
video_src = sys.argv[1]
except:
cv.imshow('img', vis)
if cv.waitKey(5) == 27:
break
+
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
cv.destroyAllWindows()
# Python 2/3 compatibility
from __future__ import print_function
+import numpy as np
import cv2 as cv
-if __name__ == '__main__':
+def main():
import sys
- print(__doc__)
try:
param = sys.argv[1]
print("\t--help\n\t\tprint this help")
else:
print("Welcome to OpenCV")
+
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
+ cv.destroyAllWindows()
import numpy as np
import cv2 as cv
+
import video
res = cv.remap(img, flow, None, cv.INTER_LINEAR)
return res
-if __name__ == '__main__':
+def main():
import sys
- print(__doc__)
try:
fn = sys.argv[1]
except IndexError:
if show_glitch:
cur_glitch = img.copy()
print('glitch is', ['off', 'on'][show_glitch])
+
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
cv.destroyAllWindows()
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
from glob import glob
import itertools as it
- print(__doc__)
-
hog = cv.HOGDescriptor()
hog.setSVMDetector( cv.HOGDescriptor_getDefaultPeopleDetector() )
ch = cv.waitKey()
if ch == 27:
break
+
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
cv.destroyAllWindows()
'''
# Python 2/3 compatibility
+from __future__ import print_function
import sys
PY3 = sys.version_info[0] == 3
squares.append(cnt)
return squares
-if __name__ == '__main__':
+def main():
from glob import glob
for fn in glob('../data/pic*.png'):
img = cv.imread(fn)
ch = cv.waitKey()
if ch == 27:
break
+
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
cv.destroyAllWindows()
np.savetxt(f, verts, fmt='%f %f %f %d %d %d ')
-if __name__ == '__main__':
+def main():
print('loading images...')
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')))
cv.imshow('left', imgL)
cv.imshow('disparity', (disp-min_disp)/num_disp)
cv.waitKey()
+
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
cv.destroyAllWindows()
import numpy as np
import cv2 as cv
-if __name__ == '__main__':
+def main():
import sys
try:
fn = sys.argv[1]
cv.imshow('input', img)
cv.imshow('flow', vis)
cv.waitKey()
+
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
+ cv.destroyAllWindows()
from __future__ import print_function
import numpy as np
+import cv2 as cv
+
from numpy import pi, sin, cos
-import cv2 as cv
defaultSize = 512
else:
self.currentRect = self.initialRect + np.int( 30*cos(self.time*self.speed) + 50*sin(self.time*self.speed))
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))
self.time += self.timeStep
self.time = 0.0
-if __name__ == '__main__':
-
+def main():
backGr = cv.imread(cv.samples.findFile('graf1.png'))
fgr = cv.imread(cv.samples.findFile('box.png'))
ch = cv.waitKey(3)
if ch == 27:
break
- #import os
- #print (os.environ['PYTHONPATH'])
+
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
cv.destroyAllWindows()
Press ESC to stop.
'''
-if __name__ == '__main__':
+def main():
print(help_message)
w, h = 512, 512
cv.imshow('a', vis)
if cv.waitKey(5) == 27:
break
+
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
cv.destroyAllWindows()
# Python 2/3 compatibility
from __future__ import print_function
+import numpy as np
+import cv2 as cv
+
import re
-import numpy as np
from numpy import pi, sin, cos
-import cv2 as cv
-
# built-in modules
from time import clock
def get(self):
return self.data
-if __name__ == '__main__':
+def main():
import sys
- print(__doc__)
-
try:
fn = sys.argv[1]
except:
threaded_mode = not threaded_mode
if ch == 27:
break
-cv.destroyAllWindows()
+
+ print('Done')
+
+
+if __name__ == '__main__':
+ print(__doc__)
+ main()
+ cv.destroyAllWindows()
# Python 2/3 compatibility
from __future__ import print_function
+import numpy as np
import cv2 as cv
-def decode_fourcc(v):
- v = int(v)
- return "".join([chr((v >> 8 * i) & 0xFF) for i in range(4)])
+def main():
-font = cv.FONT_HERSHEY_SIMPLEX
-color = (0, 255, 0)
+ def decode_fourcc(v):
+ v = int(v)
+ return "".join([chr((v >> 8 * i) & 0xFF) for i in range(4)])
-cap = cv.VideoCapture(0)
-cap.set(cv.CAP_PROP_AUTOFOCUS, False) # Known bug: https://github.com/opencv/opencv/pull/5474
+ font = cv.FONT_HERSHEY_SIMPLEX
+ 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
-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.namedWindow("Video")
-cv.createTrackbar("FPS", "Video", fps, 30, lambda v: cap.set(cv.CAP_PROP_FPS, v))
-cv.createTrackbar("Focus", "Video", focus, 100, lambda v: cap.set(cv.CAP_PROP_FOCUS, v / 100))
+ convert_rgb = True
+ 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:
- status, img = cap.read()
+ cv.createTrackbar("FPS", "Video", fps, 30, lambda v: cap.set(cv.CAP_PROP_FPS, v))
+ 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)):
- if fourcc == "MJPG":
- img = cv.imdecode(img, cv.IMREAD_GRAYSCALE)
- elif fourcc == "YUYV":
- img = cv.cvtColor(img, cv.COLOR_YUV2GRAY_YUYV)
- else:
- print("unsupported format")
+ fps = cap.get(cv.CAP_PROP_FPS)
+
+ if not bool(cap.get(cv.CAP_PROP_CONVERT_RGB)):
+ if fourcc == "MJPG":
+ img = cv.imdecode(img, cv.IMREAD_GRAYSCALE)
+ elif fourcc == "YUYV":
+ 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
+ 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)
- cv.putText(img, "FPS: {}".format(fps), (15, 80), font, 1.0, color)
- cv.imshow("Video", img)
+ print('Done')
- k = cv.waitKey(1)
- if k == 27:
- break
- elif k == ord('g'):
- convert_rgb = not convert_rgb
- cap.set(cv.CAP_PROP_CONVERT_RGB, convert_rgb)
+if __name__ == '__main__':
+ print(__doc__)
+ main()
+ cv.destroyAllWindows()
if __name__ == '__main__':
+ print(__doc__)
import sys
try:
fn = sys.argv[1]
except:
fn = 'fruits.jpg'
- print(__doc__)
App(cv.samples.findFile(fn)).run()