vendor: OpenCV 5.0.0 snapshot at 755e50675d97db9b7d449d8bd6b09888646f6c6e
This commit is contained in:
Executable
+224
@@ -0,0 +1,224 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
'''
|
||||
This module contains some common routines used by other samples.
|
||||
'''
|
||||
|
||||
from functools import reduce
|
||||
import numpy as np
|
||||
import cv2 as cv
|
||||
|
||||
# built-in modules
|
||||
import os
|
||||
import itertools as it
|
||||
from contextlib import contextmanager
|
||||
|
||||
image_extensions = ['.bmp', '.jpg', '.jpeg', '.png', '.tif', '.tiff', '.pbm', '.pgm', '.ppm']
|
||||
|
||||
class Bunch(object):
|
||||
def __init__(self, **kw):
|
||||
self.__dict__.update(kw)
|
||||
def __str__(self):
|
||||
return str(self.__dict__)
|
||||
|
||||
def splitfn(fn):
|
||||
path, fn = os.path.split(fn)
|
||||
name, ext = os.path.splitext(fn)
|
||||
return path, name, ext
|
||||
|
||||
def anorm2(a):
|
||||
return (a*a).sum(-1)
|
||||
def anorm(a):
|
||||
return np.sqrt( anorm2(a) )
|
||||
|
||||
def homotrans(H, x, y):
|
||||
xs = H[0, 0]*x + H[0, 1]*y + H[0, 2]
|
||||
ys = H[1, 0]*x + H[1, 1]*y + H[1, 2]
|
||||
s = H[2, 0]*x + H[2, 1]*y + H[2, 2]
|
||||
return xs/s, ys/s
|
||||
|
||||
def to_rect(a):
|
||||
a = np.ravel(a)
|
||||
if len(a) == 2:
|
||||
a = (0, 0, a[0], a[1])
|
||||
return np.array(a, np.float64).reshape(2, 2)
|
||||
|
||||
def rect2rect_mtx(src, dst):
|
||||
src, dst = to_rect(src), to_rect(dst)
|
||||
cx, cy = (dst[1] - dst[0]) / (src[1] - src[0])
|
||||
tx, ty = dst[0] - src[0] * (cx, cy)
|
||||
M = np.float64([[ cx, 0, tx],
|
||||
[ 0, cy, ty],
|
||||
[ 0, 0, 1]])
|
||||
return M
|
||||
|
||||
|
||||
def lookat(eye, target, up = (0, 0, 1)):
|
||||
fwd = np.asarray(target, np.float64) - eye
|
||||
fwd /= anorm(fwd)
|
||||
right = np.cross(fwd, up)
|
||||
right /= anorm(right)
|
||||
down = np.cross(fwd, right)
|
||||
R = np.float64([right, down, fwd])
|
||||
tvec = -np.dot(R, eye)
|
||||
return R, tvec
|
||||
|
||||
def mtx2rvec(R):
|
||||
w, u, vt = cv.SVDecomp(R - np.eye(3))
|
||||
p = vt[0] + u[:,0]*w[0] # same as np.dot(R, vt[0])
|
||||
c = np.dot(vt[0], p)
|
||||
s = np.dot(vt[1], p)
|
||||
axis = np.cross(vt[0], vt[1])
|
||||
return axis * np.arctan2(s, c)
|
||||
|
||||
def draw_str(dst, target, s):
|
||||
x, y = target
|
||||
cv.putText(dst, s, (x+1, y+1), cv.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 0), thickness = 2, lineType=cv.LINE_AA)
|
||||
cv.putText(dst, s, (x, y), cv.FONT_HERSHEY_PLAIN, 1.0, (255, 255, 255), lineType=cv.LINE_AA)
|
||||
|
||||
class Sketcher:
|
||||
def __init__(self, windowname, dests, colors_func):
|
||||
self.prev_pt = None
|
||||
self.windowname = windowname
|
||||
self.dests = dests
|
||||
self.colors_func = colors_func
|
||||
self.dirty = False
|
||||
self.show()
|
||||
cv.setMouseCallback(self.windowname, self.on_mouse)
|
||||
|
||||
def show(self):
|
||||
cv.imshow(self.windowname, self.dests[0])
|
||||
|
||||
def on_mouse(self, event, x, y, flags, param):
|
||||
pt = (x, y)
|
||||
if event == cv.EVENT_LBUTTONDOWN:
|
||||
self.prev_pt = pt
|
||||
elif event == cv.EVENT_LBUTTONUP:
|
||||
self.prev_pt = None
|
||||
|
||||
if self.prev_pt and flags & cv.EVENT_FLAG_LBUTTON:
|
||||
for dst, color in zip(self.dests, self.colors_func()):
|
||||
cv.line(dst, self.prev_pt, pt, color, 5)
|
||||
self.dirty = True
|
||||
self.prev_pt = pt
|
||||
self.show()
|
||||
|
||||
|
||||
# palette data from matplotlib/_cm.py
|
||||
_jet_data = {'red': ((0., 0, 0), (0.35, 0, 0), (0.66, 1, 1), (0.89,1, 1),
|
||||
(1, 0.5, 0.5)),
|
||||
'green': ((0., 0, 0), (0.125,0, 0), (0.375,1, 1), (0.64,1, 1),
|
||||
(0.91,0,0), (1, 0, 0)),
|
||||
'blue': ((0., 0.5, 0.5), (0.11, 1, 1), (0.34, 1, 1), (0.65,0, 0),
|
||||
(1, 0, 0))}
|
||||
|
||||
cmap_data = { 'jet' : _jet_data }
|
||||
|
||||
def make_cmap(name, n=256):
|
||||
data = cmap_data[name]
|
||||
xs = np.linspace(0.0, 1.0, n)
|
||||
channels = []
|
||||
eps = 1e-6
|
||||
for ch_name in ['blue', 'green', 'red']:
|
||||
ch_data = data[ch_name]
|
||||
xp, yp = [], []
|
||||
for x, y1, y2 in ch_data:
|
||||
xp += [x, x+eps]
|
||||
yp += [y1, y2]
|
||||
ch = np.interp(xs, xp, yp)
|
||||
channels.append(ch)
|
||||
return np.uint8(np.array(channels).T*255)
|
||||
|
||||
def nothing(*arg, **kw):
|
||||
pass
|
||||
|
||||
def clock():
|
||||
return cv.getTickCount() / cv.getTickFrequency()
|
||||
|
||||
@contextmanager
|
||||
def Timer(msg):
|
||||
print(msg, '...',)
|
||||
start = clock()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
print("%.2f ms" % ((clock()-start)*1000))
|
||||
|
||||
class StatValue:
|
||||
def __init__(self, smooth_coef = 0.5):
|
||||
self.value = None
|
||||
self.smooth_coef = smooth_coef
|
||||
def update(self, v):
|
||||
if self.value is None:
|
||||
self.value = v
|
||||
else:
|
||||
c = self.smooth_coef
|
||||
self.value = c * self.value + (1.0-c) * v
|
||||
|
||||
class RectSelector:
|
||||
def __init__(self, win, callback):
|
||||
self.win = win
|
||||
self.callback = callback
|
||||
cv.setMouseCallback(win, self.onmouse)
|
||||
self.drag_start = None
|
||||
self.drag_rect = None
|
||||
def onmouse(self, event, x, y, flags, param):
|
||||
x, y = np.int16([x, y]) # BUG
|
||||
if event == cv.EVENT_LBUTTONDOWN:
|
||||
self.drag_start = (x, y)
|
||||
return
|
||||
if self.drag_start:
|
||||
if flags & cv.EVENT_FLAG_LBUTTON:
|
||||
xo, yo = self.drag_start
|
||||
x0, y0 = np.minimum([xo, yo], [x, y])
|
||||
x1, y1 = np.maximum([xo, yo], [x, y])
|
||||
self.drag_rect = None
|
||||
if x1-x0 > 0 and y1-y0 > 0:
|
||||
self.drag_rect = (x0, y0, x1, y1)
|
||||
else:
|
||||
rect = self.drag_rect
|
||||
self.drag_start = None
|
||||
self.drag_rect = None
|
||||
if rect:
|
||||
self.callback(rect)
|
||||
def draw(self, vis):
|
||||
if not self.drag_rect:
|
||||
return False
|
||||
x0, y0, x1, y1 = self.drag_rect
|
||||
cv.rectangle(vis, (x0, y0), (x1, y1), (0, 255, 0), 2)
|
||||
return True
|
||||
@property
|
||||
def dragging(self):
|
||||
return self.drag_rect is not None
|
||||
|
||||
|
||||
def grouper(n, iterable, fillvalue=None):
|
||||
'''grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx'''
|
||||
args = [iter(iterable)] * n
|
||||
output = it.zip_longest(fillvalue=fillvalue, *args)
|
||||
return output
|
||||
|
||||
def mosaic(w, imgs):
|
||||
'''Make a grid from images.
|
||||
|
||||
w -- number of grid columns
|
||||
imgs -- images (must have same size and format)
|
||||
'''
|
||||
imgs = iter(imgs)
|
||||
img0 = next(imgs)
|
||||
pad = np.zeros_like(img0)
|
||||
imgs = it.chain([img0], imgs)
|
||||
rows = grouper(w, imgs, pad)
|
||||
return np.vstack(list(map(np.hstack, rows)))
|
||||
|
||||
def getsize(img):
|
||||
h, w = img.shape[:2]
|
||||
return w, h
|
||||
|
||||
def mdot(*args):
|
||||
return reduce(np.dot, args)
|
||||
|
||||
def draw_keypoints(vis, keypoints, color = (0, 255, 255)):
|
||||
for kp in keypoints:
|
||||
x, y = kp.pt
|
||||
cv.circle(vis, (int(x), int(y)), 2, color)
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
'''
|
||||
face detection using haar cascades
|
||||
|
||||
USAGE:
|
||||
facedetect.py [--cascade <cascade_fn>] [--nested-cascade <cascade_fn>] [<video_source>]
|
||||
'''
|
||||
|
||||
# Python 2/3 compatibility
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2 as cv
|
||||
|
||||
# local modules
|
||||
from video import create_capture
|
||||
from common import clock, draw_str
|
||||
|
||||
|
||||
def detect(img, cascade):
|
||||
rects = cascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30),
|
||||
flags=cv.CASCADE_SCALE_IMAGE)
|
||||
if len(rects) == 0:
|
||||
return []
|
||||
rects[:,2:] += rects[:,:2]
|
||||
return rects
|
||||
|
||||
def draw_rects(img, rects, color):
|
||||
for x1, y1, x2, y2 in rects:
|
||||
cv.rectangle(img, (x1, y1), (x2, y2), color, 2)
|
||||
|
||||
def main():
|
||||
import sys, getopt
|
||||
|
||||
args, video_src = getopt.getopt(sys.argv[1:], '', ['cascade=', 'nested-cascade='])
|
||||
try:
|
||||
video_src = video_src[0]
|
||||
except:
|
||||
video_src = 0
|
||||
args = dict(args)
|
||||
cascade_fn = args.get('--cascade', "haarcascades/haarcascade_frontalface_alt.xml")
|
||||
nested_fn = args.get('--nested-cascade', "haarcascades/haarcascade_eye.xml")
|
||||
|
||||
cascade = cv.CascadeClassifier(cv.samples.findFile(cascade_fn))
|
||||
nested = cv.CascadeClassifier(cv.samples.findFile(nested_fn))
|
||||
|
||||
cam = create_capture(video_src, fallback='synth:bg={}:noise=0.05'.format(cv.samples.findFile('lena.jpg')))
|
||||
|
||||
while True:
|
||||
_ret, img = cam.read()
|
||||
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
|
||||
gray = cv.equalizeHist(gray)
|
||||
|
||||
t = clock()
|
||||
rects = detect(gray, cascade)
|
||||
vis = img.copy()
|
||||
draw_rects(vis, rects, (0, 255, 0))
|
||||
if not nested.empty():
|
||||
for x1, y1, x2, y2 in rects:
|
||||
roi = gray[y1:y2, x1:x2]
|
||||
vis_roi = vis[y1:y2, x1:x2]
|
||||
subrects = detect(roi.copy(), nested)
|
||||
draw_rects(vis_roi, subrects, (255, 0, 0))
|
||||
dt = clock() - t
|
||||
|
||||
draw_str(vis, (20, 20), 'time: %.1f ms' % (dt*1000))
|
||||
cv.imshow('facedetect', vis)
|
||||
|
||||
if cv.waitKey(5) == 27:
|
||||
break
|
||||
|
||||
print('Done')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print(__doc__)
|
||||
main()
|
||||
cv.destroyAllWindows()
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
'''
|
||||
example to detect upright people in images using HOG features
|
||||
|
||||
Usage:
|
||||
peopledetect.py <image_names>
|
||||
|
||||
Press any key to continue, ESC to stop.
|
||||
'''
|
||||
|
||||
# Python 2/3 compatibility
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2 as cv
|
||||
|
||||
|
||||
def inside(r, q):
|
||||
rx, ry, rw, rh = r
|
||||
qx, qy, qw, qh = q
|
||||
return rx > qx and ry > qy and rx + rw < qx + qw and ry + rh < qy + qh
|
||||
|
||||
|
||||
def draw_detections(img, rects, thickness = 1):
|
||||
for x, y, w, h in rects:
|
||||
# the HOG detector returns slightly larger rectangles than the real objects.
|
||||
# so we slightly shrink the rectangles to get a nicer output.
|
||||
pad_w, pad_h = int(0.15*w), int(0.05*h)
|
||||
cv.rectangle(img, (x+pad_w, y+pad_h), (x+w-pad_w, y+h-pad_h), (0, 255, 0), thickness)
|
||||
|
||||
|
||||
def main():
|
||||
import sys
|
||||
from glob import glob
|
||||
import itertools as it
|
||||
|
||||
hog = cv.HOGDescriptor()
|
||||
hog.setSVMDetector( cv.HOGDescriptor_getDefaultPeopleDetector() )
|
||||
|
||||
default = [cv.samples.findFile('basketball2.png')] if len(sys.argv[1:]) == 0 else []
|
||||
|
||||
for fn in it.chain(*map(glob, default + sys.argv[1:])):
|
||||
print(fn, ' - ',)
|
||||
try:
|
||||
img = cv.imread(fn)
|
||||
if img is None:
|
||||
print('Failed to load image file:', fn)
|
||||
continue
|
||||
except:
|
||||
print('loading error')
|
||||
continue
|
||||
|
||||
found, _w = hog.detectMultiScale(img, winStride=(8,8), padding=(32,32), scale=1.05)
|
||||
found_filtered = []
|
||||
for ri, r in enumerate(found):
|
||||
for qi, q in enumerate(found):
|
||||
if ri != qi and inside(r, q):
|
||||
break
|
||||
else:
|
||||
found_filtered.append(r)
|
||||
draw_detections(img, found)
|
||||
draw_detections(img, found_filtered, 3)
|
||||
print('%d (%d) found' % (len(found_filtered), len(found)))
|
||||
cv.imshow('img', img)
|
||||
ch = cv.waitKey()
|
||||
if ch == 27:
|
||||
break
|
||||
|
||||
print('Done')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print(__doc__)
|
||||
main()
|
||||
cv.destroyAllWindows()
|
||||
@@ -0,0 +1,121 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
|
||||
# Python 2/3 compatibility
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2 as cv
|
||||
|
||||
from numpy import pi, sin, cos
|
||||
|
||||
|
||||
defaultSize = 512
|
||||
|
||||
class TestSceneRender():
|
||||
|
||||
def __init__(self, bgImg = None, fgImg = None,
|
||||
deformation = False, speed = 0.25, **params):
|
||||
self.time = 0.0
|
||||
self.timeStep = 1.0 / 30.0
|
||||
self.foreground = fgImg
|
||||
self.deformation = deformation
|
||||
self.speed = speed
|
||||
|
||||
if bgImg is not None:
|
||||
self.sceneBg = bgImg.copy()
|
||||
else:
|
||||
self.sceneBg = np.zeros((defaultSize, defaultSize,3), np.uint8)
|
||||
|
||||
self.w = self.sceneBg.shape[0]
|
||||
self.h = self.sceneBg.shape[1]
|
||||
|
||||
if fgImg is not None:
|
||||
self.foreground = fgImg.copy()
|
||||
self.center = self.currentCenter = (int(self.w/2 - fgImg.shape[0]/2), int(self.h/2 - fgImg.shape[1]/2))
|
||||
|
||||
self.xAmpl = self.sceneBg.shape[0] - (self.center[0] + fgImg.shape[0])
|
||||
self.yAmpl = self.sceneBg.shape[1] - (self.center[1] + fgImg.shape[1])
|
||||
|
||||
self.initialRect = np.array([ (self.h/2, self.w/2), (self.h/2, self.w/2 + self.w/10),
|
||||
(self.h/2 + self.h/10, self.w/2 + self.w/10), (self.h/2 + self.h/10, self.w/2)]).astype(int)
|
||||
self.currentRect = self.initialRect
|
||||
|
||||
def getXOffset(self, time):
|
||||
return int( self.xAmpl*cos(time*self.speed))
|
||||
|
||||
|
||||
def getYOffset(self, time):
|
||||
return int(self.yAmpl*sin(time*self.speed))
|
||||
|
||||
def setInitialRect(self, rect):
|
||||
self.initialRect = rect
|
||||
|
||||
def getRectInTime(self, time):
|
||||
|
||||
if self.foreground is not None:
|
||||
tmp = np.array(self.center) + np.array((self.getXOffset(time), self.getYOffset(time)))
|
||||
x0, y0 = tmp
|
||||
x1, y1 = tmp + self.foreground.shape[0:2]
|
||||
return np.array([y0, x0, y1, x1])
|
||||
else:
|
||||
x0, y0 = self.initialRect[0] + np.array((self.getXOffset(time), self.getYOffset(time)))
|
||||
x1, y1 = self.initialRect[2] + np.array((self.getXOffset(time), self.getYOffset(time)))
|
||||
return np.array([y0, x0, y1, x1])
|
||||
|
||||
def getCurrentRect(self):
|
||||
|
||||
if self.foreground is not None:
|
||||
|
||||
x0 = self.currentCenter[0]
|
||||
y0 = self.currentCenter[1]
|
||||
x1 = self.currentCenter[0] + self.foreground.shape[0]
|
||||
y1 = self.currentCenter[1] + self.foreground.shape[1]
|
||||
return np.array([y0, x0, y1, x1])
|
||||
else:
|
||||
x0, y0 = self.currentRect[0]
|
||||
x1, y1 = self.currentRect[2]
|
||||
return np.array([x0, y0, x1, y1])
|
||||
|
||||
def getNextFrame(self):
|
||||
img = self.sceneBg.copy()
|
||||
|
||||
if self.foreground is not None:
|
||||
self.currentCenter = (self.center[0] + self.getXOffset(self.time), self.center[1] + self.getYOffset(self.time))
|
||||
img[self.currentCenter[0]:self.currentCenter[0]+self.foreground.shape[0],
|
||||
self.currentCenter[1]:self.currentCenter[1]+self.foreground.shape[1]] = self.foreground
|
||||
else:
|
||||
self.currentRect = self.initialRect + int( 30*cos(self.time*self.speed) + 50*sin(self.time*self.speed))
|
||||
if self.deformation:
|
||||
self.currentRect[1:3] += int(self.h/20*cos(self.time))
|
||||
cv.fillConvexPoly(img, self.currentRect, (0, 0, 255))
|
||||
|
||||
self.time += self.timeStep
|
||||
return img
|
||||
|
||||
def resetTime(self):
|
||||
self.time = 0.0
|
||||
|
||||
|
||||
def main():
|
||||
backGr = cv.imread(cv.samples.findFile('graf1.png'))
|
||||
fgr = cv.imread(cv.samples.findFile('box.png'))
|
||||
|
||||
render = TestSceneRender(backGr, fgr)
|
||||
|
||||
while True:
|
||||
|
||||
img = render.getNextFrame()
|
||||
cv.imshow('img', img)
|
||||
|
||||
ch = cv.waitKey(3)
|
||||
if ch == 27:
|
||||
break
|
||||
|
||||
print('Done')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print(__doc__)
|
||||
main()
|
||||
cv.destroyAllWindows()
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
from __future__ import print_function
|
||||
import cv2 as cv
|
||||
import argparse
|
||||
|
||||
def detectAndDisplay(frame):
|
||||
frame_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
|
||||
frame_gray = cv.equalizeHist(frame_gray)
|
||||
|
||||
#-- Detect faces
|
||||
faces = face_cascade.detectMultiScale(frame_gray)
|
||||
for (x,y,w,h) in faces:
|
||||
center = (x + w//2, y + h//2)
|
||||
frame = cv.ellipse(frame, center, (w//2, h//2), 0, 0, 360, (255, 0, 255), 4)
|
||||
|
||||
faceROI = frame_gray[y:y+h,x:x+w]
|
||||
#-- In each face, detect eyes
|
||||
eyes = eyes_cascade.detectMultiScale(faceROI)
|
||||
for (x2,y2,w2,h2) in eyes:
|
||||
eye_center = (x + x2 + w2//2, y + y2 + h2//2)
|
||||
radius = int(round((w2 + h2)*0.25))
|
||||
frame = cv.circle(frame, eye_center, radius, (255, 0, 0 ), 4)
|
||||
|
||||
cv.imshow('Capture - Face detection', frame)
|
||||
|
||||
parser = argparse.ArgumentParser(description='Code for Cascade Classifier tutorial.')
|
||||
parser.add_argument('--face_cascade', help='Path to face cascade.', default='data/haarcascades/haarcascade_frontalface_alt.xml')
|
||||
parser.add_argument('--eyes_cascade', help='Path to eyes cascade.', default='data/haarcascades/haarcascade_eye_tree_eyeglasses.xml')
|
||||
parser.add_argument('--camera', help='Camera divide number.', type=int, default=0)
|
||||
args = parser.parse_args()
|
||||
|
||||
face_cascade_name = args.face_cascade
|
||||
eyes_cascade_name = args.eyes_cascade
|
||||
|
||||
face_cascade = cv.CascadeClassifier()
|
||||
eyes_cascade = cv.CascadeClassifier()
|
||||
|
||||
#-- 1. Load the cascades
|
||||
if not face_cascade.load(cv.samples.findFile(face_cascade_name)):
|
||||
print('--(!)Error loading face cascade')
|
||||
exit(0)
|
||||
if not eyes_cascade.load(cv.samples.findFile(eyes_cascade_name)):
|
||||
print('--(!)Error loading eyes cascade')
|
||||
exit(0)
|
||||
|
||||
camera_device = args.camera
|
||||
#-- 2. Read the video stream
|
||||
cap = cv.VideoCapture(camera_device)
|
||||
if not cap.isOpened:
|
||||
print('--(!)Error opening video capture')
|
||||
exit(0)
|
||||
|
||||
while True:
|
||||
ret, frame = cap.read()
|
||||
if frame is None:
|
||||
print('--(!) No captured frame -- Break!')
|
||||
break
|
||||
|
||||
detectAndDisplay(frame)
|
||||
|
||||
if cv.waitKey(10) == 27:
|
||||
break
|
||||
Executable
+228
@@ -0,0 +1,228 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
'''
|
||||
Video capture sample.
|
||||
|
||||
Sample shows how VideoCapture class can be used to acquire video
|
||||
frames from a camera of a movie file. Also the sample provides
|
||||
an example of procedural video generation by an object, mimicking
|
||||
the VideoCapture interface (see Chess class).
|
||||
|
||||
'create_capture' is a convenience function for capture creation,
|
||||
falling back to procedural video in case of error.
|
||||
|
||||
Usage:
|
||||
video.py [--shotdir <shot path>] [source0] [source1] ...'
|
||||
|
||||
sourceN is an
|
||||
- integer number for camera capture
|
||||
- name of video file
|
||||
- synth:<params> for procedural video
|
||||
|
||||
Synth examples:
|
||||
synth:bg=lena.jpg:noise=0.1
|
||||
synth:class=chess:bg=lena.jpg:noise=0.1:size=640x480
|
||||
|
||||
Keys:
|
||||
ESC - exit
|
||||
SPACE - save current frame to <shot path> directory
|
||||
|
||||
'''
|
||||
|
||||
# Python 2/3 compatibility
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2 as cv
|
||||
|
||||
import re
|
||||
|
||||
from numpy import pi, sin, cos
|
||||
|
||||
# local modules
|
||||
from tst_scene_render import TestSceneRender
|
||||
import common
|
||||
|
||||
class VideoSynthBase(object):
|
||||
def __init__(self, size=None, noise=0.0, bg = None, **params):
|
||||
self.bg = None
|
||||
self.frame_size = (640, 480)
|
||||
if bg is not None:
|
||||
self.bg = cv.imread(cv.samples.findFile(bg))
|
||||
h, w = self.bg.shape[:2]
|
||||
self.frame_size = (w, h)
|
||||
|
||||
if size is not None:
|
||||
w, h = map(int, size.split('x'))
|
||||
self.frame_size = (w, h)
|
||||
self.bg = cv.resize(self.bg, self.frame_size)
|
||||
|
||||
self.noise = float(noise)
|
||||
|
||||
def render(self, dst):
|
||||
pass
|
||||
|
||||
def read(self, dst=None):
|
||||
w, h = self.frame_size
|
||||
|
||||
if self.bg is None:
|
||||
buf = np.zeros((h, w, 3), np.uint8)
|
||||
else:
|
||||
buf = self.bg.copy()
|
||||
|
||||
self.render(buf)
|
||||
|
||||
if self.noise > 0.0:
|
||||
noise = np.zeros((h, w, 3), np.int8)
|
||||
cv.randn(noise, np.zeros(3), np.ones(3)*255*self.noise)
|
||||
buf = cv.add(buf, noise, dtype=cv.CV_8UC3)
|
||||
return True, buf
|
||||
|
||||
def isOpened(self):
|
||||
return True
|
||||
|
||||
class Book(VideoSynthBase):
|
||||
def __init__(self, **kw):
|
||||
super(Book, self).__init__(**kw)
|
||||
backGr = cv.imread(cv.samples.findFile('graf1.png'))
|
||||
fgr = cv.imread(cv.samples.findFile('box.png'))
|
||||
self.render = TestSceneRender(backGr, fgr, speed = 1)
|
||||
|
||||
def read(self, dst=None):
|
||||
noise = np.zeros(self.render.sceneBg.shape, np.int8)
|
||||
cv.randn(noise, np.zeros(3), np.ones(3)*255*self.noise)
|
||||
|
||||
return True, cv.add(self.render.getNextFrame(), noise, dtype=cv.CV_8UC3)
|
||||
|
||||
class Cube(VideoSynthBase):
|
||||
def __init__(self, **kw):
|
||||
super(Cube, self).__init__(**kw)
|
||||
self.render = TestSceneRender(cv.imread(cv.samples.findFile('pca_test1.jpg')), deformation = True, speed = 1)
|
||||
|
||||
def read(self, dst=None):
|
||||
noise = np.zeros(self.render.sceneBg.shape, np.int8)
|
||||
cv.randn(noise, np.zeros(3), np.ones(3)*255*self.noise)
|
||||
|
||||
return True, cv.add(self.render.getNextFrame(), noise, dtype=cv.CV_8UC3)
|
||||
|
||||
class Chess(VideoSynthBase):
|
||||
def __init__(self, **kw):
|
||||
super(Chess, self).__init__(**kw)
|
||||
|
||||
w, h = self.frame_size
|
||||
|
||||
self.grid_size = sx, sy = 10, 7
|
||||
white_quads = []
|
||||
black_quads = []
|
||||
for i, j in np.ndindex(sy, sx):
|
||||
q = [[j, i, 0], [j+1, i, 0], [j+1, i+1, 0], [j, i+1, 0]]
|
||||
[white_quads, black_quads][(i + j) % 2].append(q)
|
||||
self.white_quads = np.float32(white_quads)
|
||||
self.black_quads = np.float32(black_quads)
|
||||
|
||||
fx = 0.9
|
||||
self.K = np.float64([[fx*w, 0, 0.5*(w-1)],
|
||||
[0, fx*w, 0.5*(h-1)],
|
||||
[0.0,0.0, 1.0]])
|
||||
|
||||
self.dist_coef = np.float64([-0.2, 0.1, 0, 0])
|
||||
self.t = 0
|
||||
|
||||
def draw_quads(self, img, quads, color = (0, 255, 0)):
|
||||
img_quads = cv.projectPoints(quads.reshape(-1, 3), self.rvec, self.tvec, self.K, self.dist_coef) [0]
|
||||
img_quads.shape = quads.shape[:2] + (2,)
|
||||
for q in img_quads:
|
||||
cv.fillConvexPoly(img, np.int32(q*4), color, cv.LINE_AA, shift=2)
|
||||
|
||||
def render(self, dst):
|
||||
t = self.t
|
||||
self.t += 1.0/30.0
|
||||
|
||||
sx, sy = self.grid_size
|
||||
center = np.array([0.5*sx, 0.5*sy, 0.0])
|
||||
phi = pi/3 + sin(t*3)*pi/8
|
||||
c, s = cos(phi), sin(phi)
|
||||
ofs = np.array([sin(1.2*t), cos(1.8*t), 0]) * sx * 0.2
|
||||
eye_pos = center + np.array([cos(t)*c, sin(t)*c, s]) * 15.0 + ofs
|
||||
target_pos = center + ofs
|
||||
|
||||
R, self.tvec = common.lookat(eye_pos, target_pos)
|
||||
self.rvec = common.mtx2rvec(R)
|
||||
|
||||
self.draw_quads(dst, self.white_quads, (245, 245, 245))
|
||||
self.draw_quads(dst, self.black_quads, (10, 10, 10))
|
||||
|
||||
|
||||
classes = dict(chess=Chess, book=Book, cube=Cube)
|
||||
|
||||
presets = dict(
|
||||
empty = 'synth:',
|
||||
lena = 'synth:bg=lena.jpg:noise=0.1',
|
||||
chess = 'synth:class=chess:bg=lena.jpg:noise=0.1:size=640x480',
|
||||
book = 'synth:class=book:bg=graf1.png:noise=0.1:size=640x480',
|
||||
cube = 'synth:class=cube:bg=pca_test1.jpg:noise=0.0:size=640x480'
|
||||
)
|
||||
|
||||
|
||||
def create_capture(source = 0, fallback = presets['chess']):
|
||||
'''source: <int> or '<int>|<filename>|synth [:<param_name>=<value> [:...]]'
|
||||
'''
|
||||
source = str(source).strip()
|
||||
|
||||
# Win32: handle drive letter ('c:', ...)
|
||||
source = re.sub(r'(^|=)([a-zA-Z]):([/\\a-zA-Z0-9])', r'\1?disk\2?\3', source)
|
||||
chunks = source.split(':')
|
||||
chunks = [re.sub(r'\?disk([a-zA-Z])\?', r'\1:', s) for s in chunks]
|
||||
|
||||
source = chunks[0]
|
||||
try: source = int(source)
|
||||
except ValueError: pass
|
||||
params = dict( s.split('=') for s in chunks[1:] )
|
||||
|
||||
cap = None
|
||||
if source == 'synth':
|
||||
Class = classes.get(params.get('class', None), VideoSynthBase)
|
||||
try: cap = Class(**params)
|
||||
except: pass
|
||||
else:
|
||||
cap = cv.VideoCapture(source)
|
||||
if 'size' in params:
|
||||
w, h = map(int, params['size'].split('x'))
|
||||
cap.set(cv.CAP_PROP_FRAME_WIDTH, w)
|
||||
cap.set(cv.CAP_PROP_FRAME_HEIGHT, h)
|
||||
if cap is None or not cap.isOpened():
|
||||
print('Warning: unable to open video source: ', source)
|
||||
if fallback is not None:
|
||||
return create_capture(fallback, None)
|
||||
return cap
|
||||
|
||||
if __name__ == '__main__':
|
||||
import sys
|
||||
import getopt
|
||||
|
||||
print(__doc__)
|
||||
|
||||
args, sources = getopt.getopt(sys.argv[1:], '', 'shotdir=')
|
||||
args = dict(args)
|
||||
shotdir = args.get('--shotdir', '.')
|
||||
if len(sources) == 0:
|
||||
sources = [ 0 ]
|
||||
|
||||
caps = list(map(create_capture, sources))
|
||||
shot_idx = 0
|
||||
while True:
|
||||
imgs = []
|
||||
for i, cap in enumerate(caps):
|
||||
ret, img = cap.read()
|
||||
imgs.append(img)
|
||||
cv.imshow('capture %d' % i, img)
|
||||
ch = cv.waitKey(1)
|
||||
if ch == 27:
|
||||
break
|
||||
if ch == ord(' '):
|
||||
for i, img in enumerate(imgs):
|
||||
fn = '%s/shot_%d_%03d.bmp' % (shotdir, i, shot_idx)
|
||||
cv.imwrite(fn, img)
|
||||
print(fn, 'saved')
|
||||
shot_idx += 1
|
||||
cv.destroyAllWindows()
|
||||
Reference in New Issue
Block a user