mirror of
https://github.com/opencv/opencv.git
synced 2026-07-26 05:43:05 +04:00
python: 'cv2.' -> 'cv.' via 'import cv2 as cv'
This commit is contained in:
@@ -8,11 +8,11 @@ Utility for measuring python opencv API coverage by samples.
|
||||
from __future__ import print_function
|
||||
|
||||
from glob import glob
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
import re
|
||||
|
||||
if __name__ == '__main__':
|
||||
cv2_callable = set(['cv2.'+name for name in dir(cv2) if callable( getattr(cv2, name) )])
|
||||
cv2_callable = set(['cv.'+name for name in dir(cv) if callable( getattr(cv, name) )])
|
||||
|
||||
found = set()
|
||||
for fn in glob('*.py'):
|
||||
@@ -26,4 +26,4 @@ if __name__ == '__main__':
|
||||
f.write('\n'.join(sorted(cv2_unused)))
|
||||
|
||||
r = 1.0 * len(cv2_used) / len(cv2_callable)
|
||||
print('\ncv2 api coverage: %d / %d (%.1f%%)' % ( len(cv2_used), len(cv2_callable), r*100 ))
|
||||
print('\ncv api coverage: %d / %d (%.1f%%)' % ( len(cv2_used), len(cv2_callable), r*100 ))
|
||||
|
||||
+13
-13
@@ -23,7 +23,7 @@ USAGE
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
# built-in modules
|
||||
import itertools as it
|
||||
@@ -51,18 +51,18 @@ def affine_skew(tilt, phi, img, mask=None):
|
||||
A = np.float32([[c,-s], [ s, c]])
|
||||
corners = [[0, 0], [w, 0], [w, h], [0, h]]
|
||||
tcorners = np.int32( np.dot(corners, A.T) )
|
||||
x, y, w, h = cv2.boundingRect(tcorners.reshape(1,-1,2))
|
||||
x, y, w, h = cv.boundingRect(tcorners.reshape(1,-1,2))
|
||||
A = np.hstack([A, [[-x], [-y]]])
|
||||
img = cv2.warpAffine(img, A, (w, h), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)
|
||||
img = cv.warpAffine(img, A, (w, h), flags=cv.INTER_LINEAR, borderMode=cv.BORDER_REPLICATE)
|
||||
if tilt != 1.0:
|
||||
s = 0.8*np.sqrt(tilt*tilt-1)
|
||||
img = cv2.GaussianBlur(img, (0, 0), sigmaX=s, sigmaY=0.01)
|
||||
img = cv2.resize(img, (0, 0), fx=1.0/tilt, fy=1.0, interpolation=cv2.INTER_NEAREST)
|
||||
img = cv.GaussianBlur(img, (0, 0), sigmaX=s, sigmaY=0.01)
|
||||
img = cv.resize(img, (0, 0), fx=1.0/tilt, fy=1.0, interpolation=cv.INTER_NEAREST)
|
||||
A[0] /= tilt
|
||||
if phi != 0.0 or tilt != 1.0:
|
||||
h, w = img.shape[:2]
|
||||
mask = cv2.warpAffine(mask, A, (w, h), flags=cv2.INTER_NEAREST)
|
||||
Ai = cv2.invertAffineTransform(A)
|
||||
mask = cv.warpAffine(mask, A, (w, h), flags=cv.INTER_NEAREST)
|
||||
Ai = cv.invertAffineTransform(A)
|
||||
return img, mask, Ai
|
||||
|
||||
|
||||
@@ -119,8 +119,8 @@ if __name__ == '__main__':
|
||||
fn1 = '../data/aero1.jpg'
|
||||
fn2 = '../data/aero3.jpg'
|
||||
|
||||
img1 = cv2.imread(fn1, 0)
|
||||
img2 = cv2.imread(fn2, 0)
|
||||
img1 = cv.imread(fn1, 0)
|
||||
img2 = cv.imread(fn2, 0)
|
||||
detector, matcher = init_feature(feature_name)
|
||||
|
||||
if img1 is None:
|
||||
@@ -137,7 +137,7 @@ if __name__ == '__main__':
|
||||
|
||||
print('using', feature_name)
|
||||
|
||||
pool=ThreadPool(processes = cv2.getNumberOfCPUs())
|
||||
pool=ThreadPool(processes = cv.getNumberOfCPUs())
|
||||
kp1, desc1 = affine_detect(detector, img1, pool=pool)
|
||||
kp2, desc2 = affine_detect(detector, img2, pool=pool)
|
||||
print('img1 - %d features, img2 - %d features' % (len(kp1), len(kp2)))
|
||||
@@ -147,7 +147,7 @@ if __name__ == '__main__':
|
||||
raw_matches = matcher.knnMatch(desc1, trainDescriptors = desc2, k = 2) #2
|
||||
p1, p2, kp_pairs = filter_matches(kp1, kp2, raw_matches)
|
||||
if len(p1) >= 4:
|
||||
H, status = cv2.findHomography(p1, p2, cv2.RANSAC, 5.0)
|
||||
H, status = cv.findHomography(p1, p2, cv.RANSAC, 5.0)
|
||||
print('%d / %d inliers/matched' % (np.sum(status), len(status)))
|
||||
# do not draw outliers (there will be a lot of them)
|
||||
kp_pairs = [kpp for kpp, flag in zip(kp_pairs, status) if flag]
|
||||
@@ -159,5 +159,5 @@ if __name__ == '__main__':
|
||||
|
||||
|
||||
match_and_draw('affine find_obj')
|
||||
cv2.waitKey()
|
||||
cv2.destroyAllWindows()
|
||||
cv.waitKey()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
+10
-10
@@ -21,7 +21,7 @@ if PY3:
|
||||
xrange = range
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
# built-in modules
|
||||
import sys
|
||||
@@ -34,7 +34,7 @@ if __name__ == '__main__':
|
||||
if len(sys.argv) > 1:
|
||||
fn = sys.argv[1]
|
||||
print('loading %s ...' % fn)
|
||||
img = cv2.imread(fn)
|
||||
img = cv.imread(fn)
|
||||
if img is None:
|
||||
print('Failed to load fn:', fn)
|
||||
sys.exit(1)
|
||||
@@ -45,21 +45,21 @@ if __name__ == '__main__':
|
||||
img = np.zeros((sz, sz), np.uint8)
|
||||
track = np.cumsum(np.random.rand(500000, 2)-0.5, axis=0)
|
||||
track = np.int32(track*10 + (sz/2, sz/2))
|
||||
cv2.polylines(img, [track], 0, 255, 1, cv2.LINE_AA)
|
||||
cv.polylines(img, [track], 0, 255, 1, cv.LINE_AA)
|
||||
|
||||
|
||||
small = img
|
||||
for i in xrange(3):
|
||||
small = cv2.pyrDown(small)
|
||||
small = cv.pyrDown(small)
|
||||
|
||||
def onmouse(event, x, y, flags, param):
|
||||
h, _w = img.shape[:2]
|
||||
h1, _w1 = small.shape[:2]
|
||||
x, y = 1.0*x*h/h1, 1.0*y*h/h1
|
||||
zoom = cv2.getRectSubPix(img, (800, 600), (x+0.5, y+0.5))
|
||||
cv2.imshow('zoom', zoom)
|
||||
zoom = cv.getRectSubPix(img, (800, 600), (x+0.5, y+0.5))
|
||||
cv.imshow('zoom', zoom)
|
||||
|
||||
cv2.imshow('preview', small)
|
||||
cv2.setMouseCallback('preview', onmouse)
|
||||
cv2.waitKey()
|
||||
cv2.destroyAllWindows()
|
||||
cv.imshow('preview', small)
|
||||
cv.setMouseCallback('preview', onmouse)
|
||||
cv.waitKey()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
+15
-15
@@ -17,7 +17,7 @@ default values:
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
# local modules
|
||||
from common import splitfn
|
||||
@@ -53,27 +53,27 @@ if __name__ == '__main__':
|
||||
|
||||
obj_points = []
|
||||
img_points = []
|
||||
h, w = cv2.imread(img_names[0], 0).shape[:2] # TODO: use imquery call to retrieve results
|
||||
h, w = cv.imread(img_names[0], 0).shape[:2] # TODO: use imquery call to retrieve results
|
||||
|
||||
def processImage(fn):
|
||||
print('processing %s... ' % fn)
|
||||
img = cv2.imread(fn, 0)
|
||||
img = cv.imread(fn, 0)
|
||||
if img is None:
|
||||
print("Failed to load", fn)
|
||||
return None
|
||||
|
||||
assert w == img.shape[1] and h == img.shape[0], ("size: %d x %d ... " % (img.shape[1], img.shape[0]))
|
||||
found, corners = cv2.findChessboardCorners(img, pattern_size)
|
||||
found, corners = cv.findChessboardCorners(img, pattern_size)
|
||||
if found:
|
||||
term = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_COUNT, 30, 0.1)
|
||||
cv2.cornerSubPix(img, corners, (5, 5), (-1, -1), term)
|
||||
term = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_COUNT, 30, 0.1)
|
||||
cv.cornerSubPix(img, corners, (5, 5), (-1, -1), term)
|
||||
|
||||
if debug_dir:
|
||||
vis = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
|
||||
cv2.drawChessboardCorners(vis, pattern_size, corners, found)
|
||||
vis = cv.cvtColor(img, cv.COLOR_GRAY2BGR)
|
||||
cv.drawChessboardCorners(vis, pattern_size, corners, found)
|
||||
path, name, ext = splitfn(fn)
|
||||
outfile = os.path.join(debug_dir, name + '_chess.png')
|
||||
cv2.imwrite(outfile, vis)
|
||||
cv.imwrite(outfile, vis)
|
||||
|
||||
if not found:
|
||||
print('chessboard not found')
|
||||
@@ -97,7 +97,7 @@ if __name__ == '__main__':
|
||||
obj_points.append(pattern_points)
|
||||
|
||||
# calculate camera distortion
|
||||
rms, camera_matrix, dist_coefs, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, (w, h), None, None)
|
||||
rms, camera_matrix, dist_coefs, rvecs, tvecs = cv.calibrateCamera(obj_points, img_points, (w, h), None, None)
|
||||
|
||||
print("\nRMS:", rms)
|
||||
print("camera matrix:\n", camera_matrix)
|
||||
@@ -110,20 +110,20 @@ if __name__ == '__main__':
|
||||
img_found = os.path.join(debug_dir, name + '_chess.png')
|
||||
outfile = os.path.join(debug_dir, name + '_undistorted.png')
|
||||
|
||||
img = cv2.imread(img_found)
|
||||
img = cv.imread(img_found)
|
||||
if img is None:
|
||||
continue
|
||||
|
||||
h, w = img.shape[:2]
|
||||
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(camera_matrix, dist_coefs, (w, h), 1, (w, h))
|
||||
newcameramtx, roi = cv.getOptimalNewCameraMatrix(camera_matrix, dist_coefs, (w, h), 1, (w, h))
|
||||
|
||||
dst = cv2.undistort(img, camera_matrix, dist_coefs, None, newcameramtx)
|
||||
dst = cv.undistort(img, camera_matrix, dist_coefs, None, newcameramtx)
|
||||
|
||||
# crop and save the image
|
||||
x, y, w, h = roi
|
||||
dst = dst[y:y+h, x:x+w]
|
||||
|
||||
print('Undistorted image written to: %s' % outfile)
|
||||
cv2.imwrite(outfile, dst)
|
||||
cv.imwrite(outfile, dst)
|
||||
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
+20
-20
@@ -31,7 +31,7 @@ if PY3:
|
||||
xrange = range
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
# local module
|
||||
import video
|
||||
@@ -42,8 +42,8 @@ class App(object):
|
||||
def __init__(self, video_src):
|
||||
self.cam = video.create_capture(video_src, presets['cube'])
|
||||
_ret, self.frame = self.cam.read()
|
||||
cv2.namedWindow('camshift')
|
||||
cv2.setMouseCallback('camshift', self.onmouse)
|
||||
cv.namedWindow('camshift')
|
||||
cv.setMouseCallback('camshift', self.onmouse)
|
||||
|
||||
self.selection = None
|
||||
self.drag_start = None
|
||||
@@ -51,7 +51,7 @@ class App(object):
|
||||
self.track_window = None
|
||||
|
||||
def onmouse(self, event, x, y, flags, param):
|
||||
if event == cv2.EVENT_LBUTTONDOWN:
|
||||
if event == cv.EVENT_LBUTTONDOWN:
|
||||
self.drag_start = (x, y)
|
||||
self.track_window = None
|
||||
if self.drag_start:
|
||||
@@ -60,7 +60,7 @@ class App(object):
|
||||
xmax = max(x, self.drag_start[0])
|
||||
ymax = max(y, self.drag_start[1])
|
||||
self.selection = (xmin, ymin, xmax, ymax)
|
||||
if event == cv2.EVENT_LBUTTONUP:
|
||||
if event == cv.EVENT_LBUTTONUP:
|
||||
self.drag_start = None
|
||||
self.track_window = (xmin, ymin, xmax - xmin, ymax - ymin)
|
||||
|
||||
@@ -70,52 +70,52 @@ class App(object):
|
||||
img = np.zeros((256, bin_count*bin_w, 3), np.uint8)
|
||||
for i in xrange(bin_count):
|
||||
h = int(self.hist[i])
|
||||
cv2.rectangle(img, (i*bin_w+2, 255), ((i+1)*bin_w-2, 255-h), (int(180.0*i/bin_count), 255, 255), -1)
|
||||
img = cv2.cvtColor(img, cv2.COLOR_HSV2BGR)
|
||||
cv2.imshow('hist', img)
|
||||
cv.rectangle(img, (i*bin_w+2, 255), ((i+1)*bin_w-2, 255-h), (int(180.0*i/bin_count), 255, 255), -1)
|
||||
img = cv.cvtColor(img, cv.COLOR_HSV2BGR)
|
||||
cv.imshow('hist', img)
|
||||
|
||||
def run(self):
|
||||
while True:
|
||||
_ret, self.frame = self.cam.read()
|
||||
vis = self.frame.copy()
|
||||
hsv = cv2.cvtColor(self.frame, cv2.COLOR_BGR2HSV)
|
||||
mask = cv2.inRange(hsv, np.array((0., 60., 32.)), np.array((180., 255., 255.)))
|
||||
hsv = cv.cvtColor(self.frame, cv.COLOR_BGR2HSV)
|
||||
mask = cv.inRange(hsv, np.array((0., 60., 32.)), np.array((180., 255., 255.)))
|
||||
|
||||
if self.selection:
|
||||
x0, y0, x1, y1 = self.selection
|
||||
hsv_roi = hsv[y0:y1, x0:x1]
|
||||
mask_roi = mask[y0:y1, x0:x1]
|
||||
hist = cv2.calcHist( [hsv_roi], [0], mask_roi, [16], [0, 180] )
|
||||
cv2.normalize(hist, hist, 0, 255, cv2.NORM_MINMAX)
|
||||
hist = cv.calcHist( [hsv_roi], [0], mask_roi, [16], [0, 180] )
|
||||
cv.normalize(hist, hist, 0, 255, cv.NORM_MINMAX)
|
||||
self.hist = hist.reshape(-1)
|
||||
self.show_hist()
|
||||
|
||||
vis_roi = vis[y0:y1, x0:x1]
|
||||
cv2.bitwise_not(vis_roi, vis_roi)
|
||||
cv.bitwise_not(vis_roi, vis_roi)
|
||||
vis[mask == 0] = 0
|
||||
|
||||
if self.track_window and self.track_window[2] > 0 and self.track_window[3] > 0:
|
||||
self.selection = None
|
||||
prob = cv2.calcBackProject([hsv], [0], self.hist, [0, 180], 1)
|
||||
prob = cv.calcBackProject([hsv], [0], self.hist, [0, 180], 1)
|
||||
prob &= mask
|
||||
term_crit = ( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1 )
|
||||
track_box, self.track_window = cv2.CamShift(prob, self.track_window, term_crit)
|
||||
term_crit = ( cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10, 1 )
|
||||
track_box, self.track_window = cv.CamShift(prob, self.track_window, term_crit)
|
||||
|
||||
if self.show_backproj:
|
||||
vis[:] = prob[...,np.newaxis]
|
||||
try:
|
||||
cv2.ellipse(vis, track_box, (0, 0, 255), 2)
|
||||
cv.ellipse(vis, track_box, (0, 0, 255), 2)
|
||||
except:
|
||||
print(track_box)
|
||||
|
||||
cv2.imshow('camshift', vis)
|
||||
cv.imshow('camshift', vis)
|
||||
|
||||
ch = cv2.waitKey(5)
|
||||
ch = cv.waitKey(5)
|
||||
if ch == 27:
|
||||
break
|
||||
if ch == ord('b'):
|
||||
self.show_backproj = not self.show_backproj
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
+20
-20
@@ -18,7 +18,7 @@ if PY3:
|
||||
xrange = range
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
def coherence_filter(img, sigma = 11, str_sigma = 11, blend = 0.5, iter_n = 4):
|
||||
h, w = img.shape[:2]
|
||||
@@ -26,19 +26,19 @@ def coherence_filter(img, sigma = 11, str_sigma = 11, blend = 0.5, iter_n = 4):
|
||||
for i in xrange(iter_n):
|
||||
print(i)
|
||||
|
||||
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||
eigen = cv2.cornerEigenValsAndVecs(gray, str_sigma, 3)
|
||||
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
|
||||
eigen = cv.cornerEigenValsAndVecs(gray, str_sigma, 3)
|
||||
eigen = eigen.reshape(h, w, 3, 2) # [[e1, e2], v1, v2]
|
||||
x, y = eigen[:,:,1,0], eigen[:,:,1,1]
|
||||
|
||||
gxx = cv2.Sobel(gray, cv2.CV_32F, 2, 0, ksize=sigma)
|
||||
gxy = cv2.Sobel(gray, cv2.CV_32F, 1, 1, ksize=sigma)
|
||||
gyy = cv2.Sobel(gray, cv2.CV_32F, 0, 2, ksize=sigma)
|
||||
gxx = cv.Sobel(gray, cv.CV_32F, 2, 0, ksize=sigma)
|
||||
gxy = cv.Sobel(gray, cv.CV_32F, 1, 1, ksize=sigma)
|
||||
gyy = cv.Sobel(gray, cv.CV_32F, 0, 2, ksize=sigma)
|
||||
gvv = x*x*gxx + 2*x*y*gxy + y*y*gyy
|
||||
m = gvv < 0
|
||||
|
||||
ero = cv2.erode(img, None)
|
||||
dil = cv2.dilate(img, None)
|
||||
ero = cv.erode(img, None)
|
||||
dil = cv.dilate(img, None)
|
||||
img1 = ero
|
||||
img1[m] = dil[m]
|
||||
img = np.uint8(img*(1.0 - blend) + img1*blend)
|
||||
@@ -53,33 +53,33 @@ if __name__ == '__main__':
|
||||
except:
|
||||
fn = '../data/baboon.jpg'
|
||||
|
||||
src = cv2.imread(fn)
|
||||
src = cv.imread(fn)
|
||||
|
||||
def nothing(*argv):
|
||||
pass
|
||||
|
||||
def update():
|
||||
sigma = cv2.getTrackbarPos('sigma', 'control')*2+1
|
||||
str_sigma = cv2.getTrackbarPos('str_sigma', 'control')*2+1
|
||||
blend = cv2.getTrackbarPos('blend', 'control') / 10.0
|
||||
sigma = cv.getTrackbarPos('sigma', 'control')*2+1
|
||||
str_sigma = cv.getTrackbarPos('str_sigma', 'control')*2+1
|
||||
blend = cv.getTrackbarPos('blend', 'control') / 10.0
|
||||
print('sigma: %d str_sigma: %d blend_coef: %f' % (sigma, str_sigma, blend))
|
||||
dst = coherence_filter(src, sigma=sigma, str_sigma = str_sigma, blend = blend)
|
||||
cv2.imshow('dst', dst)
|
||||
cv.imshow('dst', dst)
|
||||
|
||||
cv2.namedWindow('control', 0)
|
||||
cv2.createTrackbar('sigma', 'control', 9, 15, nothing)
|
||||
cv2.createTrackbar('blend', 'control', 7, 10, nothing)
|
||||
cv2.createTrackbar('str_sigma', 'control', 9, 15, nothing)
|
||||
cv.namedWindow('control', 0)
|
||||
cv.createTrackbar('sigma', 'control', 9, 15, nothing)
|
||||
cv.createTrackbar('blend', 'control', 7, 10, nothing)
|
||||
cv.createTrackbar('str_sigma', 'control', 9, 15, nothing)
|
||||
|
||||
|
||||
print('Press SPACE to update the image\n')
|
||||
|
||||
cv2.imshow('src', src)
|
||||
cv.imshow('src', src)
|
||||
update()
|
||||
while True:
|
||||
ch = cv2.waitKey()
|
||||
ch = cv.waitKey()
|
||||
if ch == ord(' '):
|
||||
update()
|
||||
if ch == 27:
|
||||
break
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
@@ -9,7 +9,7 @@ Keys:
|
||||
'''
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
# built-in modules
|
||||
import sys
|
||||
@@ -24,16 +24,16 @@ if __name__ == '__main__':
|
||||
hsv_map[:,:,0] = h
|
||||
hsv_map[:,:,1] = s
|
||||
hsv_map[:,:,2] = 255
|
||||
hsv_map = cv2.cvtColor(hsv_map, cv2.COLOR_HSV2BGR)
|
||||
cv2.imshow('hsv_map', hsv_map)
|
||||
hsv_map = cv.cvtColor(hsv_map, cv.COLOR_HSV2BGR)
|
||||
cv.imshow('hsv_map', hsv_map)
|
||||
|
||||
cv2.namedWindow('hist', 0)
|
||||
cv.namedWindow('hist', 0)
|
||||
hist_scale = 10
|
||||
|
||||
def set_scale(val):
|
||||
global hist_scale
|
||||
hist_scale = val
|
||||
cv2.createTrackbar('scale', 'hist', hist_scale, 32, set_scale)
|
||||
cv.createTrackbar('scale', 'hist', hist_scale, 32, set_scale)
|
||||
|
||||
try:
|
||||
fn = sys.argv[1]
|
||||
@@ -43,20 +43,20 @@ if __name__ == '__main__':
|
||||
|
||||
while True:
|
||||
flag, frame = cam.read()
|
||||
cv2.imshow('camera', frame)
|
||||
cv.imshow('camera', frame)
|
||||
|
||||
small = cv2.pyrDown(frame)
|
||||
small = cv.pyrDown(frame)
|
||||
|
||||
hsv = cv2.cvtColor(small, cv2.COLOR_BGR2HSV)
|
||||
hsv = cv.cvtColor(small, cv.COLOR_BGR2HSV)
|
||||
dark = hsv[...,2] < 32
|
||||
hsv[dark] = 0
|
||||
h = cv2.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])
|
||||
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
|
||||
cv2.imshow('hist', vis)
|
||||
cv.imshow('hist', vis)
|
||||
|
||||
ch = cv2.waitKey(1)
|
||||
ch = cv.waitKey(1)
|
||||
if ch == 27:
|
||||
break
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
+16
-16
@@ -13,7 +13,7 @@ if PY3:
|
||||
from functools import reduce
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
# built-in modules
|
||||
import os
|
||||
@@ -71,7 +71,7 @@ def lookat(eye, target, up = (0, 0, 1)):
|
||||
return R, tvec
|
||||
|
||||
def mtx2rvec(R):
|
||||
w, u, vt = cv2.SVDecomp(R - np.eye(3))
|
||||
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)
|
||||
@@ -80,8 +80,8 @@ def mtx2rvec(R):
|
||||
|
||||
def draw_str(dst, target, s):
|
||||
x, y = target
|
||||
cv2.putText(dst, s, (x+1, y+1), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 0), thickness = 2, lineType=cv2.LINE_AA)
|
||||
cv2.putText(dst, s, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.0, (255, 255, 255), lineType=cv2.LINE_AA)
|
||||
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):
|
||||
@@ -91,21 +91,21 @@ class Sketcher:
|
||||
self.colors_func = colors_func
|
||||
self.dirty = False
|
||||
self.show()
|
||||
cv2.setMouseCallback(self.windowname, self.on_mouse)
|
||||
cv.setMouseCallback(self.windowname, self.on_mouse)
|
||||
|
||||
def show(self):
|
||||
cv2.imshow(self.windowname, self.dests[0])
|
||||
cv.imshow(self.windowname, self.dests[0])
|
||||
|
||||
def on_mouse(self, event, x, y, flags, param):
|
||||
pt = (x, y)
|
||||
if event == cv2.EVENT_LBUTTONDOWN:
|
||||
if event == cv.EVENT_LBUTTONDOWN:
|
||||
self.prev_pt = pt
|
||||
elif event == cv2.EVENT_LBUTTONUP:
|
||||
elif event == cv.EVENT_LBUTTONUP:
|
||||
self.prev_pt = None
|
||||
|
||||
if self.prev_pt and flags & cv2.EVENT_FLAG_LBUTTON:
|
||||
if self.prev_pt and flags & cv.EVENT_FLAG_LBUTTON:
|
||||
for dst, color in zip(self.dests, self.colors_func()):
|
||||
cv2.line(dst, self.prev_pt, pt, color, 5)
|
||||
cv.line(dst, self.prev_pt, pt, color, 5)
|
||||
self.dirty = True
|
||||
self.prev_pt = pt
|
||||
self.show()
|
||||
@@ -140,7 +140,7 @@ def nothing(*arg, **kw):
|
||||
pass
|
||||
|
||||
def clock():
|
||||
return cv2.getTickCount() / cv2.getTickFrequency()
|
||||
return cv.getTickCount() / cv.getTickFrequency()
|
||||
|
||||
@contextmanager
|
||||
def Timer(msg):
|
||||
@@ -166,16 +166,16 @@ class RectSelector:
|
||||
def __init__(self, win, callback):
|
||||
self.win = win
|
||||
self.callback = callback
|
||||
cv2.setMouseCallback(win, self.onmouse)
|
||||
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 == cv2.EVENT_LBUTTONDOWN:
|
||||
if event == cv.EVENT_LBUTTONDOWN:
|
||||
self.drag_start = (x, y)
|
||||
return
|
||||
if self.drag_start:
|
||||
if flags & cv2.EVENT_FLAG_LBUTTON:
|
||||
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])
|
||||
@@ -192,7 +192,7 @@ class RectSelector:
|
||||
if not self.drag_rect:
|
||||
return False
|
||||
x0, y0, x1, y1 = self.drag_rect
|
||||
cv2.rectangle(vis, (x0, y0), (x1, y1), (0, 255, 0), 2)
|
||||
cv.rectangle(vis, (x0, y0), (x1, y1), (0, 255, 0), 2)
|
||||
return True
|
||||
@property
|
||||
def dragging(self):
|
||||
@@ -234,4 +234,4 @@ def mdot(*args):
|
||||
def draw_keypoints(vis, keypoints, color = (0, 255, 255)):
|
||||
for kp in keypoints:
|
||||
x, y = kp.pt
|
||||
cv2.circle(vis, (int(x), int(y)), 2, color)
|
||||
cv.circle(vis, (int(x), int(y)), 2, color)
|
||||
|
||||
+22
-22
@@ -18,7 +18,7 @@ if PY3:
|
||||
xrange = range
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
def make_image():
|
||||
img = np.zeros((500, 500), np.uint8)
|
||||
@@ -33,19 +33,19 @@ def make_image():
|
||||
c, s = np.cos(angle), np.sin(angle)
|
||||
x1, y1 = np.int32([dx+100+j*10-80*c, dy+100-90*s])
|
||||
x2, y2 = np.int32([dx+100+j*10-30*c, dy+100-30*s])
|
||||
cv2.line(img, (x1, y1), (x2, y2), white)
|
||||
cv.line(img, (x1, y1), (x2, y2), white)
|
||||
|
||||
cv2.ellipse( img, (dx+150, dy+100), (100,70), 0, 0, 360, white, -1 )
|
||||
cv2.ellipse( img, (dx+115, dy+70), (30,20), 0, 0, 360, black, -1 )
|
||||
cv2.ellipse( img, (dx+185, dy+70), (30,20), 0, 0, 360, black, -1 )
|
||||
cv2.ellipse( img, (dx+115, dy+70), (15,15), 0, 0, 360, white, -1 )
|
||||
cv2.ellipse( img, (dx+185, dy+70), (15,15), 0, 0, 360, white, -1 )
|
||||
cv2.ellipse( img, (dx+115, dy+70), (5,5), 0, 0, 360, black, -1 )
|
||||
cv2.ellipse( img, (dx+185, dy+70), (5,5), 0, 0, 360, black, -1 )
|
||||
cv2.ellipse( img, (dx+150, dy+100), (10,5), 0, 0, 360, black, -1 )
|
||||
cv2.ellipse( img, (dx+150, dy+150), (40,10), 0, 0, 360, black, -1 )
|
||||
cv2.ellipse( img, (dx+27, dy+100), (20,35), 0, 0, 360, white, -1 )
|
||||
cv2.ellipse( img, (dx+273, dy+100), (20,35), 0, 0, 360, white, -1 )
|
||||
cv.ellipse( img, (dx+150, dy+100), (100,70), 0, 0, 360, white, -1 )
|
||||
cv.ellipse( img, (dx+115, dy+70), (30,20), 0, 0, 360, black, -1 )
|
||||
cv.ellipse( img, (dx+185, dy+70), (30,20), 0, 0, 360, black, -1 )
|
||||
cv.ellipse( img, (dx+115, dy+70), (15,15), 0, 0, 360, white, -1 )
|
||||
cv.ellipse( img, (dx+185, dy+70), (15,15), 0, 0, 360, white, -1 )
|
||||
cv.ellipse( img, (dx+115, dy+70), (5,5), 0, 0, 360, black, -1 )
|
||||
cv.ellipse( img, (dx+185, dy+70), (5,5), 0, 0, 360, black, -1 )
|
||||
cv.ellipse( img, (dx+150, dy+100), (10,5), 0, 0, 360, black, -1 )
|
||||
cv.ellipse( img, (dx+150, dy+150), (40,10), 0, 0, 360, black, -1 )
|
||||
cv.ellipse( img, (dx+27, 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
|
||||
|
||||
if __name__ == '__main__':
|
||||
@@ -54,17 +54,17 @@ if __name__ == '__main__':
|
||||
img = make_image()
|
||||
h, w = img.shape[:2]
|
||||
|
||||
_, contours0, hierarchy = cv2.findContours( img.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
|
||||
contours = [cv2.approxPolyDP(cnt, 3, True) for cnt in contours0]
|
||||
_, contours0, hierarchy = cv.findContours( img.copy(), cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
|
||||
contours = [cv.approxPolyDP(cnt, 3, True) for cnt in contours0]
|
||||
|
||||
def update(levels):
|
||||
vis = np.zeros((h, w, 3), np.uint8)
|
||||
levels = levels - 3
|
||||
cv2.drawContours( vis, contours, (-1, 2)[levels <= 0], (128,255,255),
|
||||
3, cv2.LINE_AA, hierarchy, abs(levels) )
|
||||
cv2.imshow('contours', vis)
|
||||
cv.drawContours( vis, contours, (-1, 2)[levels <= 0], (128,255,255),
|
||||
3, cv.LINE_AA, hierarchy, abs(levels) )
|
||||
cv.imshow('contours', vis)
|
||||
update(3)
|
||||
cv2.createTrackbar( "levels+3", "contours", 3, 7, update )
|
||||
cv2.imshow('image', img)
|
||||
cv2.waitKey()
|
||||
cv2.destroyAllWindows()
|
||||
cv.createTrackbar( "levels+3", "contours", 3, 7, update )
|
||||
cv.imshow('image', img)
|
||||
cv.waitKey()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
@@ -34,7 +34,7 @@ Examples:
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
# local module
|
||||
from common import nothing
|
||||
@@ -42,8 +42,8 @@ from common import nothing
|
||||
|
||||
def blur_edge(img, d=31):
|
||||
h, w = img.shape[:2]
|
||||
img_pad = cv2.copyMakeBorder(img, d, d, d, d, cv2.BORDER_WRAP)
|
||||
img_blur = cv2.GaussianBlur(img_pad, (2*d+1, 2*d+1), -1)[d:-d,d:-d]
|
||||
img_pad = cv.copyMakeBorder(img, d, d, d, d, cv.BORDER_WRAP)
|
||||
img_blur = cv.GaussianBlur(img_pad, (2*d+1, 2*d+1), -1)[d:-d,d:-d]
|
||||
y, x = np.indices((h, w))
|
||||
dist = np.dstack([x, w-x-1, y, h-y-1]).min(-1)
|
||||
w = np.minimum(np.float32(dist)/d, 1.0)
|
||||
@@ -55,12 +55,12 @@ def motion_kernel(angle, d, sz=65):
|
||||
A = np.float32([[c, -s, 0], [s, c, 0]])
|
||||
sz2 = sz // 2
|
||||
A[:,2] = (sz2, sz2) - np.dot(A[:,:2], ((d-1)*0.5, 0))
|
||||
kern = cv2.warpAffine(kern, A, (sz, sz), flags=cv2.INTER_CUBIC)
|
||||
kern = cv.warpAffine(kern, A, (sz, sz), flags=cv.INTER_CUBIC)
|
||||
return kern
|
||||
|
||||
def defocus_kernel(d, sz=65):
|
||||
kern = np.zeros((sz, sz), np.uint8)
|
||||
cv2.circle(kern, (sz, sz), d, 255, -1, cv2.LINE_AA, shift=1)
|
||||
cv.circle(kern, (sz, sz), d, 255, -1, cv.LINE_AA, shift=1)
|
||||
kern = np.float32(kern) / 255.0
|
||||
return kern
|
||||
|
||||
@@ -77,52 +77,52 @@ if __name__ == '__main__':
|
||||
|
||||
win = 'deconvolution'
|
||||
|
||||
img = cv2.imread(fn, 0)
|
||||
img = cv.imread(fn, 0)
|
||||
if img is None:
|
||||
print('Failed to load fn1:', fn1)
|
||||
sys.exit(1)
|
||||
|
||||
img = np.float32(img)/255.0
|
||||
cv2.imshow('input', img)
|
||||
cv.imshow('input', img)
|
||||
|
||||
img = blur_edge(img)
|
||||
IMG = cv2.dft(img, flags=cv2.DFT_COMPLEX_OUTPUT)
|
||||
IMG = cv.dft(img, flags=cv.DFT_COMPLEX_OUTPUT)
|
||||
|
||||
defocus = '--circle' in opts
|
||||
|
||||
def update(_):
|
||||
ang = np.deg2rad( cv2.getTrackbarPos('angle', win) )
|
||||
d = cv2.getTrackbarPos('d', win)
|
||||
noise = 10**(-0.1*cv2.getTrackbarPos('SNR (db)', win))
|
||||
ang = np.deg2rad( cv.getTrackbarPos('angle', win) )
|
||||
d = cv.getTrackbarPos('d', win)
|
||||
noise = 10**(-0.1*cv.getTrackbarPos('SNR (db)', win))
|
||||
|
||||
if defocus:
|
||||
psf = defocus_kernel(d)
|
||||
else:
|
||||
psf = motion_kernel(ang, d)
|
||||
cv2.imshow('psf', psf)
|
||||
cv.imshow('psf', psf)
|
||||
|
||||
psf /= psf.sum()
|
||||
psf_pad = np.zeros_like(img)
|
||||
kh, kw = psf.shape
|
||||
psf_pad[:kh, :kw] = psf
|
||||
PSF = cv2.dft(psf_pad, flags=cv2.DFT_COMPLEX_OUTPUT, nonzeroRows = kh)
|
||||
PSF = cv.dft(psf_pad, flags=cv.DFT_COMPLEX_OUTPUT, nonzeroRows = kh)
|
||||
PSF2 = (PSF**2).sum(-1)
|
||||
iPSF = PSF / (PSF2 + noise)[...,np.newaxis]
|
||||
RES = cv2.mulSpectrums(IMG, iPSF, 0)
|
||||
res = cv2.idft(RES, flags=cv2.DFT_SCALE | cv2.DFT_REAL_OUTPUT )
|
||||
RES = cv.mulSpectrums(IMG, iPSF, 0)
|
||||
res = cv.idft(RES, flags=cv.DFT_SCALE | cv.DFT_REAL_OUTPUT )
|
||||
res = np.roll(res, -kh//2, 0)
|
||||
res = np.roll(res, -kw//2, 1)
|
||||
cv2.imshow(win, res)
|
||||
cv.imshow(win, res)
|
||||
|
||||
cv2.namedWindow(win)
|
||||
cv2.namedWindow('psf', 0)
|
||||
cv2.createTrackbar('angle', win, int(opts.get('--angle', 135)), 180, update)
|
||||
cv2.createTrackbar('d', win, int(opts.get('--d', 22)), 50, update)
|
||||
cv2.createTrackbar('SNR (db)', win, int(opts.get('--snr', 25)), 50, update)
|
||||
cv.namedWindow(win)
|
||||
cv.namedWindow('psf', 0)
|
||||
cv.createTrackbar('angle', win, int(opts.get('--angle', 135)), 180, update)
|
||||
cv.createTrackbar('d', win, int(opts.get('--d', 22)), 50, update)
|
||||
cv.createTrackbar('SNR (db)', win, int(opts.get('--snr', 25)), 50, update)
|
||||
update(None)
|
||||
|
||||
while True:
|
||||
ch = cv2.waitKey()
|
||||
ch = cv.waitKey()
|
||||
if ch == 27:
|
||||
break
|
||||
if ch == ord(' '):
|
||||
|
||||
+16
-16
@@ -11,7 +11,7 @@ USAGE:
|
||||
# Python 2/3 compatibility
|
||||
from __future__ import print_function
|
||||
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
import numpy as np
|
||||
import sys
|
||||
|
||||
@@ -65,47 +65,47 @@ def shift_dft(src, dst=None):
|
||||
if __name__ == "__main__":
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
im = cv2.imread(sys.argv[1])
|
||||
im = cv.imread(sys.argv[1])
|
||||
else:
|
||||
im = cv2.imread('../data/baboon.jpg')
|
||||
im = cv.imread('../data/baboon.jpg')
|
||||
print("usage : python dft.py <image_file>")
|
||||
|
||||
# convert to grayscale
|
||||
im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
|
||||
im = cv.cvtColor(im, cv.COLOR_BGR2GRAY)
|
||||
h, w = im.shape[:2]
|
||||
|
||||
realInput = im.astype(np.float64)
|
||||
|
||||
# perform an optimally sized dft
|
||||
dft_M = cv2.getOptimalDFTSize(w)
|
||||
dft_N = cv2.getOptimalDFTSize(h)
|
||||
dft_M = cv.getOptimalDFTSize(w)
|
||||
dft_N = cv.getOptimalDFTSize(h)
|
||||
|
||||
# copy A to dft_A and pad dft_A with zeros
|
||||
dft_A = np.zeros((dft_N, dft_M, 2), dtype=np.float64)
|
||||
dft_A[:h, :w, 0] = realInput
|
||||
|
||||
# no need to pad bottom part of dft_A with zeros because of
|
||||
# use of nonzeroRows parameter in cv2.dft()
|
||||
cv2.dft(dft_A, dst=dft_A, nonzeroRows=h)
|
||||
# use of nonzeroRows parameter in cv.dft()
|
||||
cv.dft(dft_A, dst=dft_A, nonzeroRows=h)
|
||||
|
||||
cv2.imshow("win", im)
|
||||
cv.imshow("win", im)
|
||||
|
||||
# Split fourier into real and imaginary parts
|
||||
image_Re, image_Im = cv2.split(dft_A)
|
||||
image_Re, image_Im = cv.split(dft_A)
|
||||
|
||||
# Compute the magnitude of the spectrum Mag = sqrt(Re^2 + Im^2)
|
||||
magnitude = cv2.sqrt(image_Re**2.0 + image_Im**2.0)
|
||||
magnitude = cv.sqrt(image_Re**2.0 + image_Im**2.0)
|
||||
|
||||
# Compute log(1 + Mag)
|
||||
log_spectrum = cv2.log(1.0 + magnitude)
|
||||
log_spectrum = cv.log(1.0 + magnitude)
|
||||
|
||||
# Rearrange the quadrants of Fourier image so that the origin is at
|
||||
# the image center
|
||||
shift_dft(log_spectrum, log_spectrum)
|
||||
|
||||
# normalize and display the results as rgb
|
||||
cv2.normalize(log_spectrum, log_spectrum, 0.0, 1.0, cv2.NORM_MINMAX)
|
||||
cv2.imshow("magnitude", log_spectrum)
|
||||
cv.normalize(log_spectrum, log_spectrum, 0.0, 1.0, cv.NORM_MINMAX)
|
||||
cv.imshow("magnitude", log_spectrum)
|
||||
|
||||
cv2.waitKey(0)
|
||||
cv2.destroyAllWindows()
|
||||
cv.waitKey(0)
|
||||
cv.destroyAllWindows()
|
||||
|
||||
+18
-18
@@ -30,7 +30,7 @@ from __future__ import print_function
|
||||
# built-in modules
|
||||
from multiprocessing.pool import ThreadPool
|
||||
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
import numpy as np
|
||||
from numpy.linalg import norm
|
||||
@@ -55,18 +55,18 @@ def split2d(img, cell_size, flatten=True):
|
||||
|
||||
def load_digits(fn):
|
||||
print('loading "%s" ...' % fn)
|
||||
digits_img = cv2.imread(fn, 0)
|
||||
digits_img = cv.imread(fn, 0)
|
||||
digits = split2d(digits_img, (SZ, SZ))
|
||||
labels = np.repeat(np.arange(CLASS_N), len(digits)/CLASS_N)
|
||||
return digits, labels
|
||||
|
||||
def deskew(img):
|
||||
m = cv2.moments(img)
|
||||
m = cv.moments(img)
|
||||
if abs(m['mu02']) < 1e-2:
|
||||
return img.copy()
|
||||
skew = m['mu11']/m['mu02']
|
||||
M = np.float32([[1, skew, -0.5*SZ*skew], [0, 1, 0]])
|
||||
img = cv2.warpAffine(img, M, (SZ, SZ), flags=cv2.WARP_INVERSE_MAP | cv2.INTER_LINEAR)
|
||||
img = cv.warpAffine(img, M, (SZ, SZ), flags=cv.WARP_INVERSE_MAP | cv.INTER_LINEAR)
|
||||
return img
|
||||
|
||||
class StatModel(object):
|
||||
@@ -78,10 +78,10 @@ class StatModel(object):
|
||||
class KNearest(StatModel):
|
||||
def __init__(self, k = 3):
|
||||
self.k = k
|
||||
self.model = cv2.ml.KNearest_create()
|
||||
self.model = cv.ml.KNearest_create()
|
||||
|
||||
def train(self, samples, responses):
|
||||
self.model.train(samples, cv2.ml.ROW_SAMPLE, responses)
|
||||
self.model.train(samples, cv.ml.ROW_SAMPLE, responses)
|
||||
|
||||
def predict(self, samples):
|
||||
_retval, results, _neigh_resp, _dists = self.model.findNearest(samples, self.k)
|
||||
@@ -89,14 +89,14 @@ class KNearest(StatModel):
|
||||
|
||||
class SVM(StatModel):
|
||||
def __init__(self, C = 1, gamma = 0.5):
|
||||
self.model = cv2.ml.SVM_create()
|
||||
self.model = cv.ml.SVM_create()
|
||||
self.model.setGamma(gamma)
|
||||
self.model.setC(C)
|
||||
self.model.setKernel(cv2.ml.SVM_RBF)
|
||||
self.model.setType(cv2.ml.SVM_C_SVC)
|
||||
self.model.setKernel(cv.ml.SVM_RBF)
|
||||
self.model.setType(cv.ml.SVM_C_SVC)
|
||||
|
||||
def train(self, samples, responses):
|
||||
self.model.train(samples, cv2.ml.ROW_SAMPLE, responses)
|
||||
self.model.train(samples, cv.ml.ROW_SAMPLE, responses)
|
||||
|
||||
def predict(self, samples):
|
||||
return self.model.predict(samples)[1].ravel()
|
||||
@@ -116,7 +116,7 @@ def evaluate_model(model, digits, samples, labels):
|
||||
|
||||
vis = []
|
||||
for img, flag in zip(digits, resp == labels):
|
||||
img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
|
||||
img = cv.cvtColor(img, cv.COLOR_GRAY2BGR)
|
||||
if not flag:
|
||||
img[...,:2] = 0
|
||||
vis.append(img)
|
||||
@@ -128,9 +128,9 @@ def preprocess_simple(digits):
|
||||
def preprocess_hog(digits):
|
||||
samples = []
|
||||
for img in digits:
|
||||
gx = cv2.Sobel(img, cv2.CV_32F, 1, 0)
|
||||
gy = cv2.Sobel(img, cv2.CV_32F, 0, 1)
|
||||
mag, ang = cv2.cartToPolar(gx, gy)
|
||||
gx = cv.Sobel(img, cv.CV_32F, 1, 0)
|
||||
gy = cv.Sobel(img, cv.CV_32F, 0, 1)
|
||||
mag, ang = cv.cartToPolar(gx, gy)
|
||||
bin_n = 16
|
||||
bin = np.int32(bin_n*ang/(2*np.pi))
|
||||
bin_cells = bin[:10,:10], bin[10:,:10], bin[:10,10:], bin[10:,10:]
|
||||
@@ -163,7 +163,7 @@ if __name__ == '__main__':
|
||||
samples = preprocess_hog(digits2)
|
||||
|
||||
train_n = int(0.9*len(samples))
|
||||
cv2.imshow('test set', mosaic(25, digits[train_n:]))
|
||||
cv.imshow('test set', mosaic(25, digits[train_n:]))
|
||||
digits_train, digits_test = np.split(digits2, [train_n])
|
||||
samples_train, samples_test = np.split(samples, [train_n])
|
||||
labels_train, labels_test = np.split(labels, [train_n])
|
||||
@@ -173,14 +173,14 @@ if __name__ == '__main__':
|
||||
model = KNearest(k=4)
|
||||
model.train(samples_train, labels_train)
|
||||
vis = evaluate_model(model, digits_test, samples_test, labels_test)
|
||||
cv2.imshow('KNearest test', vis)
|
||||
cv.imshow('KNearest test', vis)
|
||||
|
||||
print('training SVM...')
|
||||
model = SVM(C=2.67, gamma=5.383)
|
||||
model.train(samples_train, labels_train)
|
||||
vis = evaluate_model(model, digits_test, samples_test, labels_test)
|
||||
cv2.imshow('SVM test', vis)
|
||||
cv.imshow('SVM test', vis)
|
||||
print('saving SVM as "digits_svm.dat"...')
|
||||
model.save('digits_svm.dat')
|
||||
|
||||
cv2.waitKey(0)
|
||||
cv.waitKey(0)
|
||||
|
||||
@@ -22,7 +22,7 @@ if PY3:
|
||||
xrange = range
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
from multiprocessing.pool import ThreadPool
|
||||
|
||||
from digits import *
|
||||
@@ -66,7 +66,7 @@ class App(object):
|
||||
return self._samples, self._labels
|
||||
|
||||
def run_jobs(self, f, jobs):
|
||||
pool = ThreadPool(processes=cv2.getNumberOfCPUs())
|
||||
pool = ThreadPool(processes=cv.getNumberOfCPUs())
|
||||
ires = pool.imap_unordered(f, jobs)
|
||||
return ires
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
# built-in modules
|
||||
import os
|
||||
@@ -29,19 +29,19 @@ def main():
|
||||
return
|
||||
|
||||
if True:
|
||||
model = cv2.ml.SVM_load(classifier_fn)
|
||||
model = cv.ml.SVM_load(classifier_fn)
|
||||
else:
|
||||
model = cv2.ml.SVM_create()
|
||||
model = cv.ml.SVM_create()
|
||||
model.load_(classifier_fn) #Known bug: https://github.com/opencv/opencv/issues/4969
|
||||
|
||||
while True:
|
||||
_ret, frame = cap.read()
|
||||
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
||||
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
|
||||
|
||||
|
||||
bin = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 31, 10)
|
||||
bin = cv2.medianBlur(bin, 3)
|
||||
_, contours, heirs = cv2.findContours( bin.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
|
||||
bin = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY_INV, 31, 10)
|
||||
bin = cv.medianBlur(bin, 3)
|
||||
_, contours, heirs = cv.findContours( bin.copy(), cv.RETR_CCOMP, cv.CHAIN_APPROX_SIMPLE)
|
||||
try:
|
||||
heirs = heirs[0]
|
||||
except:
|
||||
@@ -51,12 +51,12 @@ def main():
|
||||
_, _, _, outer_i = heir
|
||||
if outer_i >= 0:
|
||||
continue
|
||||
x, y, w, h = cv2.boundingRect(cnt)
|
||||
x, y, w, h = cv.boundingRect(cnt)
|
||||
if not (16 <= h <= 64 and w <= 1.2*h):
|
||||
continue
|
||||
pad = max(h-w, 0)
|
||||
x, w = x - (pad // 2), w + pad
|
||||
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0))
|
||||
cv.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0))
|
||||
|
||||
bin_roi = bin[y:,x:][:h,:w]
|
||||
|
||||
@@ -69,33 +69,33 @@ def main():
|
||||
if v_out.std() > 10.0:
|
||||
continue
|
||||
s = "%f, %f" % (abs(v_in.mean() - v_out.mean()), v_out.std())
|
||||
cv2.putText(frame, s, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.0, (200, 0, 0), thickness = 1)
|
||||
cv.putText(frame, s, (x, y), cv.FONT_HERSHEY_PLAIN, 1.0, (200, 0, 0), thickness = 1)
|
||||
'''
|
||||
|
||||
s = 1.5*float(h)/SZ
|
||||
m = cv2.moments(bin_roi)
|
||||
m = cv.moments(bin_roi)
|
||||
c1 = np.float32([m['m10'], m['m01']]) / m['m00']
|
||||
c0 = np.float32([SZ/2, SZ/2])
|
||||
t = c1 - s*c0
|
||||
A = np.zeros((2, 3), np.float32)
|
||||
A[:,:2] = np.eye(2)*s
|
||||
A[:,2] = t
|
||||
bin_norm = cv2.warpAffine(bin_roi, A, (SZ, SZ), flags=cv2.WARP_INVERSE_MAP | cv2.INTER_LINEAR)
|
||||
bin_norm = cv.warpAffine(bin_roi, A, (SZ, SZ), flags=cv.WARP_INVERSE_MAP | cv.INTER_LINEAR)
|
||||
bin_norm = deskew(bin_norm)
|
||||
if x+w+SZ < frame.shape[1] and y+SZ < frame.shape[0]:
|
||||
frame[y:,x+w:][:SZ, :SZ] = bin_norm[...,np.newaxis]
|
||||
|
||||
sample = preprocess_hog([bin_norm])
|
||||
digit = model.predict(sample)[0]
|
||||
cv2.putText(frame, '%d'%digit, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.0, (200, 0, 0), thickness = 1)
|
||||
cv.putText(frame, '%d'%digit, (x, y), cv.FONT_HERSHEY_PLAIN, 1.0, (200, 0, 0), thickness = 1)
|
||||
|
||||
|
||||
cv2.imshow('frame', frame)
|
||||
cv2.imshow('bin', bin)
|
||||
ch = cv2.waitKey(1)
|
||||
cv.imshow('frame', frame)
|
||||
cv.imshow('bin', bin)
|
||||
ch = cv.waitKey(1)
|
||||
if ch == 27:
|
||||
break
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
+10
-10
@@ -15,7 +15,7 @@ Keys:
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
from common import make_cmap
|
||||
|
||||
@@ -27,7 +27,7 @@ if __name__ == '__main__':
|
||||
fn = '../data/fruits.jpg'
|
||||
print(__doc__)
|
||||
|
||||
img = cv2.imread(fn, 0)
|
||||
img = cv.imread(fn, 0)
|
||||
if img is None:
|
||||
print('Failed to load fn:', fn)
|
||||
sys.exit(1)
|
||||
@@ -39,27 +39,27 @@ if __name__ == '__main__':
|
||||
def update(dummy=None):
|
||||
global need_update
|
||||
need_update = False
|
||||
thrs = cv2.getTrackbarPos('threshold', 'distrans')
|
||||
mark = cv2.Canny(img, thrs, 3*thrs)
|
||||
dist, labels = cv2.distanceTransformWithLabels(~mark, cv2.DIST_L2, 5)
|
||||
thrs = cv.getTrackbarPos('threshold', 'distrans')
|
||||
mark = cv.Canny(img, thrs, 3*thrs)
|
||||
dist, labels = cv.distanceTransformWithLabels(~mark, cv.DIST_L2, 5)
|
||||
if voronoi:
|
||||
vis = cm[np.uint8(labels)]
|
||||
else:
|
||||
vis = cm[np.uint8(dist*2)]
|
||||
vis[mark != 0] = 255
|
||||
cv2.imshow('distrans', vis)
|
||||
cv.imshow('distrans', vis)
|
||||
|
||||
def invalidate(dummy=None):
|
||||
global need_update
|
||||
need_update = True
|
||||
|
||||
cv2.namedWindow('distrans')
|
||||
cv2.createTrackbar('threshold', 'distrans', 60, 255, invalidate)
|
||||
cv.namedWindow('distrans')
|
||||
cv.createTrackbar('threshold', 'distrans', 60, 255, invalidate)
|
||||
update()
|
||||
|
||||
|
||||
while True:
|
||||
ch = cv2.waitKey(50)
|
||||
ch = cv.waitKey(50)
|
||||
if ch == 27:
|
||||
break
|
||||
if ch == ord('v'):
|
||||
@@ -68,4 +68,4 @@ if __name__ == '__main__':
|
||||
update()
|
||||
if need_update:
|
||||
update()
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
+11
-11
@@ -13,7 +13,7 @@ Usage:
|
||||
# Python 2/3 compatibility
|
||||
from __future__ import print_function
|
||||
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
import numpy as np
|
||||
|
||||
# relative module
|
||||
@@ -34,22 +34,22 @@ if __name__ == '__main__':
|
||||
def nothing(*arg):
|
||||
pass
|
||||
|
||||
cv2.namedWindow('edge')
|
||||
cv2.createTrackbar('thrs1', 'edge', 2000, 5000, nothing)
|
||||
cv2.createTrackbar('thrs2', 'edge', 4000, 5000, nothing)
|
||||
cv.namedWindow('edge')
|
||||
cv.createTrackbar('thrs1', 'edge', 2000, 5000, nothing)
|
||||
cv.createTrackbar('thrs2', 'edge', 4000, 5000, nothing)
|
||||
|
||||
cap = video.create_capture(fn)
|
||||
while True:
|
||||
flag, img = cap.read()
|
||||
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||
thrs1 = cv2.getTrackbarPos('thrs1', 'edge')
|
||||
thrs2 = cv2.getTrackbarPos('thrs2', 'edge')
|
||||
edge = cv2.Canny(gray, thrs1, thrs2, apertureSize=5)
|
||||
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
|
||||
thrs1 = cv.getTrackbarPos('thrs1', 'edge')
|
||||
thrs2 = cv.getTrackbarPos('thrs2', 'edge')
|
||||
edge = cv.Canny(gray, thrs1, thrs2, apertureSize=5)
|
||||
vis = img.copy()
|
||||
vis = np.uint8(vis/2.)
|
||||
vis[edge != 0] = (0, 255, 0)
|
||||
cv2.imshow('edge', vis)
|
||||
ch = cv2.waitKey(5)
|
||||
cv.imshow('edge', vis)
|
||||
ch = cv.waitKey(5)
|
||||
if ch == 27:
|
||||
break
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
@@ -11,7 +11,7 @@ USAGE:
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
# local modules
|
||||
from video import create_capture
|
||||
@@ -20,7 +20,7 @@ from common import clock, draw_str
|
||||
|
||||
def detect(img, cascade):
|
||||
rects = cascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30),
|
||||
flags=cv2.CASCADE_SCALE_IMAGE)
|
||||
flags=cv.CASCADE_SCALE_IMAGE)
|
||||
if len(rects) == 0:
|
||||
return []
|
||||
rects[:,2:] += rects[:,:2]
|
||||
@@ -28,7 +28,7 @@ def detect(img, cascade):
|
||||
|
||||
def draw_rects(img, rects, color):
|
||||
for x1, y1, x2, y2 in rects:
|
||||
cv2.rectangle(img, (x1, y1), (x2, y2), color, 2)
|
||||
cv.rectangle(img, (x1, y1), (x2, y2), color, 2)
|
||||
|
||||
if __name__ == '__main__':
|
||||
import sys, getopt
|
||||
@@ -43,15 +43,15 @@ if __name__ == '__main__':
|
||||
cascade_fn = args.get('--cascade', "../../data/haarcascades/haarcascade_frontalface_alt.xml")
|
||||
nested_fn = args.get('--nested-cascade', "../../data/haarcascades/haarcascade_eye.xml")
|
||||
|
||||
cascade = cv2.CascadeClassifier(cascade_fn)
|
||||
nested = cv2.CascadeClassifier(nested_fn)
|
||||
cascade = cv.CascadeClassifier(cascade_fn)
|
||||
nested = cv.CascadeClassifier(nested_fn)
|
||||
|
||||
cam = create_capture(video_src, fallback='synth:bg=../data/lena.jpg:noise=0.05')
|
||||
|
||||
while True:
|
||||
ret, img = cam.read()
|
||||
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||
gray = cv2.equalizeHist(gray)
|
||||
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
|
||||
gray = cv.equalizeHist(gray)
|
||||
|
||||
t = clock()
|
||||
rects = detect(gray, cascade)
|
||||
@@ -66,8 +66,8 @@ if __name__ == '__main__':
|
||||
dt = clock() - t
|
||||
|
||||
draw_str(vis, (20, 20), 'time: %.1f ms' % (dt*1000))
|
||||
cv2.imshow('facedetect', vis)
|
||||
cv.imshow('facedetect', vis)
|
||||
|
||||
if cv2.waitKey(5) == 27:
|
||||
if cv.waitKey(5) == 27:
|
||||
break
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
@@ -26,7 +26,7 @@ Select a textured planar object to track by drawing a box with a mouse.
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
# local modules
|
||||
import video
|
||||
@@ -43,7 +43,7 @@ class App:
|
||||
self.paused = False
|
||||
self.tracker = PlaneTracker()
|
||||
|
||||
cv2.namedWindow('plane')
|
||||
cv.namedWindow('plane')
|
||||
self.rect_sel = common.RectSelector('plane', self.on_rect)
|
||||
|
||||
def on_rect(self, rect):
|
||||
@@ -67,20 +67,20 @@ class App:
|
||||
vis[:,w:] = target.image
|
||||
draw_keypoints(vis[:,w:], target.keypoints)
|
||||
x0, y0, x1, y1 = target.rect
|
||||
cv2.rectangle(vis, (x0+w, y0), (x1+w, y1), (0, 255, 0), 2)
|
||||
cv.rectangle(vis, (x0+w, y0), (x1+w, y1), (0, 255, 0), 2)
|
||||
|
||||
if playing:
|
||||
tracked = self.tracker.track(self.frame)
|
||||
if len(tracked) > 0:
|
||||
tracked = tracked[0]
|
||||
cv2.polylines(vis, [np.int32(tracked.quad)], True, (255, 255, 255), 2)
|
||||
cv.polylines(vis, [np.int32(tracked.quad)], True, (255, 255, 255), 2)
|
||||
for (x0, y0), (x1, y1) in zip(np.int32(tracked.p0), np.int32(tracked.p1)):
|
||||
cv2.line(vis, (x0+w, y0), (x1, y1), (0, 255, 0))
|
||||
cv.line(vis, (x0+w, y0), (x1, y1), (0, 255, 0))
|
||||
draw_keypoints(vis, self.tracker.frame_points)
|
||||
|
||||
self.rect_sel.draw(vis)
|
||||
cv2.imshow('plane', vis)
|
||||
ch = cv2.waitKey(1)
|
||||
cv.imshow('plane', vis)
|
||||
ch = cv.waitKey(1)
|
||||
if ch == ord(' '):
|
||||
self.paused = not self.paused
|
||||
if ch == 27:
|
||||
|
||||
+36
-36
@@ -18,7 +18,7 @@ USAGE
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
from common import anorm, getsize
|
||||
|
||||
FLANN_INDEX_KDTREE = 1 # bug: flann enums are missing
|
||||
@@ -28,33 +28,33 @@ FLANN_INDEX_LSH = 6
|
||||
def init_feature(name):
|
||||
chunks = name.split('-')
|
||||
if chunks[0] == 'sift':
|
||||
detector = cv2.xfeatures2d.SIFT_create()
|
||||
norm = cv2.NORM_L2
|
||||
detector = cv.xfeatures2d.SIFT_create()
|
||||
norm = cv.NORM_L2
|
||||
elif chunks[0] == 'surf':
|
||||
detector = cv2.xfeatures2d.SURF_create(800)
|
||||
norm = cv2.NORM_L2
|
||||
detector = cv.xfeatures2d.SURF_create(800)
|
||||
norm = cv.NORM_L2
|
||||
elif chunks[0] == 'orb':
|
||||
detector = cv2.ORB_create(400)
|
||||
norm = cv2.NORM_HAMMING
|
||||
detector = cv.ORB_create(400)
|
||||
norm = cv.NORM_HAMMING
|
||||
elif chunks[0] == 'akaze':
|
||||
detector = cv2.AKAZE_create()
|
||||
norm = cv2.NORM_HAMMING
|
||||
detector = cv.AKAZE_create()
|
||||
norm = cv.NORM_HAMMING
|
||||
elif chunks[0] == 'brisk':
|
||||
detector = cv2.BRISK_create()
|
||||
norm = cv2.NORM_HAMMING
|
||||
detector = cv.BRISK_create()
|
||||
norm = cv.NORM_HAMMING
|
||||
else:
|
||||
return None, None
|
||||
if 'flann' in chunks:
|
||||
if norm == cv2.NORM_L2:
|
||||
if norm == cv.NORM_L2:
|
||||
flann_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
|
||||
else:
|
||||
flann_params= dict(algorithm = FLANN_INDEX_LSH,
|
||||
table_number = 6, # 12
|
||||
key_size = 12, # 20
|
||||
multi_probe_level = 1) #2
|
||||
matcher = cv2.FlannBasedMatcher(flann_params, {}) # bug : need to pass empty dict (#1329)
|
||||
matcher = cv.FlannBasedMatcher(flann_params, {}) # bug : need to pass empty dict (#1329)
|
||||
else:
|
||||
matcher = cv2.BFMatcher(norm)
|
||||
matcher = cv.BFMatcher(norm)
|
||||
return detector, matcher
|
||||
|
||||
|
||||
@@ -76,12 +76,12 @@ def explore_match(win, img1, img2, kp_pairs, status = None, H = None):
|
||||
vis = np.zeros((max(h1, h2), w1+w2), np.uint8)
|
||||
vis[:h1, :w1] = img1
|
||||
vis[:h2, w1:w1+w2] = img2
|
||||
vis = cv2.cvtColor(vis, cv2.COLOR_GRAY2BGR)
|
||||
vis = cv.cvtColor(vis, cv.COLOR_GRAY2BGR)
|
||||
|
||||
if H is not None:
|
||||
corners = np.float32([[0, 0], [w1, 0], [w1, h1], [0, h1]])
|
||||
corners = np.int32( cv2.perspectiveTransform(corners.reshape(1, -1, 2), H).reshape(-1, 2) + (w1, 0) )
|
||||
cv2.polylines(vis, [corners], True, (255, 255, 255))
|
||||
corners = np.int32( cv.perspectiveTransform(corners.reshape(1, -1, 2), H).reshape(-1, 2) + (w1, 0) )
|
||||
cv.polylines(vis, [corners], True, (255, 255, 255))
|
||||
|
||||
if status is None:
|
||||
status = np.ones(len(kp_pairs), np.bool_)
|
||||
@@ -96,26 +96,26 @@ def explore_match(win, img1, img2, kp_pairs, status = None, H = None):
|
||||
for (x1, y1), (x2, y2), inlier in zip(p1, p2, status):
|
||||
if inlier:
|
||||
col = green
|
||||
cv2.circle(vis, (x1, y1), 2, col, -1)
|
||||
cv2.circle(vis, (x2, y2), 2, col, -1)
|
||||
cv.circle(vis, (x1, y1), 2, col, -1)
|
||||
cv.circle(vis, (x2, y2), 2, col, -1)
|
||||
else:
|
||||
col = red
|
||||
r = 2
|
||||
thickness = 3
|
||||
cv2.line(vis, (x1-r, y1-r), (x1+r, y1+r), col, thickness)
|
||||
cv2.line(vis, (x1-r, y1+r), (x1+r, y1-r), col, thickness)
|
||||
cv2.line(vis, (x2-r, y2-r), (x2+r, y2+r), col, thickness)
|
||||
cv2.line(vis, (x2-r, y2+r), (x2+r, y2-r), col, thickness)
|
||||
cv.line(vis, (x1-r, y1-r), (x1+r, y1+r), col, thickness)
|
||||
cv.line(vis, (x1-r, y1+r), (x1+r, y1-r), col, thickness)
|
||||
cv.line(vis, (x2-r, y2-r), (x2+r, y2+r), col, thickness)
|
||||
cv.line(vis, (x2-r, y2+r), (x2+r, y2-r), col, thickness)
|
||||
vis0 = vis.copy()
|
||||
for (x1, y1), (x2, y2), inlier in zip(p1, p2, status):
|
||||
if inlier:
|
||||
cv2.line(vis, (x1, y1), (x2, y2), green)
|
||||
cv.line(vis, (x1, y1), (x2, y2), green)
|
||||
|
||||
cv2.imshow(win, vis)
|
||||
cv.imshow(win, vis)
|
||||
|
||||
def onmouse(event, x, y, flags, param):
|
||||
cur_vis = vis
|
||||
if flags & cv2.EVENT_FLAG_LBUTTON:
|
||||
if flags & cv.EVENT_FLAG_LBUTTON:
|
||||
cur_vis = vis0.copy()
|
||||
r = 8
|
||||
m = (anorm(np.array(p1) - (x, y)) < r) | (anorm(np.array(p2) - (x, y)) < r)
|
||||
@@ -124,15 +124,15 @@ def explore_match(win, img1, img2, kp_pairs, status = None, H = None):
|
||||
for i in idxs:
|
||||
(x1, y1), (x2, y2) = p1[i], p2[i]
|
||||
col = (red, green)[status[i]]
|
||||
cv2.line(cur_vis, (x1, y1), (x2, y2), col)
|
||||
cv.line(cur_vis, (x1, y1), (x2, y2), col)
|
||||
kp1, kp2 = kp_pairs[i]
|
||||
kp1s.append(kp1)
|
||||
kp2s.append(kp2)
|
||||
cur_vis = cv2.drawKeypoints(cur_vis, kp1s, None, flags=4, color=kp_color)
|
||||
cur_vis[:,w1:] = cv2.drawKeypoints(cur_vis[:,w1:], kp2s, None, flags=4, color=kp_color)
|
||||
cur_vis = cv.drawKeypoints(cur_vis, kp1s, None, flags=4, color=kp_color)
|
||||
cur_vis[:,w1:] = cv.drawKeypoints(cur_vis[:,w1:], kp2s, None, flags=4, color=kp_color)
|
||||
|
||||
cv2.imshow(win, cur_vis)
|
||||
cv2.setMouseCallback(win, onmouse)
|
||||
cv.imshow(win, cur_vis)
|
||||
cv.setMouseCallback(win, onmouse)
|
||||
return vis
|
||||
|
||||
|
||||
@@ -149,8 +149,8 @@ if __name__ == '__main__':
|
||||
fn1 = '../data/box.png'
|
||||
fn2 = '../data/box_in_scene.png'
|
||||
|
||||
img1 = cv2.imread(fn1, 0)
|
||||
img2 = cv2.imread(fn2, 0)
|
||||
img1 = cv.imread(fn1, 0)
|
||||
img2 = cv.imread(fn2, 0)
|
||||
detector, matcher = init_feature(feature_name)
|
||||
|
||||
if img1 is None:
|
||||
@@ -176,7 +176,7 @@ if __name__ == '__main__':
|
||||
raw_matches = matcher.knnMatch(desc1, trainDescriptors = desc2, k = 2) #2
|
||||
p1, p2, kp_pairs = filter_matches(kp1, kp2, raw_matches)
|
||||
if len(p1) >= 4:
|
||||
H, status = cv2.findHomography(p1, p2, cv2.RANSAC, 5.0)
|
||||
H, status = cv.findHomography(p1, p2, cv.RANSAC, 5.0)
|
||||
print('%d / %d inliers/matched' % (np.sum(status), len(status)))
|
||||
else:
|
||||
H, status = None, None
|
||||
@@ -185,5 +185,5 @@ if __name__ == '__main__':
|
||||
_vis = explore_match(win, img1, img2, kp_pairs, status, H)
|
||||
|
||||
match_and_draw('find_obj')
|
||||
cv2.waitKey()
|
||||
cv2.destroyAllWindows()
|
||||
cv.waitKey()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
+17
-17
@@ -4,7 +4,7 @@
|
||||
Robust line fitting.
|
||||
==================
|
||||
|
||||
Example of using cv2.fitLine function for fitting line
|
||||
Example of using cv.fitLine function for fitting line
|
||||
to points in presence of outliers.
|
||||
|
||||
Usage
|
||||
@@ -28,7 +28,7 @@ import sys
|
||||
PY3 = sys.version_info[0] == 3
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
# built-in modules
|
||||
import itertools as it
|
||||
@@ -55,40 +55,40 @@ else:
|
||||
cur_func_name = dist_func_names.next()
|
||||
|
||||
def update(_=None):
|
||||
noise = cv2.getTrackbarPos('noise', 'fit line')
|
||||
n = cv2.getTrackbarPos('point n', 'fit line')
|
||||
r = cv2.getTrackbarPos('outlier %', 'fit line') / 100.0
|
||||
noise = cv.getTrackbarPos('noise', 'fit line')
|
||||
n = cv.getTrackbarPos('point n', 'fit line')
|
||||
r = cv.getTrackbarPos('outlier %', 'fit line') / 100.0
|
||||
outn = int(n*r)
|
||||
|
||||
p0, p1 = (90, 80), (w-90, h-80)
|
||||
img = np.zeros((h, w, 3), np.uint8)
|
||||
cv2.line(img, toint(p0), toint(p1), (0, 255, 0))
|
||||
cv.line(img, toint(p0), toint(p1), (0, 255, 0))
|
||||
|
||||
if n > 0:
|
||||
line_points = sample_line(p0, p1, n-outn, noise)
|
||||
outliers = np.random.rand(outn, 2) * (w, h)
|
||||
points = np.vstack([line_points, outliers])
|
||||
for p in line_points:
|
||||
cv2.circle(img, toint(p), 2, (255, 255, 255), -1)
|
||||
cv.circle(img, toint(p), 2, (255, 255, 255), -1)
|
||||
for p in outliers:
|
||||
cv2.circle(img, toint(p), 2, (64, 64, 255), -1)
|
||||
func = getattr(cv2, cur_func_name)
|
||||
vx, vy, cx, cy = cv2.fitLine(np.float32(points), func, 0, 0.01, 0.01)
|
||||
cv2.line(img, (int(cx-vx*w), int(cy-vy*w)), (int(cx+vx*w), int(cy+vy*w)), (0, 0, 255))
|
||||
cv.circle(img, toint(p), 2, (64, 64, 255), -1)
|
||||
func = getattr(cv, cur_func_name)
|
||||
vx, vy, cx, cy = cv.fitLine(np.float32(points), func, 0, 0.01, 0.01)
|
||||
cv.line(img, (int(cx-vx*w), int(cy-vy*w)), (int(cx+vx*w), int(cy+vy*w)), (0, 0, 255))
|
||||
|
||||
draw_str(img, (20, 20), cur_func_name)
|
||||
cv2.imshow('fit line', img)
|
||||
cv.imshow('fit line', img)
|
||||
|
||||
if __name__ == '__main__':
|
||||
print(__doc__)
|
||||
|
||||
cv2.namedWindow('fit line')
|
||||
cv2.createTrackbar('noise', 'fit line', 3, 50, update)
|
||||
cv2.createTrackbar('point n', 'fit line', 100, 500, update)
|
||||
cv2.createTrackbar('outlier %', 'fit line', 30, 100, update)
|
||||
cv.namedWindow('fit line')
|
||||
cv.createTrackbar('noise', 'fit line', 3, 50, update)
|
||||
cv.createTrackbar('point n', 'fit line', 100, 500, update)
|
||||
cv.createTrackbar('outlier %', 'fit line', 30, 100, update)
|
||||
while True:
|
||||
update()
|
||||
ch = cv2.waitKey(0)
|
||||
ch = cv.waitKey(0)
|
||||
if ch == ord('f'):
|
||||
if PY3:
|
||||
cur_func_name = next(dist_func_names)
|
||||
|
||||
+15
-15
@@ -18,7 +18,7 @@ Keys:
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
if __name__ == '__main__':
|
||||
import sys
|
||||
@@ -28,7 +28,7 @@ if __name__ == '__main__':
|
||||
fn = '../data/fruits.jpg'
|
||||
print(__doc__)
|
||||
|
||||
img = cv2.imread(fn, True)
|
||||
img = cv.imread(fn, True)
|
||||
if img is None:
|
||||
print('Failed to load image file:', fn)
|
||||
sys.exit(1)
|
||||
@@ -41,32 +41,32 @@ if __name__ == '__main__':
|
||||
|
||||
def update(dummy=None):
|
||||
if seed_pt is None:
|
||||
cv2.imshow('floodfill', img)
|
||||
cv.imshow('floodfill', img)
|
||||
return
|
||||
flooded = img.copy()
|
||||
mask[:] = 0
|
||||
lo = cv2.getTrackbarPos('lo', 'floodfill')
|
||||
hi = cv2.getTrackbarPos('hi', 'floodfill')
|
||||
lo = cv.getTrackbarPos('lo', 'floodfill')
|
||||
hi = cv.getTrackbarPos('hi', 'floodfill')
|
||||
flags = connectivity
|
||||
if fixed_range:
|
||||
flags |= cv2.FLOODFILL_FIXED_RANGE
|
||||
cv2.floodFill(flooded, mask, seed_pt, (255, 255, 255), (lo,)*3, (hi,)*3, flags)
|
||||
cv2.circle(flooded, seed_pt, 2, (0, 0, 255), -1)
|
||||
cv2.imshow('floodfill', flooded)
|
||||
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.imshow('floodfill', flooded)
|
||||
|
||||
def onmouse(event, x, y, flags, param):
|
||||
global seed_pt
|
||||
if flags & cv2.EVENT_FLAG_LBUTTON:
|
||||
if flags & cv.EVENT_FLAG_LBUTTON:
|
||||
seed_pt = x, y
|
||||
update()
|
||||
|
||||
update()
|
||||
cv2.setMouseCallback('floodfill', onmouse)
|
||||
cv2.createTrackbar('lo', 'floodfill', 20, 255, update)
|
||||
cv2.createTrackbar('hi', 'floodfill', 20, 255, update)
|
||||
cv.setMouseCallback('floodfill', onmouse)
|
||||
cv.createTrackbar('lo', 'floodfill', 20, 255, update)
|
||||
cv.createTrackbar('hi', 'floodfill', 20, 255, update)
|
||||
|
||||
while True:
|
||||
ch = cv2.waitKey()
|
||||
ch = cv.waitKey()
|
||||
if ch == 27:
|
||||
break
|
||||
if ch == ord('f'):
|
||||
@@ -77,4 +77,4 @@ if __name__ == '__main__':
|
||||
connectivity = 12-connectivity
|
||||
print('connectivity =', connectivity)
|
||||
update()
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
@@ -18,7 +18,7 @@ gabor_threads.py [image filename]
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
from multiprocessing.pool import ThreadPool
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ def build_filters():
|
||||
filters = []
|
||||
ksize = 31
|
||||
for theta in np.arange(0, np.pi, np.pi / 16):
|
||||
kern = cv2.getGaborKernel((ksize, ksize), 4.0, theta, 10.0, 0.5, 0, ktype=cv2.CV_32F)
|
||||
kern = cv.getGaborKernel((ksize, ksize), 4.0, theta, 10.0, 0.5, 0, ktype=cv.CV_32F)
|
||||
kern /= 1.5*kern.sum()
|
||||
filters.append(kern)
|
||||
return filters
|
||||
@@ -34,14 +34,14 @@ def build_filters():
|
||||
def process(img, filters):
|
||||
accum = np.zeros_like(img)
|
||||
for kern in filters:
|
||||
fimg = cv2.filter2D(img, cv2.CV_8UC3, kern)
|
||||
fimg = cv.filter2D(img, cv.CV_8UC3, kern)
|
||||
np.maximum(accum, fimg, accum)
|
||||
return accum
|
||||
|
||||
def process_threaded(img, filters, threadn = 8):
|
||||
accum = np.zeros_like(img)
|
||||
def f(kern):
|
||||
return cv2.filter2D(img, cv2.CV_8UC3, kern)
|
||||
return cv.filter2D(img, cv.CV_8UC3, kern)
|
||||
pool = ThreadPool(processes=threadn)
|
||||
for fimg in pool.imap_unordered(f, filters):
|
||||
np.maximum(accum, fimg, accum)
|
||||
@@ -57,7 +57,7 @@ if __name__ == '__main__':
|
||||
except:
|
||||
img_fn = '../data/baboon.jpg'
|
||||
|
||||
img = cv2.imread(img_fn)
|
||||
img = cv.imread(img_fn)
|
||||
if img is None:
|
||||
print('Failed to load image file:', img_fn)
|
||||
sys.exit(1)
|
||||
@@ -70,7 +70,7 @@ if __name__ == '__main__':
|
||||
res2 = process_threaded(img, filters)
|
||||
|
||||
print('res1 == res2: ', (res1 == res2).all())
|
||||
cv2.imshow('img', img)
|
||||
cv2.imshow('result', res2)
|
||||
cv2.waitKey()
|
||||
cv2.destroyAllWindows()
|
||||
cv.imshow('img', img)
|
||||
cv.imshow('result', res2)
|
||||
cv.waitKey()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
@@ -10,7 +10,7 @@ if PY3:
|
||||
|
||||
import numpy as np
|
||||
from numpy import random
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
def make_gaussians(cluster_n, img_size):
|
||||
points = []
|
||||
@@ -28,10 +28,10 @@ def make_gaussians(cluster_n, img_size):
|
||||
|
||||
def draw_gaussain(img, mean, cov, color):
|
||||
x, y = np.int32(mean)
|
||||
w, u, _vt = cv2.SVDecomp(cov)
|
||||
w, u, _vt = cv.SVDecomp(cov)
|
||||
ang = np.arctan2(u[1, 0], u[0, 0])*(180/np.pi)
|
||||
s1, s2 = np.sqrt(w)*3.0
|
||||
cv2.ellipse(img, (x, y), (s1, s2), ang, 0, 360, color, 1, cv2.LINE_AA)
|
||||
cv.ellipse(img, (x, y), (s1, s2), ang, 0, 360, color, 1, cv.LINE_AA)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
@@ -45,9 +45,9 @@ if __name__ == '__main__':
|
||||
points, ref_distrs = make_gaussians(cluster_n, img_size)
|
||||
|
||||
print('EM (opencv) ...')
|
||||
em = cv2.ml.EM_create()
|
||||
em = cv.ml.EM_create()
|
||||
em.setClustersNumber(cluster_n)
|
||||
em.setCovarianceMatrixType(cv2.ml.EM_COV_MAT_GENERIC)
|
||||
em.setCovarianceMatrixType(cv.ml.EM_COV_MAT_GENERIC)
|
||||
em.trainEM(points)
|
||||
means = em.getMeans()
|
||||
covs = em.getCovs() # Known bug: https://github.com/opencv/opencv/pull/4232
|
||||
@@ -56,14 +56,14 @@ if __name__ == '__main__':
|
||||
|
||||
img = np.zeros((img_size, img_size, 3), np.uint8)
|
||||
for x, y in np.int32(points):
|
||||
cv2.circle(img, (x, y), 1, (255, 255, 255), -1)
|
||||
cv.circle(img, (x, y), 1, (255, 255, 255), -1)
|
||||
for m, cov in ref_distrs:
|
||||
draw_gaussain(img, m, cov, (0, 255, 0))
|
||||
for m, cov in found_distrs:
|
||||
draw_gaussain(img, m, cov, (0, 0, 255))
|
||||
|
||||
cv2.imshow('gaussian mixture', img)
|
||||
ch = cv2.waitKey(0)
|
||||
cv.imshow('gaussian mixture', img)
|
||||
ch = cv.waitKey(0)
|
||||
if ch == 27:
|
||||
break
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
+28
-28
@@ -31,7 +31,7 @@ Key 's' - To save the results
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
import sys
|
||||
|
||||
BLUE = [255,0,0] # rectangle color
|
||||
@@ -58,45 +58,45 @@ 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 == cv2.EVENT_RBUTTONDOWN:
|
||||
if event == cv.EVENT_RBUTTONDOWN:
|
||||
rectangle = True
|
||||
ix,iy = x,y
|
||||
|
||||
elif event == cv2.EVENT_MOUSEMOVE:
|
||||
elif event == cv.EVENT_MOUSEMOVE:
|
||||
if rectangle == True:
|
||||
img = img2.copy()
|
||||
cv2.rectangle(img,(ix,iy),(x,y),BLUE,2)
|
||||
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 == cv2.EVENT_RBUTTONUP:
|
||||
elif event == cv.EVENT_RBUTTONUP:
|
||||
rectangle = False
|
||||
rect_over = True
|
||||
cv2.rectangle(img,(ix,iy),(x,y),BLUE,2)
|
||||
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 == cv2.EVENT_LBUTTONDOWN:
|
||||
if event == cv.EVENT_LBUTTONDOWN:
|
||||
if rect_over == False:
|
||||
print("first draw rectangle \n")
|
||||
else:
|
||||
drawing = True
|
||||
cv2.circle(img,(x,y),thickness,value['color'],-1)
|
||||
cv2.circle(mask,(x,y),thickness,value['val'],-1)
|
||||
cv.circle(img,(x,y),thickness,value['color'],-1)
|
||||
cv.circle(mask,(x,y),thickness,value['val'],-1)
|
||||
|
||||
elif event == cv2.EVENT_MOUSEMOVE:
|
||||
elif event == cv.EVENT_MOUSEMOVE:
|
||||
if drawing == True:
|
||||
cv2.circle(img,(x,y),thickness,value['color'],-1)
|
||||
cv2.circle(mask,(x,y),thickness,value['val'],-1)
|
||||
cv.circle(img,(x,y),thickness,value['color'],-1)
|
||||
cv.circle(mask,(x,y),thickness,value['val'],-1)
|
||||
|
||||
elif event == cv2.EVENT_LBUTTONUP:
|
||||
elif event == cv.EVENT_LBUTTONUP:
|
||||
if drawing == True:
|
||||
drawing = False
|
||||
cv2.circle(img,(x,y),thickness,value['color'],-1)
|
||||
cv2.circle(mask,(x,y),thickness,value['val'],-1)
|
||||
cv.circle(img,(x,y),thickness,value['color'],-1)
|
||||
cv.circle(mask,(x,y),thickness,value['val'],-1)
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -111,25 +111,25 @@ if __name__ == '__main__':
|
||||
print("Correct Usage: python grabcut.py <filename> \n")
|
||||
filename = '../data/lena.jpg'
|
||||
|
||||
img = cv2.imread(filename)
|
||||
img = cv.imread(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
|
||||
cv2.namedWindow('output')
|
||||
cv2.namedWindow('input')
|
||||
cv2.setMouseCallback('input',onmouse)
|
||||
cv2.moveWindow('input',img.shape[1]+10,90)
|
||||
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):
|
||||
|
||||
cv2.imshow('output',output)
|
||||
cv2.imshow('input',img)
|
||||
k = cv2.waitKey(1)
|
||||
cv.imshow('output',output)
|
||||
cv.imshow('input',img)
|
||||
k = cv.waitKey(1)
|
||||
|
||||
# key bindings
|
||||
if k == 27: # esc to exit
|
||||
@@ -147,7 +147,7 @@ if __name__ == '__main__':
|
||||
elif k == ord('s'): # save image
|
||||
bar = np.zeros((img.shape[0],5,3),np.uint8)
|
||||
res = np.hstack((img2,bar,img,bar,output))
|
||||
cv2.imwrite('grabcut_output.png',res)
|
||||
cv.imwrite('grabcut_output.png',res)
|
||||
print(" Result saved as image \n")
|
||||
elif k == ord('r'): # reset everything
|
||||
print("resetting \n")
|
||||
@@ -166,14 +166,14 @@ if __name__ == '__main__':
|
||||
if (rect_or_mask == 0): # grabcut with rect
|
||||
bgdmodel = np.zeros((1,65),np.float64)
|
||||
fgdmodel = np.zeros((1,65),np.float64)
|
||||
cv2.grabCut(img2,mask,rect,bgdmodel,fgdmodel,1,cv2.GC_INIT_WITH_RECT)
|
||||
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)
|
||||
cv2.grabCut(img2,mask,rect,bgdmodel,fgdmodel,1,cv2.GC_INIT_WITH_MASK)
|
||||
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 = cv2.bitwise_and(img2,img2,mask=mask2)
|
||||
output = cv.bitwise_and(img2,img2,mask=mask2)
|
||||
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
+27
-27
@@ -3,7 +3,7 @@
|
||||
''' This is a sample for histogram plotting for RGB images and grayscale images for better understanding of colour distribution
|
||||
|
||||
Benefit : Learn how to draw histogram of images
|
||||
Get familier with cv2.calcHist, cv2.equalizeHist,cv2.normalize and some drawing functions
|
||||
Get familier with cv.calcHist, cv.equalizeHist,cv.normalize and some drawing functions
|
||||
|
||||
Level : Beginner or Intermediate
|
||||
|
||||
@@ -18,7 +18,7 @@ Abid Rahman 3/14/12 debug Gary Bradski
|
||||
# Python 2/3 compatibility
|
||||
from __future__ import print_function
|
||||
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
import numpy as np
|
||||
|
||||
bins = np.arange(256).reshape(256,1)
|
||||
@@ -30,11 +30,11 @@ def hist_curve(im):
|
||||
elif im.shape[2] == 3:
|
||||
color = [ (255,0,0),(0,255,0),(0,0,255) ]
|
||||
for ch, col in enumerate(color):
|
||||
hist_item = cv2.calcHist([im],[ch],None,[256],[0,256])
|
||||
cv2.normalize(hist_item,hist_item,0,255,cv2.NORM_MINMAX)
|
||||
hist_item = cv.calcHist([im],[ch],None,[256],[0,256])
|
||||
cv.normalize(hist_item,hist_item,0,255,cv.NORM_MINMAX)
|
||||
hist=np.int32(np.around(hist_item))
|
||||
pts = np.int32(np.column_stack((bins,hist)))
|
||||
cv2.polylines(h,[pts],False,col)
|
||||
cv.polylines(h,[pts],False,col)
|
||||
y=np.flipud(h)
|
||||
return y
|
||||
|
||||
@@ -43,12 +43,12 @@ def hist_lines(im):
|
||||
if len(im.shape)!=2:
|
||||
print("hist_lines applicable only for grayscale images")
|
||||
#print("so converting image to grayscale for representation"
|
||||
im = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
|
||||
hist_item = cv2.calcHist([im],[0],None,[256],[0,256])
|
||||
cv2.normalize(hist_item,hist_item,0,255,cv2.NORM_MINMAX)
|
||||
im = cv.cvtColor(im,cv.COLOR_BGR2GRAY)
|
||||
hist_item = cv.calcHist([im],[0],None,[256],[0,256])
|
||||
cv.normalize(hist_item,hist_item,0,255,cv.NORM_MINMAX)
|
||||
hist=np.int32(np.around(hist_item))
|
||||
for x,y in enumerate(hist):
|
||||
cv2.line(h,(x,0),(x,y),(255,255,255))
|
||||
cv.line(h,(x,0),(x,y),(255,255,255))
|
||||
y = np.flipud(h)
|
||||
return y
|
||||
|
||||
@@ -63,13 +63,13 @@ if __name__ == '__main__':
|
||||
fname = '../data/lena.jpg'
|
||||
print("usage : python hist.py <image_file>")
|
||||
|
||||
im = cv2.imread(fname)
|
||||
im = cv.imread(fname)
|
||||
|
||||
if im is None:
|
||||
print('Failed to load image file:', fname)
|
||||
sys.exit(1)
|
||||
|
||||
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
|
||||
gray = cv.cvtColor(im,cv.COLOR_BGR2GRAY)
|
||||
|
||||
|
||||
print(''' Histogram plotting \n
|
||||
@@ -82,38 +82,38 @@ if __name__ == '__main__':
|
||||
Esc - exit \n
|
||||
''')
|
||||
|
||||
cv2.imshow('image',im)
|
||||
cv.imshow('image',im)
|
||||
while True:
|
||||
k = cv2.waitKey(0)
|
||||
k = cv.waitKey(0)
|
||||
if k == ord('a'):
|
||||
curve = hist_curve(im)
|
||||
cv2.imshow('histogram',curve)
|
||||
cv2.imshow('image',im)
|
||||
cv.imshow('histogram',curve)
|
||||
cv.imshow('image',im)
|
||||
print('a')
|
||||
elif k == ord('b'):
|
||||
print('b')
|
||||
lines = hist_lines(im)
|
||||
cv2.imshow('histogram',lines)
|
||||
cv2.imshow('image',gray)
|
||||
cv.imshow('histogram',lines)
|
||||
cv.imshow('image',gray)
|
||||
elif k == ord('c'):
|
||||
print('c')
|
||||
equ = cv2.equalizeHist(gray)
|
||||
equ = cv.equalizeHist(gray)
|
||||
lines = hist_lines(equ)
|
||||
cv2.imshow('histogram',lines)
|
||||
cv2.imshow('image',equ)
|
||||
cv.imshow('histogram',lines)
|
||||
cv.imshow('image',equ)
|
||||
elif k == ord('d'):
|
||||
print('d')
|
||||
curve = hist_curve(gray)
|
||||
cv2.imshow('histogram',curve)
|
||||
cv2.imshow('image',gray)
|
||||
cv.imshow('histogram',curve)
|
||||
cv.imshow('image',gray)
|
||||
elif k == ord('e'):
|
||||
print('e')
|
||||
norm = cv2.normalize(gray, gray, alpha = 0,beta = 255,norm_type = cv2.NORM_MINMAX)
|
||||
norm = cv.normalize(gray, gray, alpha = 0,beta = 255,norm_type = cv.NORM_MINMAX)
|
||||
lines = hist_lines(norm)
|
||||
cv2.imshow('histogram',lines)
|
||||
cv2.imshow('image',norm)
|
||||
cv.imshow('histogram',lines)
|
||||
cv.imshow('image',norm)
|
||||
elif k == 27:
|
||||
print('ESC')
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
break
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/python
|
||||
|
||||
'''
|
||||
This example illustrates how to use cv2.HoughCircles() function.
|
||||
This example illustrates how to use cv.HoughCircles() function.
|
||||
|
||||
Usage:
|
||||
houghcircles.py [<image_name>]
|
||||
@@ -11,7 +11,7 @@ Usage:
|
||||
# Python 2/3 compatibility
|
||||
from __future__ import print_function
|
||||
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
import numpy as np
|
||||
import sys
|
||||
|
||||
@@ -23,20 +23,20 @@ if __name__ == '__main__':
|
||||
except IndexError:
|
||||
fn = "../data/board.jpg"
|
||||
|
||||
src = cv2.imread(fn, 1)
|
||||
img = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
|
||||
img = cv2.medianBlur(img, 5)
|
||||
src = cv.imread(fn, 1)
|
||||
img = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
|
||||
img = cv.medianBlur(img, 5)
|
||||
cimg = src.copy() # numpy function
|
||||
|
||||
circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 10, np.array([]), 100, 30, 1, 30)
|
||||
circles = cv.HoughCircles(img, cv.HOUGH_GRADIENT, 1, 10, np.array([]), 100, 30, 1, 30)
|
||||
|
||||
if circles is not None: # Check if circles have been found and only then iterate over these and add them to the image
|
||||
a, b, c = circles.shape
|
||||
for i in range(b):
|
||||
cv2.circle(cimg, (circles[0][i][0], circles[0][i][1]), circles[0][i][2], (0, 0, 255), 3, cv2.LINE_AA)
|
||||
cv2.circle(cimg, (circles[0][i][0], circles[0][i][1]), 2, (0, 255, 0), 3, cv2.LINE_AA) # draw center of circle
|
||||
cv.circle(cimg, (circles[0][i][0], circles[0][i][1]), circles[0][i][2], (0, 0, 255), 3, cv.LINE_AA)
|
||||
cv.circle(cimg, (circles[0][i][0], circles[0][i][1]), 2, (0, 255, 0), 3, cv.LINE_AA) # draw center of circle
|
||||
|
||||
cv2.imshow("detected circles", cimg)
|
||||
cv.imshow("detected circles", cimg)
|
||||
|
||||
cv2.imshow("source", src)
|
||||
cv2.waitKey(0)
|
||||
cv.imshow("source", src)
|
||||
cv.waitKey(0)
|
||||
|
||||
@@ -11,7 +11,7 @@ Usage:
|
||||
# Python 2/3 compatibility
|
||||
from __future__ import print_function
|
||||
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
import numpy as np
|
||||
import sys
|
||||
import math
|
||||
@@ -24,18 +24,18 @@ if __name__ == '__main__':
|
||||
except IndexError:
|
||||
fn = "../data/pic1.png"
|
||||
|
||||
src = cv2.imread(fn)
|
||||
dst = cv2.Canny(src, 50, 200)
|
||||
cdst = cv2.cvtColor(dst, cv2.COLOR_GRAY2BGR)
|
||||
src = cv.imread(fn)
|
||||
dst = cv.Canny(src, 50, 200)
|
||||
cdst = cv.cvtColor(dst, cv.COLOR_GRAY2BGR)
|
||||
|
||||
if True: # HoughLinesP
|
||||
lines = cv2.HoughLinesP(dst, 1, math.pi/180.0, 40, np.array([]), 50, 10)
|
||||
lines = cv.HoughLinesP(dst, 1, math.pi/180.0, 40, np.array([]), 50, 10)
|
||||
a,b,c = lines.shape
|
||||
for i in range(a):
|
||||
cv2.line(cdst, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (0, 0, 255), 3, cv2.LINE_AA)
|
||||
cv.line(cdst, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (0, 0, 255), 3, cv.LINE_AA)
|
||||
|
||||
else: # HoughLines
|
||||
lines = cv2.HoughLines(dst, 1, math.pi/180.0, 50, np.array([]), 0, 0)
|
||||
lines = cv.HoughLines(dst, 1, math.pi/180.0, 50, np.array([]), 0, 0)
|
||||
if lines is not None:
|
||||
a,b,c = lines.shape
|
||||
for i in range(a):
|
||||
@@ -46,9 +46,9 @@ if __name__ == '__main__':
|
||||
x0, y0 = a*rho, b*rho
|
||||
pt1 = ( int(x0+1000*(-b)), int(y0+1000*(a)) )
|
||||
pt2 = ( int(x0-1000*(-b)), int(y0-1000*(a)) )
|
||||
cv2.line(cdst, pt1, pt2, (0, 0, 255), 3, cv2.LINE_AA)
|
||||
cv.line(cdst, pt1, pt2, (0, 0, 255), 3, cv.LINE_AA)
|
||||
|
||||
cv2.imshow("detected lines", cdst)
|
||||
cv.imshow("detected lines", cdst)
|
||||
|
||||
cv2.imshow("source", src)
|
||||
cv2.waitKey(0)
|
||||
cv.imshow("source", src)
|
||||
cv.waitKey(0)
|
||||
|
||||
@@ -19,7 +19,7 @@ Keys:
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
from common import Sketcher
|
||||
|
||||
if __name__ == '__main__':
|
||||
@@ -31,7 +31,7 @@ if __name__ == '__main__':
|
||||
|
||||
print(__doc__)
|
||||
|
||||
img = cv2.imread(fn)
|
||||
img = cv.imread(fn)
|
||||
if img is None:
|
||||
print('Failed to load image file:', fn)
|
||||
sys.exit(1)
|
||||
@@ -41,14 +41,14 @@ if __name__ == '__main__':
|
||||
sketch = Sketcher('img', [img_mark, mark], lambda : ((255, 255, 255), 255))
|
||||
|
||||
while True:
|
||||
ch = cv2.waitKey()
|
||||
ch = cv.waitKey()
|
||||
if ch == 27:
|
||||
break
|
||||
if ch == ord(' '):
|
||||
res = cv2.inpaint(img_mark, mark, 3, cv2.INPAINT_TELEA)
|
||||
cv2.imshow('inpaint', res)
|
||||
res = cv.inpaint(img_mark, mark, 3, cv.INPAINT_TELEA)
|
||||
cv.imshow('inpaint', res)
|
||||
if ch == ord('r'):
|
||||
img_mark[:] = img
|
||||
mark[:] = 0
|
||||
sketch.show()
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
+12
-12
@@ -18,7 +18,7 @@ PY3 = sys.version_info[0] == 3
|
||||
if PY3:
|
||||
long = int
|
||||
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
from math import cos, sin, sqrt
|
||||
import numpy as np
|
||||
|
||||
@@ -26,11 +26,11 @@ if __name__ == "__main__":
|
||||
|
||||
img_height = 500
|
||||
img_width = 500
|
||||
kalman = cv2.KalmanFilter(2, 1, 0)
|
||||
kalman = cv.KalmanFilter(2, 1, 0)
|
||||
|
||||
code = long(-1)
|
||||
|
||||
cv2.namedWindow("Kalman")
|
||||
cv.namedWindow("Kalman")
|
||||
|
||||
while True:
|
||||
state = 0.1 * np.random.randn(2, 1)
|
||||
@@ -64,33 +64,33 @@ if __name__ == "__main__":
|
||||
|
||||
# plot points
|
||||
def draw_cross(center, color, d):
|
||||
cv2.line(img,
|
||||
cv.line(img,
|
||||
(center[0] - d, center[1] - d), (center[0] + d, center[1] + d),
|
||||
color, 1, cv2.LINE_AA, 0)
|
||||
cv2.line(img,
|
||||
color, 1, cv.LINE_AA, 0)
|
||||
cv.line(img,
|
||||
(center[0] + d, center[1] - d), (center[0] - d, center[1] + d),
|
||||
color, 1, cv2.LINE_AA, 0)
|
||||
color, 1, cv.LINE_AA, 0)
|
||||
|
||||
img = np.zeros((img_height, img_width, 3), np.uint8)
|
||||
draw_cross(np.int32(state_pt), (255, 255, 255), 3)
|
||||
draw_cross(np.int32(measurement_pt), (0, 0, 255), 3)
|
||||
draw_cross(np.int32(predict_pt), (0, 255, 0), 3)
|
||||
|
||||
cv2.line(img, state_pt, measurement_pt, (0, 0, 255), 3, cv2.LINE_AA, 0)
|
||||
cv2.line(img, state_pt, predict_pt, (0, 255, 255), 3, cv2.LINE_AA, 0)
|
||||
cv.line(img, state_pt, measurement_pt, (0, 0, 255), 3, cv.LINE_AA, 0)
|
||||
cv.line(img, state_pt, predict_pt, (0, 255, 255), 3, cv.LINE_AA, 0)
|
||||
|
||||
kalman.correct(measurement)
|
||||
|
||||
process_noise = sqrt(kalman.processNoiseCov[0,0]) * np.random.randn(2, 1)
|
||||
state = np.dot(kalman.transitionMatrix, state) + process_noise
|
||||
|
||||
cv2.imshow("Kalman", img)
|
||||
cv.imshow("Kalman", img)
|
||||
|
||||
code = cv2.waitKey(100)
|
||||
code = cv.waitKey(100)
|
||||
if code != -1:
|
||||
break
|
||||
|
||||
if code in [27, ord('q'), ord('Q')]:
|
||||
break
|
||||
|
||||
cv2.destroyWindow("Kalman")
|
||||
cv.destroyWindow("Kalman")
|
||||
|
||||
@@ -14,7 +14,7 @@ Keyboard shortcuts:
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
from gaussian_mix import make_gaussians
|
||||
|
||||
@@ -28,23 +28,23 @@ if __name__ == '__main__':
|
||||
colors = np.zeros((1, cluster_n, 3), np.uint8)
|
||||
colors[0,:] = 255
|
||||
colors[0,:,0] = np.arange(0, 180, 180.0/cluster_n)
|
||||
colors = cv2.cvtColor(colors, cv2.COLOR_HSV2BGR)[0]
|
||||
colors = cv.cvtColor(colors, cv.COLOR_HSV2BGR)[0]
|
||||
|
||||
while True:
|
||||
print('sampling distributions...')
|
||||
points, _ = make_gaussians(cluster_n, img_size)
|
||||
|
||||
term_crit = (cv2.TERM_CRITERIA_EPS, 30, 0.1)
|
||||
ret, labels, centers = cv2.kmeans(points, cluster_n, None, term_crit, 10, 0)
|
||||
term_crit = (cv.TERM_CRITERIA_EPS, 30, 0.1)
|
||||
ret, labels, centers = cv.kmeans(points, cluster_n, None, term_crit, 10, 0)
|
||||
|
||||
img = np.zeros((img_size, img_size, 3), np.uint8)
|
||||
for (x, y), label in zip(np.int32(points), labels.ravel()):
|
||||
c = list(map(int, colors[label]))
|
||||
|
||||
cv2.circle(img, (x, y), 1, c, -1)
|
||||
cv.circle(img, (x, y), 1, c, -1)
|
||||
|
||||
cv2.imshow('gaussian mixture', img)
|
||||
ch = cv2.waitKey(0)
|
||||
cv.imshow('gaussian mixture', img)
|
||||
ch = cv.waitKey(0)
|
||||
if ch == 27:
|
||||
break
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
@@ -21,7 +21,7 @@ if PY3:
|
||||
xrange = range
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
import video
|
||||
from common import nothing, getsize
|
||||
|
||||
@@ -29,8 +29,8 @@ def build_lappyr(img, leveln=6, dtype=np.int16):
|
||||
img = dtype(img)
|
||||
levels = []
|
||||
for _i in xrange(leveln-1):
|
||||
next_img = cv2.pyrDown(img)
|
||||
img1 = cv2.pyrUp(next_img, dstsize=getsize(img))
|
||||
next_img = cv.pyrDown(img)
|
||||
img1 = cv.pyrUp(next_img, dstsize=getsize(img))
|
||||
levels.append(img-img1)
|
||||
img = next_img
|
||||
levels.append(img)
|
||||
@@ -39,7 +39,7 @@ def build_lappyr(img, leveln=6, dtype=np.int16):
|
||||
def merge_lappyr(levels):
|
||||
img = levels[-1]
|
||||
for lev_img in levels[-2::-1]:
|
||||
img = cv2.pyrUp(img, dstsize=getsize(lev_img))
|
||||
img = cv.pyrUp(img, dstsize=getsize(lev_img))
|
||||
img += lev_img
|
||||
return np.uint8(np.clip(img, 0, 255))
|
||||
|
||||
@@ -55,20 +55,20 @@ if __name__ == '__main__':
|
||||
cap = video.create_capture(fn)
|
||||
|
||||
leveln = 6
|
||||
cv2.namedWindow('level control')
|
||||
cv.namedWindow('level control')
|
||||
for i in xrange(leveln):
|
||||
cv2.createTrackbar('%d'%i, 'level control', 5, 50, nothing)
|
||||
cv.createTrackbar('%d'%i, 'level control', 5, 50, nothing)
|
||||
|
||||
while True:
|
||||
ret, frame = cap.read()
|
||||
|
||||
pyr = build_lappyr(frame, leveln)
|
||||
for i in xrange(leveln):
|
||||
v = int(cv2.getTrackbarPos('%d'%i, 'level control') / 5)
|
||||
v = int(cv.getTrackbarPos('%d'%i, 'level control') / 5)
|
||||
pyr[i] *= v
|
||||
res = merge_lappyr(pyr)
|
||||
|
||||
cv2.imshow('laplacian pyramid filter', res)
|
||||
cv.imshow('laplacian pyramid filter', res)
|
||||
|
||||
if cv2.waitKey(1) == 27:
|
||||
if cv.waitKey(1) == 27:
|
||||
break
|
||||
|
||||
@@ -29,7 +29,7 @@ USAGE:
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
def load_base(fn):
|
||||
a = np.loadtxt(fn, np.float32, delimiter=',', converters={ 0 : lambda ch : ord(ch)-ord('A') })
|
||||
@@ -61,11 +61,11 @@ class LetterStatModel(object):
|
||||
|
||||
class RTrees(LetterStatModel):
|
||||
def __init__(self):
|
||||
self.model = cv2.ml.RTrees_create()
|
||||
self.model = cv.ml.RTrees_create()
|
||||
|
||||
def train(self, samples, responses):
|
||||
self.model.setMaxDepth(20)
|
||||
self.model.train(samples, cv2.ml.ROW_SAMPLE, responses.astype(int))
|
||||
self.model.train(samples, cv.ml.ROW_SAMPLE, responses.astype(int))
|
||||
|
||||
def predict(self, samples):
|
||||
_ret, resp = self.model.predict(samples)
|
||||
@@ -74,10 +74,10 @@ class RTrees(LetterStatModel):
|
||||
|
||||
class KNearest(LetterStatModel):
|
||||
def __init__(self):
|
||||
self.model = cv2.ml.KNearest_create()
|
||||
self.model = cv.ml.KNearest_create()
|
||||
|
||||
def train(self, samples, responses):
|
||||
self.model.train(samples, cv2.ml.ROW_SAMPLE, responses)
|
||||
self.model.train(samples, cv.ml.ROW_SAMPLE, responses)
|
||||
|
||||
def predict(self, samples):
|
||||
_retval, results, _neigh_resp, _dists = self.model.findNearest(samples, k = 10)
|
||||
@@ -86,17 +86,17 @@ class KNearest(LetterStatModel):
|
||||
|
||||
class Boost(LetterStatModel):
|
||||
def __init__(self):
|
||||
self.model = cv2.ml.Boost_create()
|
||||
self.model = cv.ml.Boost_create()
|
||||
|
||||
def train(self, samples, responses):
|
||||
_sample_n, var_n = samples.shape
|
||||
new_samples = self.unroll_samples(samples)
|
||||
new_responses = self.unroll_responses(responses)
|
||||
var_types = np.array([cv2.ml.VAR_NUMERICAL] * var_n + [cv2.ml.VAR_CATEGORICAL, cv2.ml.VAR_CATEGORICAL], np.uint8)
|
||||
var_types = np.array([cv.ml.VAR_NUMERICAL] * var_n + [cv.ml.VAR_CATEGORICAL, cv.ml.VAR_CATEGORICAL], np.uint8)
|
||||
|
||||
self.model.setWeakCount(15)
|
||||
self.model.setMaxDepth(10)
|
||||
self.model.train(cv2.ml.TrainData_create(new_samples, cv2.ml.ROW_SAMPLE, new_responses.astype(int), varType = var_types))
|
||||
self.model.train(cv.ml.TrainData_create(new_samples, cv.ml.ROW_SAMPLE, new_responses.astype(int), varType = var_types))
|
||||
|
||||
def predict(self, samples):
|
||||
new_samples = self.unroll_samples(samples)
|
||||
@@ -107,14 +107,14 @@ class Boost(LetterStatModel):
|
||||
|
||||
class SVM(LetterStatModel):
|
||||
def __init__(self):
|
||||
self.model = cv2.ml.SVM_create()
|
||||
self.model = cv.ml.SVM_create()
|
||||
|
||||
def train(self, samples, responses):
|
||||
self.model.setType(cv2.ml.SVM_C_SVC)
|
||||
self.model.setType(cv.ml.SVM_C_SVC)
|
||||
self.model.setC(1)
|
||||
self.model.setKernel(cv2.ml.SVM_RBF)
|
||||
self.model.setKernel(cv.ml.SVM_RBF)
|
||||
self.model.setGamma(.1)
|
||||
self.model.train(samples, cv2.ml.ROW_SAMPLE, responses.astype(int))
|
||||
self.model.train(samples, cv.ml.ROW_SAMPLE, responses.astype(int))
|
||||
|
||||
def predict(self, samples):
|
||||
_ret, resp = self.model.predict(samples)
|
||||
@@ -123,7 +123,7 @@ class SVM(LetterStatModel):
|
||||
|
||||
class MLP(LetterStatModel):
|
||||
def __init__(self):
|
||||
self.model = cv2.ml.ANN_MLP_create()
|
||||
self.model = cv.ml.ANN_MLP_create()
|
||||
|
||||
def train(self, samples, responses):
|
||||
_sample_n, var_n = samples.shape
|
||||
@@ -131,13 +131,13 @@ class MLP(LetterStatModel):
|
||||
layer_sizes = np.int32([var_n, 100, 100, self.class_n])
|
||||
|
||||
self.model.setLayerSizes(layer_sizes)
|
||||
self.model.setTrainMethod(cv2.ml.ANN_MLP_BACKPROP)
|
||||
self.model.setTrainMethod(cv.ml.ANN_MLP_BACKPROP)
|
||||
self.model.setBackpropMomentumScale(0.0)
|
||||
self.model.setBackpropWeightScale(0.001)
|
||||
self.model.setTermCriteria((cv2.TERM_CRITERIA_COUNT, 20, 0.01))
|
||||
self.model.setActivationFunction(cv2.ml.ANN_MLP_SIGMOID_SYM, 2, 1)
|
||||
self.model.setTermCriteria((cv.TERM_CRITERIA_COUNT, 20, 0.01))
|
||||
self.model.setActivationFunction(cv.ml.ANN_MLP_SIGMOID_SYM, 2, 1)
|
||||
|
||||
self.model.train(samples, cv2.ml.ROW_SAMPLE, np.float32(new_responses))
|
||||
self.model.train(samples, cv.ml.ROW_SAMPLE, np.float32(new_responses))
|
||||
|
||||
def predict(self, samples):
|
||||
_ret, resp = self.model.predict(samples)
|
||||
@@ -184,4 +184,4 @@ if __name__ == '__main__':
|
||||
fn = args['--save']
|
||||
print('saving model to %s ...' % fn)
|
||||
model.save(fn)
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
@@ -24,14 +24,14 @@ r - toggle RANSAC
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
import video
|
||||
from common import draw_str
|
||||
from video import presets
|
||||
|
||||
lk_params = dict( winSize = (19, 19),
|
||||
maxLevel = 2,
|
||||
criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))
|
||||
criteria = (cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10, 0.03))
|
||||
|
||||
feature_params = dict( maxCorners = 1000,
|
||||
qualityLevel = 0.01,
|
||||
@@ -39,8 +39,8 @@ feature_params = dict( maxCorners = 1000,
|
||||
blockSize = 19 )
|
||||
|
||||
def checkedTrace(img0, img1, p0, back_threshold = 1.0):
|
||||
p1, _st, _err = cv2.calcOpticalFlowPyrLK(img0, img1, p0, None, **lk_params)
|
||||
p0r, _st, _err = cv2.calcOpticalFlowPyrLK(img1, img0, p1, None, **lk_params)
|
||||
p1, _st, _err = cv.calcOpticalFlowPyrLK(img0, img1, p0, None, **lk_params)
|
||||
p0r, _st, _err = cv.calcOpticalFlowPyrLK(img1, img0, p1, None, **lk_params)
|
||||
d = abs(p0-p0r).reshape(-1, 2).max(-1)
|
||||
status = d < back_threshold
|
||||
return p1, status
|
||||
@@ -57,7 +57,7 @@ class App:
|
||||
def run(self):
|
||||
while True:
|
||||
_ret, frame = self.cam.read()
|
||||
frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
||||
frame_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
|
||||
vis = frame.copy()
|
||||
if self.p0 is not None:
|
||||
p2, trace_status = checkedTrace(self.gray1, frame_gray, self.p1)
|
||||
@@ -69,33 +69,33 @@ class App:
|
||||
if len(self.p0) < 4:
|
||||
self.p0 = None
|
||||
continue
|
||||
H, status = cv2.findHomography(self.p0, self.p1, (0, cv2.RANSAC)[self.use_ransac], 10.0)
|
||||
H, status = cv.findHomography(self.p0, self.p1, (0, cv.RANSAC)[self.use_ransac], 10.0)
|
||||
h, w = frame.shape[:2]
|
||||
overlay = cv2.warpPerspective(self.frame0, H, (w, h))
|
||||
vis = cv2.addWeighted(vis, 0.5, overlay, 0.5, 0.0)
|
||||
overlay = cv.warpPerspective(self.frame0, H, (w, h))
|
||||
vis = cv.addWeighted(vis, 0.5, overlay, 0.5, 0.0)
|
||||
|
||||
for (x0, y0), (x1, y1), good in zip(self.p0[:,0], self.p1[:,0], status[:,0]):
|
||||
if good:
|
||||
cv2.line(vis, (x0, y0), (x1, y1), (0, 128, 0))
|
||||
cv2.circle(vis, (x1, y1), 2, (red, green)[good], -1)
|
||||
cv.line(vis, (x0, y0), (x1, y1), (0, 128, 0))
|
||||
cv.circle(vis, (x1, y1), 2, (red, green)[good], -1)
|
||||
draw_str(vis, (20, 20), 'track count: %d' % len(self.p1))
|
||||
if self.use_ransac:
|
||||
draw_str(vis, (20, 40), 'RANSAC')
|
||||
else:
|
||||
p = cv2.goodFeaturesToTrack(frame_gray, **feature_params)
|
||||
p = cv.goodFeaturesToTrack(frame_gray, **feature_params)
|
||||
if p is not None:
|
||||
for x, y in p[:,0]:
|
||||
cv2.circle(vis, (x, y), 2, green, -1)
|
||||
cv.circle(vis, (x, y), 2, green, -1)
|
||||
draw_str(vis, (20, 20), 'feature count: %d' % len(p))
|
||||
|
||||
cv2.imshow('lk_homography', vis)
|
||||
cv.imshow('lk_homography', vis)
|
||||
|
||||
ch = cv2.waitKey(1)
|
||||
ch = cv.waitKey(1)
|
||||
if ch == 27:
|
||||
break
|
||||
if ch == ord(' '):
|
||||
self.frame0 = frame.copy()
|
||||
self.p0 = cv2.goodFeaturesToTrack(frame_gray, **feature_params)
|
||||
self.p0 = cv.goodFeaturesToTrack(frame_gray, **feature_params)
|
||||
if self.p0 is not None:
|
||||
self.p1 = self.p0
|
||||
self.gray0 = frame_gray
|
||||
@@ -114,7 +114,7 @@ def main():
|
||||
|
||||
print(__doc__)
|
||||
App(video_src).run()
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
+12
-12
@@ -22,14 +22,14 @@ ESC - exit
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
import video
|
||||
from common import anorm2, draw_str
|
||||
from time import clock
|
||||
|
||||
lk_params = dict( winSize = (15, 15),
|
||||
maxLevel = 2,
|
||||
criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))
|
||||
criteria = (cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10, 0.03))
|
||||
|
||||
feature_params = dict( maxCorners = 500,
|
||||
qualityLevel = 0.3,
|
||||
@@ -47,14 +47,14 @@ class App:
|
||||
def run(self):
|
||||
while True:
|
||||
_ret, frame = self.cam.read()
|
||||
frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
||||
frame_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
|
||||
vis = frame.copy()
|
||||
|
||||
if len(self.tracks) > 0:
|
||||
img0, img1 = self.prev_gray, frame_gray
|
||||
p0 = np.float32([tr[-1] for tr in self.tracks]).reshape(-1, 1, 2)
|
||||
p1, _st, _err = cv2.calcOpticalFlowPyrLK(img0, img1, p0, None, **lk_params)
|
||||
p0r, _st, _err = cv2.calcOpticalFlowPyrLK(img1, img0, p1, None, **lk_params)
|
||||
p1, _st, _err = cv.calcOpticalFlowPyrLK(img0, img1, p0, None, **lk_params)
|
||||
p0r, _st, _err = cv.calcOpticalFlowPyrLK(img1, img0, p1, None, **lk_params)
|
||||
d = abs(p0-p0r).reshape(-1, 2).max(-1)
|
||||
good = d < 1
|
||||
new_tracks = []
|
||||
@@ -65,17 +65,17 @@ class App:
|
||||
if len(tr) > self.track_len:
|
||||
del tr[0]
|
||||
new_tracks.append(tr)
|
||||
cv2.circle(vis, (x, y), 2, (0, 255, 0), -1)
|
||||
cv.circle(vis, (x, y), 2, (0, 255, 0), -1)
|
||||
self.tracks = new_tracks
|
||||
cv2.polylines(vis, [np.int32(tr) for tr in self.tracks], False, (0, 255, 0))
|
||||
cv.polylines(vis, [np.int32(tr) for tr in self.tracks], False, (0, 255, 0))
|
||||
draw_str(vis, (20, 20), 'track count: %d' % len(self.tracks))
|
||||
|
||||
if self.frame_idx % self.detect_interval == 0:
|
||||
mask = np.zeros_like(frame_gray)
|
||||
mask[:] = 255
|
||||
for x, y in [np.int32(tr[-1]) for tr in self.tracks]:
|
||||
cv2.circle(mask, (x, y), 5, 0, -1)
|
||||
p = cv2.goodFeaturesToTrack(frame_gray, mask = mask, **feature_params)
|
||||
cv.circle(mask, (x, y), 5, 0, -1)
|
||||
p = cv.goodFeaturesToTrack(frame_gray, mask = mask, **feature_params)
|
||||
if p is not None:
|
||||
for x, y in np.float32(p).reshape(-1, 2):
|
||||
self.tracks.append([(x, y)])
|
||||
@@ -83,9 +83,9 @@ class App:
|
||||
|
||||
self.frame_idx += 1
|
||||
self.prev_gray = frame_gray
|
||||
cv2.imshow('lk_track', vis)
|
||||
cv.imshow('lk_track', vis)
|
||||
|
||||
ch = cv2.waitKey(1)
|
||||
ch = cv.waitKey(1)
|
||||
if ch == 27:
|
||||
break
|
||||
|
||||
@@ -98,7 +98,7 @@ def main():
|
||||
|
||||
print(__doc__)
|
||||
App(video_src).run()
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
@@ -13,7 +13,7 @@ Keys:
|
||||
# Python 2/3 compatibility
|
||||
from __future__ import print_function
|
||||
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
if __name__ == '__main__':
|
||||
print(__doc__)
|
||||
@@ -24,16 +24,16 @@ if __name__ == '__main__':
|
||||
except IndexError:
|
||||
fn = '../data/fruits.jpg'
|
||||
|
||||
img = cv2.imread(fn)
|
||||
img = cv.imread(fn)
|
||||
if img is None:
|
||||
print('Failed to load image file:', fn)
|
||||
sys.exit(1)
|
||||
|
||||
img2 = cv2.logPolar(img, (img.shape[0]/2, img.shape[1]/2), 40, cv2.WARP_FILL_OUTLIERS)
|
||||
img3 = cv2.linearPolar(img, (img.shape[0]/2, img.shape[1]/2), 40, cv2.WARP_FILL_OUTLIERS)
|
||||
img2 = cv.logPolar(img, (img.shape[0]/2, img.shape[1]/2), 40, cv.WARP_FILL_OUTLIERS)
|
||||
img3 = cv.linearPolar(img, (img.shape[0]/2, img.shape[1]/2), 40, cv.WARP_FILL_OUTLIERS)
|
||||
|
||||
cv2.imshow('before', img)
|
||||
cv2.imshow('logpolar', img2)
|
||||
cv2.imshow('linearpolar', img3)
|
||||
cv.imshow('before', img)
|
||||
cv.imshow('logpolar', img2)
|
||||
cv.imshow('linearpolar', img3)
|
||||
|
||||
cv2.waitKey(0)
|
||||
cv.waitKey(0)
|
||||
|
||||
@@ -18,7 +18,7 @@ import sys
|
||||
PY3 = sys.version_info[0] == 3
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
@@ -33,13 +33,13 @@ if __name__ == '__main__':
|
||||
except:
|
||||
fn = '../data/baboon.jpg'
|
||||
|
||||
img = cv2.imread(fn)
|
||||
img = cv.imread(fn)
|
||||
|
||||
if img is None:
|
||||
print('Failed to load image file:', fn)
|
||||
sys.exit(1)
|
||||
|
||||
cv2.imshow('original', img)
|
||||
cv.imshow('original', img)
|
||||
|
||||
modes = cycle(['erode/dilate', 'open/close', 'blackhat/tophat', 'gradient'])
|
||||
str_modes = cycle(['ellipse', 'rect', 'cross'])
|
||||
@@ -52,8 +52,8 @@ if __name__ == '__main__':
|
||||
cur_str_mode = str_modes.next()
|
||||
|
||||
def update(dummy=None):
|
||||
sz = cv2.getTrackbarPos('op/size', 'morphology')
|
||||
iters = cv2.getTrackbarPos('iters', 'morphology')
|
||||
sz = cv.getTrackbarPos('op/size', 'morphology')
|
||||
iters = cv.getTrackbarPos('iters', 'morphology')
|
||||
opers = cur_mode.split('/')
|
||||
if len(opers) > 1:
|
||||
sz = sz - 10
|
||||
@@ -65,21 +65,21 @@ if __name__ == '__main__':
|
||||
|
||||
str_name = 'MORPH_' + cur_str_mode.upper()
|
||||
oper_name = 'MORPH_' + op.upper()
|
||||
st = cv2.getStructuringElement(getattr(cv2, str_name), (sz, sz))
|
||||
res = cv2.morphologyEx(img, getattr(cv2, oper_name), st, iterations=iters)
|
||||
st = cv.getStructuringElement(getattr(cv, str_name), (sz, sz))
|
||||
res = cv.morphologyEx(img, getattr(cv, oper_name), st, iterations=iters)
|
||||
|
||||
draw_str(res, (10, 20), 'mode: ' + cur_mode)
|
||||
draw_str(res, (10, 40), 'operation: ' + oper_name)
|
||||
draw_str(res, (10, 60), 'structure: ' + str_name)
|
||||
draw_str(res, (10, 80), 'ksize: %d iters: %d' % (sz, iters))
|
||||
cv2.imshow('morphology', res)
|
||||
cv.imshow('morphology', res)
|
||||
|
||||
cv2.namedWindow('morphology')
|
||||
cv2.createTrackbar('op/size', 'morphology', 12, 20, update)
|
||||
cv2.createTrackbar('iters', 'morphology', 1, 10, update)
|
||||
cv.namedWindow('morphology')
|
||||
cv.createTrackbar('op/size', 'morphology', 12, 20, update)
|
||||
cv.createTrackbar('iters', 'morphology', 1, 10, update)
|
||||
update()
|
||||
while True:
|
||||
ch = cv2.waitKey()
|
||||
ch = cv.waitKey()
|
||||
if ch == 27:
|
||||
break
|
||||
if ch == ord('1'):
|
||||
@@ -93,4 +93,4 @@ if __name__ == '__main__':
|
||||
else:
|
||||
cur_str_mode = str_modes.next()
|
||||
update()
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
+30
-30
@@ -30,7 +30,7 @@ if PY3:
|
||||
xrange = range
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
from common import draw_str, RectSelector
|
||||
import video
|
||||
|
||||
@@ -44,7 +44,7 @@ def rnd_warp(a):
|
||||
T[:2, :2] += (np.random.rand(2, 2) - 0.5)*coef
|
||||
c = (w/2, h/2)
|
||||
T[:,2] = c - np.dot(T[:2, :2], c)
|
||||
return cv2.warpAffine(a, T, (w, h), borderMode = cv2.BORDER_REFLECT)
|
||||
return cv.warpAffine(a, T, (w, h), borderMode = cv.BORDER_REFLECT)
|
||||
|
||||
def divSpec(A, B):
|
||||
Ar, Ai = A[...,0], A[...,1]
|
||||
@@ -58,32 +58,32 @@ eps = 1e-5
|
||||
class MOSSE:
|
||||
def __init__(self, frame, rect):
|
||||
x1, y1, x2, y2 = rect
|
||||
w, h = map(cv2.getOptimalDFTSize, [x2-x1, y2-y1])
|
||||
w, h = map(cv.getOptimalDFTSize, [x2-x1, y2-y1])
|
||||
x1, y1 = (x1+x2-w)//2, (y1+y2-h)//2
|
||||
self.pos = x, y = x1+0.5*(w-1), y1+0.5*(h-1)
|
||||
self.size = w, h
|
||||
img = cv2.getRectSubPix(frame, (w, h), (x, y))
|
||||
img = cv.getRectSubPix(frame, (w, h), (x, y))
|
||||
|
||||
self.win = cv2.createHanningWindow((w, h), cv2.CV_32F)
|
||||
self.win = cv.createHanningWindow((w, h), cv.CV_32F)
|
||||
g = np.zeros((h, w), np.float32)
|
||||
g[h//2, w//2] = 1
|
||||
g = cv2.GaussianBlur(g, (-1, -1), 2.0)
|
||||
g = cv.GaussianBlur(g, (-1, -1), 2.0)
|
||||
g /= g.max()
|
||||
|
||||
self.G = cv2.dft(g, flags=cv2.DFT_COMPLEX_OUTPUT)
|
||||
self.G = cv.dft(g, flags=cv.DFT_COMPLEX_OUTPUT)
|
||||
self.H1 = np.zeros_like(self.G)
|
||||
self.H2 = np.zeros_like(self.G)
|
||||
for _i in xrange(128):
|
||||
a = self.preprocess(rnd_warp(img))
|
||||
A = cv2.dft(a, flags=cv2.DFT_COMPLEX_OUTPUT)
|
||||
self.H1 += cv2.mulSpectrums(self.G, A, 0, conjB=True)
|
||||
self.H2 += cv2.mulSpectrums( A, A, 0, conjB=True)
|
||||
A = cv.dft(a, flags=cv.DFT_COMPLEX_OUTPUT)
|
||||
self.H1 += cv.mulSpectrums(self.G, A, 0, conjB=True)
|
||||
self.H2 += cv.mulSpectrums( A, A, 0, conjB=True)
|
||||
self.update_kernel()
|
||||
self.update(frame)
|
||||
|
||||
def update(self, frame, rate = 0.125):
|
||||
(x, y), (w, h) = self.pos, self.size
|
||||
self.last_img = img = cv2.getRectSubPix(frame, (w, h), (x, y))
|
||||
self.last_img = img = cv.getRectSubPix(frame, (w, h), (x, y))
|
||||
img = self.preprocess(img)
|
||||
self.last_resp, (dx, dy), self.psr = self.correlate(img)
|
||||
self.good = self.psr > 8.0
|
||||
@@ -91,19 +91,19 @@ class MOSSE:
|
||||
return
|
||||
|
||||
self.pos = x+dx, y+dy
|
||||
self.last_img = img = cv2.getRectSubPix(frame, (w, h), self.pos)
|
||||
self.last_img = img = cv.getRectSubPix(frame, (w, h), self.pos)
|
||||
img = self.preprocess(img)
|
||||
|
||||
A = cv2.dft(img, flags=cv2.DFT_COMPLEX_OUTPUT)
|
||||
H1 = cv2.mulSpectrums(self.G, A, 0, conjB=True)
|
||||
H2 = cv2.mulSpectrums( A, A, 0, conjB=True)
|
||||
A = cv.dft(img, flags=cv.DFT_COMPLEX_OUTPUT)
|
||||
H1 = cv.mulSpectrums(self.G, A, 0, conjB=True)
|
||||
H2 = cv.mulSpectrums( A, A, 0, conjB=True)
|
||||
self.H1 = self.H1 * (1.0-rate) + H1 * rate
|
||||
self.H2 = self.H2 * (1.0-rate) + H2 * rate
|
||||
self.update_kernel()
|
||||
|
||||
@property
|
||||
def state_vis(self):
|
||||
f = cv2.idft(self.H, flags=cv2.DFT_SCALE | cv2.DFT_REAL_OUTPUT )
|
||||
f = cv.idft(self.H, flags=cv.DFT_SCALE | cv.DFT_REAL_OUTPUT )
|
||||
h, w = f.shape
|
||||
f = np.roll(f, -h//2, 0)
|
||||
f = np.roll(f, -w//2, 1)
|
||||
@@ -116,12 +116,12 @@ class MOSSE:
|
||||
def draw_state(self, vis):
|
||||
(x, y), (w, h) = self.pos, self.size
|
||||
x1, y1, x2, y2 = int(x-0.5*w), int(y-0.5*h), int(x+0.5*w), int(y+0.5*h)
|
||||
cv2.rectangle(vis, (x1, y1), (x2, y2), (0, 0, 255))
|
||||
cv.rectangle(vis, (x1, y1), (x2, y2), (0, 0, 255))
|
||||
if self.good:
|
||||
cv2.circle(vis, (int(x), int(y)), 2, (0, 0, 255), -1)
|
||||
cv.circle(vis, (int(x), int(y)), 2, (0, 0, 255), -1)
|
||||
else:
|
||||
cv2.line(vis, (x1, y1), (x2, y2), (0, 0, 255))
|
||||
cv2.line(vis, (x2, y1), (x1, y2), (0, 0, 255))
|
||||
cv.line(vis, (x1, y1), (x2, y2), (0, 0, 255))
|
||||
cv.line(vis, (x2, y1), (x1, y2), (0, 0, 255))
|
||||
draw_str(vis, (x1, y2+16), 'PSR: %.2f' % self.psr)
|
||||
|
||||
def preprocess(self, img):
|
||||
@@ -130,12 +130,12 @@ class MOSSE:
|
||||
return img*self.win
|
||||
|
||||
def correlate(self, img):
|
||||
C = cv2.mulSpectrums(cv2.dft(img, flags=cv2.DFT_COMPLEX_OUTPUT), self.H, 0, conjB=True)
|
||||
resp = cv2.idft(C, flags=cv2.DFT_SCALE | cv2.DFT_REAL_OUTPUT)
|
||||
C = cv.mulSpectrums(cv.dft(img, flags=cv.DFT_COMPLEX_OUTPUT), self.H, 0, conjB=True)
|
||||
resp = cv.idft(C, flags=cv.DFT_SCALE | cv.DFT_REAL_OUTPUT)
|
||||
h, w = resp.shape
|
||||
_, mval, _, (mx, my) = cv2.minMaxLoc(resp)
|
||||
_, mval, _, (mx, my) = cv.minMaxLoc(resp)
|
||||
side_resp = resp.copy()
|
||||
cv2.rectangle(side_resp, (mx-5, my-5), (mx+5, my+5), 0, -1)
|
||||
cv.rectangle(side_resp, (mx-5, my-5), (mx+5, my+5), 0, -1)
|
||||
smean, sstd = side_resp.mean(), side_resp.std()
|
||||
psr = (mval-smean) / (sstd+eps)
|
||||
return resp, (mx-w//2, my-h//2), psr
|
||||
@@ -148,13 +148,13 @@ class App:
|
||||
def __init__(self, video_src, paused = False):
|
||||
self.cap = video.create_capture(video_src)
|
||||
_, self.frame = self.cap.read()
|
||||
cv2.imshow('frame', self.frame)
|
||||
cv.imshow('frame', self.frame)
|
||||
self.rect_sel = RectSelector('frame', self.onrect)
|
||||
self.trackers = []
|
||||
self.paused = paused
|
||||
|
||||
def onrect(self, rect):
|
||||
frame_gray = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY)
|
||||
frame_gray = cv.cvtColor(self.frame, cv.COLOR_BGR2GRAY)
|
||||
tracker = MOSSE(frame_gray, rect)
|
||||
self.trackers.append(tracker)
|
||||
|
||||
@@ -164,7 +164,7 @@ class App:
|
||||
ret, self.frame = self.cap.read()
|
||||
if not ret:
|
||||
break
|
||||
frame_gray = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY)
|
||||
frame_gray = cv.cvtColor(self.frame, cv.COLOR_BGR2GRAY)
|
||||
for tracker in self.trackers:
|
||||
tracker.update(frame_gray)
|
||||
|
||||
@@ -172,11 +172,11 @@ class App:
|
||||
for tracker in self.trackers:
|
||||
tracker.draw_state(vis)
|
||||
if len(self.trackers) > 0:
|
||||
cv2.imshow('tracker state', self.trackers[-1].state_vis)
|
||||
cv.imshow('tracker state', self.trackers[-1].state_vis)
|
||||
self.rect_sel.draw(vis)
|
||||
|
||||
cv2.imshow('frame', vis)
|
||||
ch = cv2.waitKey(10)
|
||||
cv.imshow('frame', vis)
|
||||
ch = cv.waitKey(10)
|
||||
if ch == 27:
|
||||
break
|
||||
if ch == ord(' '):
|
||||
|
||||
@@ -15,7 +15,7 @@ Demonstrate using a mouse to interact with an image:
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
# built-in modules
|
||||
import os
|
||||
@@ -30,27 +30,27 @@ sel = (0,0,0,0)
|
||||
|
||||
def onmouse(event, x, y, flags, param):
|
||||
global drag_start, sel
|
||||
if event == cv2.EVENT_LBUTTONDOWN:
|
||||
if event == cv.EVENT_LBUTTONDOWN:
|
||||
drag_start = x, y
|
||||
sel = 0,0,0,0
|
||||
elif event == cv2.EVENT_LBUTTONUP:
|
||||
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 = cv2.matchTemplate(gray,patch,cv2.TM_CCOEFF_NORMED)
|
||||
result = cv.matchTemplate(gray,patch,cv.TM_CCOEFF_NORMED)
|
||||
result = np.abs(result)**3
|
||||
_val, result = cv2.threshold(result, 0.01, 0, cv2.THRESH_TOZERO)
|
||||
result8 = cv2.normalize(result,None,0,255,cv2.NORM_MINMAX,cv2.CV_8U)
|
||||
cv2.imshow("result", result8)
|
||||
_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 & cv2.EVENT_FLAG_LBUTTON:
|
||||
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 = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
|
||||
cv2.rectangle(img, (sel[0], sel[1]), (sel[2], sel[3]), (0,255,255), 1)
|
||||
cv2.imshow("gray", img)
|
||||
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
|
||||
@@ -63,21 +63,21 @@ if __name__ == '__main__':
|
||||
args = parser.parse_args()
|
||||
path = args.input
|
||||
|
||||
cv2.namedWindow("gray",1)
|
||||
cv2.setMouseCallback("gray", onmouse)
|
||||
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 extenstion
|
||||
if ext == "png" or ext == "jpg" or ext == "bmp" or ext == "tiff" or ext == "pbm":
|
||||
print(infile)
|
||||
|
||||
img=cv2.imread(infile,1)
|
||||
img=cv.imread(infile,1)
|
||||
if img is None:
|
||||
continue
|
||||
sel = (0,0,0,0)
|
||||
drag_start = None
|
||||
gray=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||
cv2.imshow("gray",gray)
|
||||
if cv2.waitKey() == 27:
|
||||
gray=cv.cvtColor(img, cv.COLOR_BGR2GRAY)
|
||||
cv.imshow("gray",gray)
|
||||
if cv.waitKey() == 27:
|
||||
break
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
@@ -15,7 +15,7 @@ Keys:
|
||||
'''
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
import video
|
||||
import sys
|
||||
|
||||
@@ -26,20 +26,20 @@ if __name__ == '__main__':
|
||||
video_src = 0
|
||||
|
||||
cam = video.create_capture(video_src)
|
||||
mser = cv2.MSER_create()
|
||||
mser = cv.MSER_create()
|
||||
|
||||
while True:
|
||||
ret, img = cam.read()
|
||||
if ret == 0:
|
||||
break
|
||||
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
|
||||
vis = img.copy()
|
||||
|
||||
regions, _ = mser.detectRegions(gray)
|
||||
hulls = [cv2.convexHull(p.reshape(-1, 1, 2)) for p in regions]
|
||||
cv2.polylines(vis, hulls, 1, (0, 255, 0))
|
||||
hulls = [cv.convexHull(p.reshape(-1, 1, 2)) for p in regions]
|
||||
cv.polylines(vis, hulls, 1, (0, 255, 0))
|
||||
|
||||
cv2.imshow('img', vis)
|
||||
if cv2.waitKey(5) == 27:
|
||||
cv.imshow('img', vis)
|
||||
if cv.waitKey(5) == 27:
|
||||
break
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
@@ -13,7 +13,7 @@ Usage:
|
||||
# Python 2/3 compatibility
|
||||
from __future__ import print_function
|
||||
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
if __name__ == '__main__':
|
||||
import sys
|
||||
@@ -25,7 +25,7 @@ if __name__ == '__main__':
|
||||
param = ""
|
||||
|
||||
if "--build" == param:
|
||||
print(cv2.getBuildInformation())
|
||||
print(cv.getBuildInformation())
|
||||
elif "--help" == param:
|
||||
print("\t--build\n\t\tprint complete build info")
|
||||
print("\t--help\n\t\tprint this help")
|
||||
|
||||
+14
-14
@@ -17,7 +17,7 @@ Keys:
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
import video
|
||||
|
||||
|
||||
@@ -27,10 +27,10 @@ def draw_flow(img, flow, step=16):
|
||||
fx, fy = flow[y,x].T
|
||||
lines = np.vstack([x, y, x+fx, y+fy]).T.reshape(-1, 2, 2)
|
||||
lines = np.int32(lines + 0.5)
|
||||
vis = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
|
||||
cv2.polylines(vis, lines, 0, (0, 255, 0))
|
||||
vis = cv.cvtColor(img, cv.COLOR_GRAY2BGR)
|
||||
cv.polylines(vis, lines, 0, (0, 255, 0))
|
||||
for (x1, y1), (_x2, _y2) in lines:
|
||||
cv2.circle(vis, (x1, y1), 1, (0, 255, 0), -1)
|
||||
cv.circle(vis, (x1, y1), 1, (0, 255, 0), -1)
|
||||
return vis
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@ def draw_hsv(flow):
|
||||
hsv[...,0] = ang*(180/np.pi/2)
|
||||
hsv[...,1] = 255
|
||||
hsv[...,2] = np.minimum(v*4, 255)
|
||||
bgr = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
|
||||
bgr = cv.cvtColor(hsv, cv.COLOR_HSV2BGR)
|
||||
return bgr
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ def warp_flow(img, flow):
|
||||
flow = -flow
|
||||
flow[:,:,0] += np.arange(w)
|
||||
flow[:,:,1] += np.arange(h)[:,np.newaxis]
|
||||
res = cv2.remap(img, flow, None, cv2.INTER_LINEAR)
|
||||
res = cv.remap(img, flow, None, cv.INTER_LINEAR)
|
||||
return res
|
||||
|
||||
if __name__ == '__main__':
|
||||
@@ -65,25 +65,25 @@ if __name__ == '__main__':
|
||||
|
||||
cam = video.create_capture(fn)
|
||||
ret, prev = cam.read()
|
||||
prevgray = cv2.cvtColor(prev, cv2.COLOR_BGR2GRAY)
|
||||
prevgray = cv.cvtColor(prev, cv.COLOR_BGR2GRAY)
|
||||
show_hsv = False
|
||||
show_glitch = False
|
||||
cur_glitch = prev.copy()
|
||||
|
||||
while True:
|
||||
ret, img = cam.read()
|
||||
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||
flow = cv2.calcOpticalFlowFarneback(prevgray, gray, None, 0.5, 3, 15, 3, 5, 1.2, 0)
|
||||
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
|
||||
flow = cv.calcOpticalFlowFarneback(prevgray, gray, None, 0.5, 3, 15, 3, 5, 1.2, 0)
|
||||
prevgray = gray
|
||||
|
||||
cv2.imshow('flow', draw_flow(gray, flow))
|
||||
cv.imshow('flow', draw_flow(gray, flow))
|
||||
if show_hsv:
|
||||
cv2.imshow('flow HSV', draw_hsv(flow))
|
||||
cv.imshow('flow HSV', draw_hsv(flow))
|
||||
if show_glitch:
|
||||
cur_glitch = warp_flow(cur_glitch, flow)
|
||||
cv2.imshow('glitch', cur_glitch)
|
||||
cv.imshow('glitch', cur_glitch)
|
||||
|
||||
ch = cv2.waitKey(5)
|
||||
ch = cv.waitKey(5)
|
||||
if ch == 27:
|
||||
break
|
||||
if ch == ord('1'):
|
||||
@@ -94,4 +94,4 @@ if __name__ == '__main__':
|
||||
if show_glitch:
|
||||
cur_glitch = img.copy()
|
||||
print('glitch is', ['off', 'on'][show_glitch])
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
@@ -13,7 +13,7 @@ Press any key to continue, ESC to stop.
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
|
||||
def inside(r, q):
|
||||
@@ -27,7 +27,7 @@ def draw_detections(img, rects, thickness = 1):
|
||||
# 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)
|
||||
cv2.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__':
|
||||
@@ -37,15 +37,15 @@ if __name__ == '__main__':
|
||||
|
||||
print(__doc__)
|
||||
|
||||
hog = cv2.HOGDescriptor()
|
||||
hog.setSVMDetector( cv2.HOGDescriptor_getDefaultPeopleDetector() )
|
||||
hog = cv.HOGDescriptor()
|
||||
hog.setSVMDetector( cv.HOGDescriptor_getDefaultPeopleDetector() )
|
||||
|
||||
default = ['../data/basketball2.png '] if len(sys.argv[1:]) == 0 else []
|
||||
|
||||
for fn in it.chain(*map(glob, default + sys.argv[1:])):
|
||||
print(fn, ' - ',)
|
||||
try:
|
||||
img = cv2.imread(fn)
|
||||
img = cv.imread(fn)
|
||||
if img is None:
|
||||
print('Failed to load image file:', fn)
|
||||
continue
|
||||
@@ -64,8 +64,8 @@ if __name__ == '__main__':
|
||||
draw_detections(img, found)
|
||||
draw_detections(img, found_filtered, 3)
|
||||
print('%d (%d) found' % (len(found_filtered), len(found)))
|
||||
cv2.imshow('img', img)
|
||||
ch = cv2.waitKey()
|
||||
cv.imshow('img', img)
|
||||
ch = cv.waitKey()
|
||||
if ch == 27:
|
||||
break
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
+11
-11
@@ -26,7 +26,7 @@ Use 'focal' slider to adjust to camera focal length for proper video augmentatio
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
import video
|
||||
import common
|
||||
from plane_tracker import PlaneTracker
|
||||
@@ -48,8 +48,8 @@ class App:
|
||||
self.paused = False
|
||||
self.tracker = PlaneTracker()
|
||||
|
||||
cv2.namedWindow('plane')
|
||||
cv2.createTrackbar('focal', 'plane', 25, 50, common.nothing)
|
||||
cv.namedWindow('plane')
|
||||
cv.createTrackbar('focal', 'plane', 25, 50, common.nothing)
|
||||
self.rect_sel = common.RectSelector('plane', self.on_rect)
|
||||
|
||||
def on_rect(self, rect):
|
||||
@@ -68,14 +68,14 @@ class App:
|
||||
if playing:
|
||||
tracked = self.tracker.track(self.frame)
|
||||
for tr in tracked:
|
||||
cv2.polylines(vis, [np.int32(tr.quad)], True, (255, 255, 255), 2)
|
||||
cv.polylines(vis, [np.int32(tr.quad)], True, (255, 255, 255), 2)
|
||||
for (x, y) in np.int32(tr.p1):
|
||||
cv2.circle(vis, (x, y), 2, (255, 255, 255))
|
||||
cv.circle(vis, (x, y), 2, (255, 255, 255))
|
||||
self.draw_overlay(vis, tr)
|
||||
|
||||
self.rect_sel.draw(vis)
|
||||
cv2.imshow('plane', vis)
|
||||
ch = cv2.waitKey(1)
|
||||
cv.imshow('plane', vis)
|
||||
ch = cv.waitKey(1)
|
||||
if ch == ord(' '):
|
||||
self.paused = not self.paused
|
||||
if ch == ord('c'):
|
||||
@@ -86,18 +86,18 @@ class App:
|
||||
def draw_overlay(self, vis, tracked):
|
||||
x0, y0, x1, y1 = tracked.target.rect
|
||||
quad_3d = np.float32([[x0, y0, 0], [x1, y0, 0], [x1, y1, 0], [x0, y1, 0]])
|
||||
fx = 0.5 + cv2.getTrackbarPos('focal', 'plane') / 50.0
|
||||
fx = 0.5 + cv.getTrackbarPos('focal', 'plane') / 50.0
|
||||
h, w = vis.shape[:2]
|
||||
K = np.float64([[fx*w, 0, 0.5*(w-1)],
|
||||
[0, fx*w, 0.5*(h-1)],
|
||||
[0.0,0.0, 1.0]])
|
||||
dist_coef = np.zeros(4)
|
||||
_ret, rvec, tvec = cv2.solvePnP(quad_3d, tracked.quad, K, dist_coef)
|
||||
_ret, rvec, tvec = cv.solvePnP(quad_3d, tracked.quad, K, dist_coef)
|
||||
verts = ar_verts * [(x1-x0), (y1-y0), -(x1-x0)*0.3] + (x0, y0, 0)
|
||||
verts = cv2.projectPoints(verts, rvec, tvec, K, dist_coef)[0].reshape(-1, 2)
|
||||
verts = cv.projectPoints(verts, rvec, tvec, K, dist_coef)[0].reshape(-1, 2)
|
||||
for i, j in ar_edges:
|
||||
(x0, y0), (x1, y1) = verts[i], verts[j]
|
||||
cv2.line(vis, (int(x0), int(y0)), (int(x1), int(y1)), (255, 255, 0), 2)
|
||||
cv.line(vis, (int(x0), int(y0)), (int(x1), int(y1)), (255, 255, 0), 2)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -30,7 +30,7 @@ if PY3:
|
||||
xrange = range
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
# built-in modules
|
||||
from collections import namedtuple
|
||||
@@ -70,8 +70,8 @@ TrackedTarget = namedtuple('TrackedTarget', 'target, p0, p1, H, quad')
|
||||
|
||||
class PlaneTracker:
|
||||
def __init__(self):
|
||||
self.detector = cv2.ORB_create( nfeatures = 1000 )
|
||||
self.matcher = cv2.FlannBasedMatcher(flann_params, {}) # bug : need to pass empty dict (#1329)
|
||||
self.detector = cv.ORB_create( nfeatures = 1000 )
|
||||
self.matcher = cv.FlannBasedMatcher(flann_params, {}) # bug : need to pass empty dict (#1329)
|
||||
self.targets = []
|
||||
self.frame_points = []
|
||||
|
||||
@@ -115,7 +115,7 @@ class PlaneTracker:
|
||||
p0 = [target.keypoints[m.trainIdx].pt for m in matches]
|
||||
p1 = [self.frame_points[m.queryIdx].pt for m in matches]
|
||||
p0, p1 = np.float32((p0, p1))
|
||||
H, status = cv2.findHomography(p0, p1, cv2.RANSAC, 3.0)
|
||||
H, status = cv.findHomography(p0, p1, cv.RANSAC, 3.0)
|
||||
status = status.ravel() != 0
|
||||
if status.sum() < MIN_MATCH_COUNT:
|
||||
continue
|
||||
@@ -123,7 +123,7 @@ class PlaneTracker:
|
||||
|
||||
x0, y0, x1, y1 = target.rect
|
||||
quad = np.float32([[x0, y0], [x1, y0], [x1, y1], [x0, y1]])
|
||||
quad = cv2.perspectiveTransform(quad.reshape(1, -1, 2), H).reshape(-1, 2)
|
||||
quad = cv.perspectiveTransform(quad.reshape(1, -1, 2), H).reshape(-1, 2)
|
||||
|
||||
track = TrackedTarget(target=target, p0=p0, p1=p1, H=H, quad=quad)
|
||||
tracked.append(track)
|
||||
@@ -145,7 +145,7 @@ class App:
|
||||
self.paused = False
|
||||
self.tracker = PlaneTracker()
|
||||
|
||||
cv2.namedWindow('plane')
|
||||
cv.namedWindow('plane')
|
||||
self.rect_sel = common.RectSelector('plane', self.on_rect)
|
||||
|
||||
def on_rect(self, rect):
|
||||
@@ -164,13 +164,13 @@ class App:
|
||||
if playing:
|
||||
tracked = self.tracker.track(self.frame)
|
||||
for tr in tracked:
|
||||
cv2.polylines(vis, [np.int32(tr.quad)], True, (255, 255, 255), 2)
|
||||
cv.polylines(vis, [np.int32(tr.quad)], True, (255, 255, 255), 2)
|
||||
for (x, y) in np.int32(tr.p1):
|
||||
cv2.circle(vis, (x, y), 2, (255, 255, 255))
|
||||
cv.circle(vis, (x, y), 2, (255, 255, 255))
|
||||
|
||||
self.rect_sel.draw(vis)
|
||||
cv2.imshow('plane', vis)
|
||||
ch = cv2.waitKey(1)
|
||||
cv.imshow('plane', vis)
|
||||
ch = cv.waitKey(1)
|
||||
if ch == ord(' '):
|
||||
self.paused = not self.paused
|
||||
if ch == ord('c'):
|
||||
|
||||
+15
-15
@@ -14,7 +14,7 @@ if PY3:
|
||||
xrange = range
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
|
||||
def angle_cos(p0, p1, p2):
|
||||
@@ -22,20 +22,20 @@ def angle_cos(p0, p1, p2):
|
||||
return abs( np.dot(d1, d2) / np.sqrt( np.dot(d1, d1)*np.dot(d2, d2) ) )
|
||||
|
||||
def find_squares(img):
|
||||
img = cv2.GaussianBlur(img, (5, 5), 0)
|
||||
img = cv.GaussianBlur(img, (5, 5), 0)
|
||||
squares = []
|
||||
for gray in cv2.split(img):
|
||||
for gray in cv.split(img):
|
||||
for thrs in xrange(0, 255, 26):
|
||||
if thrs == 0:
|
||||
bin = cv2.Canny(gray, 0, 50, apertureSize=5)
|
||||
bin = cv2.dilate(bin, None)
|
||||
bin = cv.Canny(gray, 0, 50, apertureSize=5)
|
||||
bin = cv.dilate(bin, None)
|
||||
else:
|
||||
_retval, bin = cv2.threshold(gray, thrs, 255, cv2.THRESH_BINARY)
|
||||
bin, contours, _hierarchy = cv2.findContours(bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
|
||||
_retval, bin = cv.threshold(gray, thrs, 255, cv.THRESH_BINARY)
|
||||
bin, contours, _hierarchy = cv.findContours(bin, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)
|
||||
for cnt in contours:
|
||||
cnt_len = cv2.arcLength(cnt, True)
|
||||
cnt = cv2.approxPolyDP(cnt, 0.02*cnt_len, True)
|
||||
if len(cnt) == 4 and cv2.contourArea(cnt) > 1000 and cv2.isContourConvex(cnt):
|
||||
cnt_len = cv.arcLength(cnt, True)
|
||||
cnt = cv.approxPolyDP(cnt, 0.02*cnt_len, True)
|
||||
if len(cnt) == 4 and cv.contourArea(cnt) > 1000 and cv.isContourConvex(cnt):
|
||||
cnt = cnt.reshape(-1, 2)
|
||||
max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in xrange(4)])
|
||||
if max_cos < 0.1:
|
||||
@@ -45,11 +45,11 @@ def find_squares(img):
|
||||
if __name__ == '__main__':
|
||||
from glob import glob
|
||||
for fn in glob('../data/pic*.png'):
|
||||
img = cv2.imread(fn)
|
||||
img = cv.imread(fn)
|
||||
squares = find_squares(img)
|
||||
cv2.drawContours( img, squares, -1, (0, 255, 0), 3 )
|
||||
cv2.imshow('squares', img)
|
||||
ch = cv2.waitKey()
|
||||
cv.drawContours( img, squares, -1, (0, 255, 0), 3 )
|
||||
cv.imshow('squares', img)
|
||||
ch = cv.waitKey()
|
||||
if ch == 27:
|
||||
break
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
@@ -10,7 +10,7 @@ Resulting .ply file cam be easily viewed using MeshLab ( http://meshlab.sourcefo
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
ply_header = '''ply
|
||||
format ascii 1.0
|
||||
@@ -35,14 +35,14 @@ def write_ply(fn, verts, colors):
|
||||
|
||||
if __name__ == '__main__':
|
||||
print('loading images...')
|
||||
imgL = cv2.pyrDown( cv2.imread('../data/aloeL.jpg') ) # downscale images for faster processing
|
||||
imgR = cv2.pyrDown( cv2.imread('../data/aloeR.jpg') )
|
||||
imgL = cv.pyrDown( cv.imread('../data/aloeL.jpg') ) # downscale images for faster processing
|
||||
imgR = cv.pyrDown( cv.imread('../data/aloeR.jpg') )
|
||||
|
||||
# disparity range is tuned for 'aloe' image pair
|
||||
window_size = 3
|
||||
min_disp = 16
|
||||
num_disp = 112-min_disp
|
||||
stereo = cv2.StereoSGBM_create(minDisparity = min_disp,
|
||||
stereo = cv.StereoSGBM_create(minDisparity = min_disp,
|
||||
numDisparities = num_disp,
|
||||
blockSize = 16,
|
||||
P1 = 8*3*window_size**2,
|
||||
@@ -63,8 +63,8 @@ if __name__ == '__main__':
|
||||
[0,-1, 0, 0.5*h], # turn points 180 deg around x-axis,
|
||||
[0, 0, 0, -f], # so that y-axis looks up
|
||||
[0, 0, 1, 0]])
|
||||
points = cv2.reprojectImageTo3D(disp, Q)
|
||||
colors = cv2.cvtColor(imgL, cv2.COLOR_BGR2RGB)
|
||||
points = cv.reprojectImageTo3D(disp, Q)
|
||||
colors = cv.cvtColor(imgL, cv.COLOR_BGR2RGB)
|
||||
mask = disp > disp.min()
|
||||
out_points = points[mask]
|
||||
out_colors = colors[mask]
|
||||
@@ -72,7 +72,7 @@ if __name__ == '__main__':
|
||||
write_ply('out.ply', out_points, out_colors)
|
||||
print('%s saved' % 'out.ply')
|
||||
|
||||
cv2.imshow('left', imgL)
|
||||
cv2.imshow('disparity', (disp-min_disp)/num_disp)
|
||||
cv2.waitKey()
|
||||
cv2.destroyAllWindows()
|
||||
cv.imshow('left', imgL)
|
||||
cv.imshow('disparity', (disp-min_disp)/num_disp)
|
||||
cv.waitKey()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
'''
|
||||
Texture flow direction estimation.
|
||||
|
||||
Sample shows how cv2.cornerEigenValsAndVecs function can be used
|
||||
Sample shows how cv.cornerEigenValsAndVecs function can be used
|
||||
to estimate image texture flow direction.
|
||||
|
||||
Usage:
|
||||
@@ -14,7 +14,7 @@ Usage:
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
if __name__ == '__main__':
|
||||
import sys
|
||||
@@ -23,15 +23,15 @@ if __name__ == '__main__':
|
||||
except:
|
||||
fn = '../data/starry_night.jpg'
|
||||
|
||||
img = cv2.imread(fn)
|
||||
img = cv.imread(fn)
|
||||
if img is None:
|
||||
print('Failed to load image file:', fn)
|
||||
sys.exit(1)
|
||||
|
||||
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
|
||||
h, w = img.shape[:2]
|
||||
|
||||
eigen = cv2.cornerEigenValsAndVecs(gray, 15, 3)
|
||||
eigen = cv.cornerEigenValsAndVecs(gray, 15, 3)
|
||||
eigen = eigen.reshape(h, w, 3, 2) # [[e1, e2], v1, v2]
|
||||
flow = eigen[:,:,2]
|
||||
|
||||
@@ -41,7 +41,7 @@ if __name__ == '__main__':
|
||||
points = np.dstack( np.mgrid[d/2:w:d, d/2:h:d] ).reshape(-1, 2)
|
||||
for x, y in np.int32(points):
|
||||
vx, vy = np.int32(flow[y, x]*d)
|
||||
cv2.line(vis, (x-vx, y-vy), (x+vx, y+vy), (0, 0, 0), 1, cv2.LINE_AA)
|
||||
cv2.imshow('input', img)
|
||||
cv2.imshow('flow', vis)
|
||||
cv2.waitKey()
|
||||
cv.line(vis, (x-vx, y-vy), (x+vx, y+vy), (0, 0, 0), 1, cv.LINE_AA)
|
||||
cv.imshow('input', img)
|
||||
cv.imshow('flow', vis)
|
||||
cv.waitKey()
|
||||
|
||||
@@ -7,7 +7,7 @@ from __future__ import print_function
|
||||
import numpy as np
|
||||
from numpy import pi, sin, cos
|
||||
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
defaultSize = 512
|
||||
|
||||
@@ -87,7 +87,7 @@ class TestSceneRender():
|
||||
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)
|
||||
cv2.fillConvexPoly(img, self.currentRect, (0, 0, 255))
|
||||
cv.fillConvexPoly(img, self.currentRect, (0, 0, 255))
|
||||
|
||||
self.time += self.timeStep
|
||||
return img
|
||||
@@ -98,19 +98,19 @@ class TestSceneRender():
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
backGr = cv2.imread('../data/graf1.png')
|
||||
fgr = cv2.imread('../data/box.png')
|
||||
backGr = cv.imread('../data/graf1.png')
|
||||
fgr = cv.imread('../data/box.png')
|
||||
|
||||
render = TestSceneRender(backGr, fgr)
|
||||
|
||||
while True:
|
||||
|
||||
img = render.getNextFrame()
|
||||
cv2.imshow('img', img)
|
||||
cv.imshow('img', img)
|
||||
|
||||
ch = cv2.waitKey(3)
|
||||
ch = cv.waitKey(3)
|
||||
if ch == 27:
|
||||
break
|
||||
#import os
|
||||
#print (os.environ['PYTHONPATH'])
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
+10
-10
@@ -16,7 +16,7 @@ if PY3:
|
||||
xrange = range
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
from common import draw_str
|
||||
import getopt, sys
|
||||
from itertools import count
|
||||
@@ -37,24 +37,24 @@ if __name__ == '__main__':
|
||||
out = None
|
||||
if '-o' in args:
|
||||
fn = args['-o']
|
||||
out = cv2.VideoWriter(args['-o'], cv2.VideoWriter_fourcc(*'DIB '), 30.0, (w, h), False)
|
||||
out = cv.VideoWriter(args['-o'], cv.VideoWriter_fourcc(*'DIB '), 30.0, (w, h), False)
|
||||
print('writing %s ...' % fn)
|
||||
|
||||
a = np.zeros((h, w), np.float32)
|
||||
cv2.randu(a, np.array([0]), np.array([1]))
|
||||
cv.randu(a, np.array([0]), np.array([1]))
|
||||
|
||||
def process_scale(a_lods, lod):
|
||||
d = a_lods[lod] - cv2.pyrUp(a_lods[lod+1])
|
||||
d = a_lods[lod] - cv.pyrUp(a_lods[lod+1])
|
||||
for _i in xrange(lod):
|
||||
d = cv2.pyrUp(d)
|
||||
v = cv2.GaussianBlur(d*d, (3, 3), 0)
|
||||
d = cv.pyrUp(d)
|
||||
v = cv.GaussianBlur(d*d, (3, 3), 0)
|
||||
return np.sign(d), v
|
||||
|
||||
scale_num = 6
|
||||
for frame_i in count():
|
||||
a_lods = [a]
|
||||
for i in xrange(scale_num):
|
||||
a_lods.append(cv2.pyrDown(a_lods[-1]))
|
||||
a_lods.append(cv.pyrDown(a_lods[-1]))
|
||||
ms, vs = [], []
|
||||
for i in xrange(1, scale_num):
|
||||
m, v = process_scale(a_lods, i)
|
||||
@@ -68,7 +68,7 @@ if __name__ == '__main__':
|
||||
out.write(a)
|
||||
vis = a.copy()
|
||||
draw_str(vis, (20, 20), 'frame %d' % frame_i)
|
||||
cv2.imshow('a', vis)
|
||||
if cv2.waitKey(5) == 27:
|
||||
cv.imshow('a', vis)
|
||||
if cv.waitKey(5) == 27:
|
||||
break
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
@brief Sample code that shows how to implement your own linear filters by using filter2D function
|
||||
"""
|
||||
import sys
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
import numpy as np
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ def main(argv):
|
||||
imageName = argv[0] if len(argv) > 0 else "../data/lena.jpg"
|
||||
|
||||
# Loads an image
|
||||
src = cv2.imread(imageName, cv2.IMREAD_COLOR)
|
||||
src = cv.imread(imageName, cv.IMREAD_COLOR)
|
||||
|
||||
# Check if image is loaded fine
|
||||
if src is None:
|
||||
@@ -37,11 +37,11 @@ def main(argv):
|
||||
## [update_kernel]
|
||||
## [apply_filter]
|
||||
# Apply filter
|
||||
dst = cv2.filter2D(src, ddepth, kernel)
|
||||
dst = cv.filter2D(src, ddepth, kernel)
|
||||
## [apply_filter]
|
||||
cv2.imshow(window_name, dst)
|
||||
cv.imshow(window_name, dst)
|
||||
|
||||
c = cv2.waitKey(500)
|
||||
c = cv.waitKey(500)
|
||||
if c == 27:
|
||||
break
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import sys
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
import numpy as np
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ def main(argv):
|
||||
filename = argv[0] if len(argv) > 0 else default_file
|
||||
|
||||
# Loads an image
|
||||
src = cv2.imread(filename, cv2.IMREAD_COLOR)
|
||||
src = cv.imread(filename, cv.IMREAD_COLOR)
|
||||
|
||||
# Check if image is loaded fine
|
||||
if src is None:
|
||||
@@ -20,17 +20,17 @@ def main(argv):
|
||||
|
||||
## [convert_to_gray]
|
||||
# Convert it to gray
|
||||
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
|
||||
gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
|
||||
## [convert_to_gray]
|
||||
|
||||
## [reduce_noise]
|
||||
# Reduce the noise to avoid false circle detection
|
||||
gray = cv2.medianBlur(gray, 5)
|
||||
gray = cv.medianBlur(gray, 5)
|
||||
## [reduce_noise]
|
||||
|
||||
## [houghcircles]
|
||||
rows = gray.shape[0]
|
||||
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, rows / 8,
|
||||
circles = cv.HoughCircles(gray, cv.HOUGH_GRADIENT, 1, rows / 8,
|
||||
param1=100, param2=30,
|
||||
minRadius=1, maxRadius=30)
|
||||
## [houghcircles]
|
||||
@@ -41,15 +41,15 @@ def main(argv):
|
||||
for i in circles[0, :]:
|
||||
center = (i[0], i[1])
|
||||
# circle center
|
||||
cv2.circle(src, center, 1, (0, 100, 100), 3)
|
||||
cv.circle(src, center, 1, (0, 100, 100), 3)
|
||||
# circle outline
|
||||
radius = i[2]
|
||||
cv2.circle(src, center, radius, (255, 0, 255), 3)
|
||||
cv.circle(src, center, radius, (255, 0, 255), 3)
|
||||
## [draw]
|
||||
|
||||
## [display]
|
||||
cv2.imshow("detected circles", src)
|
||||
cv2.waitKey(0)
|
||||
cv.imshow("detected circles", src)
|
||||
cv.waitKey(0)
|
||||
## [display]
|
||||
|
||||
return 0
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"""
|
||||
import sys
|
||||
import math
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
import numpy as np
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ def main(argv):
|
||||
filename = argv[0] if len(argv) > 0 else default_file
|
||||
|
||||
# Loads an image
|
||||
src = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
|
||||
src = cv.imread(filename, cv.IMREAD_GRAYSCALE)
|
||||
|
||||
# Check if image is loaded fine
|
||||
if src is None:
|
||||
@@ -25,16 +25,16 @@ def main(argv):
|
||||
|
||||
## [edge_detection]
|
||||
# Edge detection
|
||||
dst = cv2.Canny(src, 50, 200, None, 3)
|
||||
dst = cv.Canny(src, 50, 200, None, 3)
|
||||
## [edge_detection]
|
||||
|
||||
# Copy edges to the images that will display the results in BGR
|
||||
cdst = cv2.cvtColor(dst, cv2.COLOR_GRAY2BGR)
|
||||
cdst = cv.cvtColor(dst, cv.COLOR_GRAY2BGR)
|
||||
cdstP = np.copy(cdst)
|
||||
|
||||
## [hough_lines]
|
||||
# Standard Hough Line Transform
|
||||
lines = cv2.HoughLines(dst, 1, np.pi / 180, 150, None, 0, 0)
|
||||
lines = cv.HoughLines(dst, 1, np.pi / 180, 150, None, 0, 0)
|
||||
## [hough_lines]
|
||||
## [draw_lines]
|
||||
# Draw the lines
|
||||
@@ -49,29 +49,29 @@ def main(argv):
|
||||
pt1 = (int(x0 + 1000*(-b)), int(y0 + 1000*(a)))
|
||||
pt2 = (int(x0 - 1000*(-b)), int(y0 - 1000*(a)))
|
||||
|
||||
cv2.line(cdst, pt1, pt2, (0,0,255), 3, cv2.LINE_AA)
|
||||
cv.line(cdst, pt1, pt2, (0,0,255), 3, cv.LINE_AA)
|
||||
## [draw_lines]
|
||||
|
||||
## [hough_lines_p]
|
||||
# Probabilistic Line Transform
|
||||
linesP = cv2.HoughLinesP(dst, 1, np.pi / 180, 50, None, 50, 10)
|
||||
linesP = cv.HoughLinesP(dst, 1, np.pi / 180, 50, None, 50, 10)
|
||||
## [hough_lines_p]
|
||||
## [draw_lines_p]
|
||||
# Draw the lines
|
||||
if linesP is not None:
|
||||
for i in range(0, len(linesP)):
|
||||
l = linesP[i][0]
|
||||
cv2.line(cdstP, (l[0], l[1]), (l[2], l[3]), (0,0,255), 3, cv2.LINE_AA)
|
||||
cv.line(cdstP, (l[0], l[1]), (l[2], l[3]), (0,0,255), 3, cv.LINE_AA)
|
||||
## [draw_lines_p]
|
||||
## [imshow]
|
||||
# Show results
|
||||
cv2.imshow("Source", src)
|
||||
cv2.imshow("Detected Lines (in red) - Standard Hough Line Transform", cdst)
|
||||
cv2.imshow("Detected Lines (in red) - Probabilistic Line Transform", cdstP)
|
||||
cv.imshow("Source", src)
|
||||
cv.imshow("Detected Lines (in red) - Standard Hough Line Transform", cdst)
|
||||
cv.imshow("Detected Lines (in red) - Probabilistic Line Transform", cdstP)
|
||||
## [imshow]
|
||||
## [exit]
|
||||
# Wait and Exit
|
||||
cv2.waitKey()
|
||||
cv.waitKey()
|
||||
return 0
|
||||
## [exit]
|
||||
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
@brief Sample code showing how to detect edges using the Laplace operator
|
||||
"""
|
||||
import sys
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
def main(argv):
|
||||
# [variables]
|
||||
# Declare the variables we are going to use
|
||||
ddepth = cv2.CV_16S
|
||||
ddepth = cv.CV_16S
|
||||
kernel_size = 3
|
||||
window_name = "Laplace Demo"
|
||||
# [variables]
|
||||
@@ -16,7 +16,7 @@ def main(argv):
|
||||
# [load]
|
||||
imageName = argv[0] if len(argv) > 0 else "../data/lena.jpg"
|
||||
|
||||
src = cv2.imread(imageName, cv2.IMREAD_COLOR) # Load an image
|
||||
src = cv.imread(imageName, cv.IMREAD_COLOR) # Load an image
|
||||
|
||||
# Check if image is loaded fine
|
||||
if src is None:
|
||||
@@ -27,30 +27,30 @@ def main(argv):
|
||||
|
||||
# [reduce_noise]
|
||||
# Remove noise by blurring with a Gaussian filter
|
||||
src = cv2.GaussianBlur(src, (3, 3), 0)
|
||||
src = cv.GaussianBlur(src, (3, 3), 0)
|
||||
# [reduce_noise]
|
||||
|
||||
# [convert_to_gray]
|
||||
# Convert the image to grayscale
|
||||
src_gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
|
||||
src_gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
|
||||
# [convert_to_gray]
|
||||
|
||||
# Create Window
|
||||
cv2.namedWindow(window_name, cv2.WINDOW_AUTOSIZE)
|
||||
cv.namedWindow(window_name, cv.WINDOW_AUTOSIZE)
|
||||
|
||||
# [laplacian]
|
||||
# Apply Laplace function
|
||||
dst = cv2.Laplacian(src_gray, ddepth, kernel_size)
|
||||
dst = cv.Laplacian(src_gray, ddepth, kernel_size)
|
||||
# [laplacian]
|
||||
|
||||
# [convert]
|
||||
# converting back to uint8
|
||||
abs_dst = cv2.convertScaleAbs(dst)
|
||||
abs_dst = cv.convertScaleAbs(dst)
|
||||
# [convert]
|
||||
|
||||
# [display]
|
||||
cv2.imshow(window_name, abs_dst)
|
||||
cv2.waitKey(0)
|
||||
cv.imshow(window_name, abs_dst)
|
||||
cv.waitKey(0)
|
||||
# [display]
|
||||
|
||||
return 0
|
||||
|
||||
@@ -4,20 +4,20 @@
|
||||
"""
|
||||
import sys
|
||||
from random import randint
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
|
||||
def main(argv):
|
||||
## [variables]
|
||||
# First we declare the variables we are going to use
|
||||
borderType = cv2.BORDER_CONSTANT
|
||||
borderType = cv.BORDER_CONSTANT
|
||||
window_name = "copyMakeBorder Demo"
|
||||
## [variables]
|
||||
## [load]
|
||||
imageName = argv[0] if len(argv) > 0 else "../data/lena.jpg"
|
||||
|
||||
# Loads an image
|
||||
src = cv2.imread(imageName, cv2.IMREAD_COLOR)
|
||||
src = cv.imread(imageName, cv.IMREAD_COLOR)
|
||||
|
||||
# Check if image is loaded fine
|
||||
if src is None:
|
||||
@@ -33,7 +33,7 @@ def main(argv):
|
||||
' ** Press \'r\' to set the border to be replicated \n'
|
||||
' ** Press \'ESC\' to exit the program ')
|
||||
## [create_window]
|
||||
cv2.namedWindow(window_name, cv2.WINDOW_AUTOSIZE)
|
||||
cv.namedWindow(window_name, cv.WINDOW_AUTOSIZE)
|
||||
## [create_window]
|
||||
## [init_arguments]
|
||||
# Initialize arguments for the filter
|
||||
@@ -47,20 +47,20 @@ def main(argv):
|
||||
value = [randint(0, 255), randint(0, 255), randint(0, 255)]
|
||||
## [update_value]
|
||||
## [copymakeborder]
|
||||
dst = cv2.copyMakeBorder(src, top, bottom, left, right, borderType, None, value)
|
||||
dst = cv.copyMakeBorder(src, top, bottom, left, right, borderType, None, value)
|
||||
## [copymakeborder]
|
||||
## [display]
|
||||
cv2.imshow(window_name, dst)
|
||||
cv.imshow(window_name, dst)
|
||||
## [display]
|
||||
## [check_keypress]
|
||||
c = cv2.waitKey(500)
|
||||
c = cv.waitKey(500)
|
||||
|
||||
if c == 27:
|
||||
break
|
||||
elif c == 99: # 99 = ord('c')
|
||||
borderType = cv2.BORDER_CONSTANT
|
||||
borderType = cv.BORDER_CONSTANT
|
||||
elif c == 114: # 114 = ord('r')
|
||||
borderType = cv2.BORDER_REPLICATE
|
||||
borderType = cv.BORDER_REPLICATE
|
||||
## [check_keypress]
|
||||
return 0
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
@brief Sample code using Sobel and/or Scharr OpenCV functions to make a simple Edge Detector
|
||||
"""
|
||||
import sys
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
|
||||
def main(argv):
|
||||
@@ -12,7 +12,7 @@ def main(argv):
|
||||
window_name = ('Sobel Demo - Simple Edge Detector')
|
||||
scale = 1
|
||||
delta = 0
|
||||
ddepth = cv2.CV_16S
|
||||
ddepth = cv.CV_16S
|
||||
## [variables]
|
||||
|
||||
## [load]
|
||||
@@ -24,7 +24,7 @@ def main(argv):
|
||||
return -1
|
||||
|
||||
# Load the image
|
||||
src = cv2.imread(argv[0], cv2.IMREAD_COLOR)
|
||||
src = cv.imread(argv[0], cv.IMREAD_COLOR)
|
||||
|
||||
# Check if image is loaded fine
|
||||
if src is None:
|
||||
@@ -34,38 +34,38 @@ def main(argv):
|
||||
|
||||
## [reduce_noise]
|
||||
# Remove noise by blurring with a Gaussian filter ( kernel size = 3 )
|
||||
src = cv2.GaussianBlur(src, (3, 3), 0)
|
||||
src = cv.GaussianBlur(src, (3, 3), 0)
|
||||
## [reduce_noise]
|
||||
|
||||
## [convert_to_gray]
|
||||
# Convert the image to grayscale
|
||||
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
|
||||
gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
|
||||
## [convert_to_gray]
|
||||
|
||||
## [sobel]
|
||||
# Gradient-X
|
||||
# grad_x = cv2.Scharr(gray,ddepth,1,0)
|
||||
grad_x = cv2.Sobel(gray, ddepth, 1, 0, ksize=3, scale=scale, delta=delta, borderType=cv2.BORDER_DEFAULT)
|
||||
# grad_x = cv.Scharr(gray,ddepth,1,0)
|
||||
grad_x = cv.Sobel(gray, ddepth, 1, 0, ksize=3, scale=scale, delta=delta, borderType=cv.BORDER_DEFAULT)
|
||||
|
||||
# Gradient-Y
|
||||
# grad_y = cv2.Scharr(gray,ddepth,0,1)
|
||||
grad_y = cv2.Sobel(gray, ddepth, 0, 1, ksize=3, scale=scale, delta=delta, borderType=cv2.BORDER_DEFAULT)
|
||||
# grad_y = cv.Scharr(gray,ddepth,0,1)
|
||||
grad_y = cv.Sobel(gray, ddepth, 0, 1, ksize=3, scale=scale, delta=delta, borderType=cv.BORDER_DEFAULT)
|
||||
## [sobel]
|
||||
|
||||
## [convert]
|
||||
# converting back to uint8
|
||||
abs_grad_x = cv2.convertScaleAbs(grad_x)
|
||||
abs_grad_y = cv2.convertScaleAbs(grad_y)
|
||||
abs_grad_x = cv.convertScaleAbs(grad_x)
|
||||
abs_grad_y = cv.convertScaleAbs(grad_y)
|
||||
## [convert]
|
||||
|
||||
## [blend]
|
||||
## Total Gradient (approximate)
|
||||
grad = cv2.addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0)
|
||||
grad = cv.addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0)
|
||||
## [blend]
|
||||
|
||||
## [display]
|
||||
cv2.imshow(window_name, grad)
|
||||
cv2.waitKey(0)
|
||||
cv.imshow(window_name, grad)
|
||||
cv.waitKey(0)
|
||||
## [display]
|
||||
|
||||
return 0
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from __future__ import print_function
|
||||
import sys
|
||||
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
alpha = 0.5
|
||||
|
||||
@@ -15,8 +15,8 @@ else:
|
||||
if 0 <= alpha <= 1:
|
||||
alpha = input_alpha
|
||||
## [load]
|
||||
src1 = cv2.imread('../../../../data/LinuxLogo.jpg')
|
||||
src2 = cv2.imread('../../../../data/WindowsLogo.jpg')
|
||||
src1 = cv.imread('../../../../data/LinuxLogo.jpg')
|
||||
src2 = cv.imread('../../../../data/WindowsLogo.jpg')
|
||||
## [load]
|
||||
if src1 is None:
|
||||
print ("Error loading src1")
|
||||
@@ -26,10 +26,10 @@ elif src2 is None:
|
||||
exit(-1)
|
||||
## [blend_images]
|
||||
beta = (1.0 - alpha)
|
||||
dst = cv2.addWeighted(src1, alpha, src2, beta, 0.0)
|
||||
dst = cv.addWeighted(src1, alpha, src2, beta, 0.0)
|
||||
## [blend_images]
|
||||
## [display]
|
||||
cv2.imshow('dst', dst)
|
||||
cv2.waitKey(0)
|
||||
cv.imshow('dst', dst)
|
||||
cv.waitKey(0)
|
||||
## [display]
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
+13
-13
@@ -1,4 +1,4 @@
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
import numpy as np
|
||||
|
||||
W = 400
|
||||
@@ -7,7 +7,7 @@ def my_ellipse(img, angle):
|
||||
thickness = 2
|
||||
line_type = 8
|
||||
|
||||
cv2.ellipse(img,
|
||||
cv.ellipse(img,
|
||||
(W / 2, W / 2),
|
||||
(W / 4, W / 16),
|
||||
angle,
|
||||
@@ -22,7 +22,7 @@ def my_filled_circle(img, center):
|
||||
thickness = -1
|
||||
line_type = 8
|
||||
|
||||
cv2.circle(img,
|
||||
cv.circle(img,
|
||||
center,
|
||||
W / 32,
|
||||
(0, 0, 255),
|
||||
@@ -45,16 +45,16 @@ def my_polygon(img):
|
||||
[W / 4, 3 * W / 8], [13 * W / 32, 3 * W / 8],
|
||||
[5 * W / 16, 13 * W / 16], [W / 4, 13 * W / 16]], np.int32)
|
||||
ppt = ppt.reshape((-1, 1, 2))
|
||||
cv2.fillPoly(img, [ppt], (255, 255, 255), line_type)
|
||||
cv.fillPoly(img, [ppt], (255, 255, 255), line_type)
|
||||
# Only drawind the lines would be:
|
||||
# cv2.polylines(img, [ppt], True, (255, 0, 255), line_type)
|
||||
# cv.polylines(img, [ppt], True, (255, 0, 255), line_type)
|
||||
## [my_polygon]
|
||||
## [my_line]
|
||||
def my_line(img, start, end):
|
||||
thickness = 2
|
||||
line_type = 8
|
||||
|
||||
cv2.line(img,
|
||||
cv.line(img,
|
||||
start,
|
||||
end,
|
||||
(0, 0, 0),
|
||||
@@ -92,7 +92,7 @@ my_filled_circle(atom_image, (W / 2, W / 2))
|
||||
my_polygon(rook_image)
|
||||
## [rectangle]
|
||||
# 2.b. Creating rectangles
|
||||
cv2.rectangle(rook_image,
|
||||
cv.rectangle(rook_image,
|
||||
(0, 7 * W / 8),
|
||||
(W, W),
|
||||
(0, 255, 255),
|
||||
@@ -106,10 +106,10 @@ my_line(rook_image, (W / 4, 7 * W / 8), (W / 4, W))
|
||||
my_line(rook_image, (W / 2, 7 * W / 8), (W / 2, W))
|
||||
my_line(rook_image, (3 * W / 4, 7 * W / 8), (3 * W / 4, W))
|
||||
## [draw_rook]
|
||||
cv2.imshow(atom_window, atom_image)
|
||||
cv2.moveWindow(atom_window, 0, 200)
|
||||
cv2.imshow(rook_window, rook_image)
|
||||
cv2.moveWindow(rook_window, W, 200)
|
||||
cv.imshow(atom_window, atom_image)
|
||||
cv.moveWindow(atom_window, 0, 200)
|
||||
cv.imshow(rook_window, rook_image)
|
||||
cv.moveWindow(rook_window, W, 200)
|
||||
|
||||
cv2.waitKey(0)
|
||||
cv2.destroyAllWindows()
|
||||
cv.waitKey(0)
|
||||
cv.destroyAllWindows()
|
||||
|
||||
+15
-15
@@ -1,7 +1,7 @@
|
||||
from __future__ import print_function
|
||||
import sys
|
||||
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
import numpy as np
|
||||
|
||||
|
||||
@@ -19,34 +19,34 @@ def main(argv):
|
||||
|
||||
filename = argv[0] if len(argv) > 0 else "../../../../data/lena.jpg"
|
||||
|
||||
I = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
|
||||
I = cv.imread(filename, cv.IMREAD_GRAYSCALE)
|
||||
if I is None:
|
||||
print('Error opening image')
|
||||
return -1
|
||||
## [expand]
|
||||
rows, cols = I.shape
|
||||
m = cv2.getOptimalDFTSize( rows )
|
||||
n = cv2.getOptimalDFTSize( cols )
|
||||
padded = cv2.copyMakeBorder(I, 0, m - rows, 0, n - cols, cv2.BORDER_CONSTANT, value=[0, 0, 0])
|
||||
m = cv.getOptimalDFTSize( rows )
|
||||
n = cv.getOptimalDFTSize( cols )
|
||||
padded = cv.copyMakeBorder(I, 0, m - rows, 0, n - cols, cv.BORDER_CONSTANT, value=[0, 0, 0])
|
||||
## [expand]
|
||||
## [complex_and_real]
|
||||
planes = [np.float32(padded), np.zeros(padded.shape, np.float32)]
|
||||
complexI = cv2.merge(planes) # Add to the expanded another plane with zeros
|
||||
complexI = cv.merge(planes) # Add to the expanded another plane with zeros
|
||||
## [complex_and_real]
|
||||
## [dft]
|
||||
cv2.dft(complexI, complexI) # this way the result may fit in the source matrix
|
||||
cv.dft(complexI, complexI) # this way the result may fit in the source matrix
|
||||
## [dft]
|
||||
# compute the magnitude and switch to logarithmic scale
|
||||
# = > log(1 + sqrt(Re(DFT(I)) ^ 2 + Im(DFT(I)) ^ 2))
|
||||
## [magnitude]
|
||||
cv2.split(complexI, planes) # planes[0] = Re(DFT(I), planes[1] = Im(DFT(I))
|
||||
cv2.magnitude(planes[0], planes[1], planes[0])# planes[0] = magnitude
|
||||
cv.split(complexI, planes) # planes[0] = Re(DFT(I), planes[1] = Im(DFT(I))
|
||||
cv.magnitude(planes[0], planes[1], planes[0])# planes[0] = magnitude
|
||||
magI = planes[0]
|
||||
## [magnitude]
|
||||
## [log]
|
||||
matOfOnes = np.ones(magI.shape, dtype=magI.dtype)
|
||||
cv2.add(matOfOnes, magI, magI) # switch to logarithmic scale
|
||||
cv2.log(magI, magI)
|
||||
cv.add(matOfOnes, magI, magI) # switch to logarithmic scale
|
||||
cv.log(magI, magI)
|
||||
## [log]
|
||||
## [crop_rearrange]
|
||||
magI_rows, magI_cols = magI.shape
|
||||
@@ -69,12 +69,12 @@ def main(argv):
|
||||
magI[0:cx, cy:cy + cy] = tmp
|
||||
## [crop_rearrange]
|
||||
## [normalize]
|
||||
cv2.normalize(magI, magI, 0, 1, cv2.NORM_MINMAX) # Transform the matrix with float values into a
|
||||
cv.normalize(magI, magI, 0, 1, cv.NORM_MINMAX) # Transform the matrix with float values into a
|
||||
## viewable image form(float between values 0 and 1).
|
||||
## [normalize]
|
||||
cv2.imshow("Input Image" , I ) # Show the result
|
||||
cv2.imshow("spectrum magnitude", magI)
|
||||
cv2.waitKey()
|
||||
cv.imshow("Input Image" , I ) # Show the result
|
||||
cv.imshow("spectrum magnitude", magI)
|
||||
cv.waitKey()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv[1:])
|
||||
|
||||
@@ -3,7 +3,7 @@ import sys
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
## [basic_method]
|
||||
def is_grayscale(my_image):
|
||||
@@ -23,7 +23,7 @@ def sharpen(my_image):
|
||||
if is_grayscale(my_image):
|
||||
height, width = my_image.shape
|
||||
else:
|
||||
my_image = cv2.cvtColor(my_image, cv2.CV_8U)
|
||||
my_image = cv.cvtColor(my_image, cv.CV_8U)
|
||||
height, width, n_channels = my_image.shape
|
||||
|
||||
result = np.zeros(my_image.shape, my_image.dtype)
|
||||
@@ -47,13 +47,13 @@ def sharpen(my_image):
|
||||
def main(argv):
|
||||
filename = "../../../../data/lena.jpg"
|
||||
|
||||
img_codec = cv2.IMREAD_COLOR
|
||||
img_codec = cv.IMREAD_COLOR
|
||||
if argv:
|
||||
filename = sys.argv[1]
|
||||
if len(argv) >= 2 and sys.argv[2] == "G":
|
||||
img_codec = cv2.IMREAD_GRAYSCALE
|
||||
img_codec = cv.IMREAD_GRAYSCALE
|
||||
|
||||
src = cv2.imread(filename, img_codec)
|
||||
src = cv.imread(filename, img_codec)
|
||||
|
||||
if src is None:
|
||||
print("Can't open image [" + filename + "]")
|
||||
@@ -61,10 +61,10 @@ def main(argv):
|
||||
print("mat_mask_operations.py [image_path -- default ../../../../data/lena.jpg] [G -- grayscale]")
|
||||
return -1
|
||||
|
||||
cv2.namedWindow("Input", cv2.WINDOW_AUTOSIZE)
|
||||
cv2.namedWindow("Output", cv2.WINDOW_AUTOSIZE)
|
||||
cv.namedWindow("Input", cv.WINDOW_AUTOSIZE)
|
||||
cv.namedWindow("Output", cv.WINDOW_AUTOSIZE)
|
||||
|
||||
cv2.imshow("Input", src)
|
||||
cv.imshow("Input", src)
|
||||
t = round(time.time())
|
||||
|
||||
dst0 = sharpen(src)
|
||||
@@ -72,8 +72,8 @@ def main(argv):
|
||||
t = (time.time() - t) / 1000
|
||||
print("Hand written function time passed in seconds: %s" % t)
|
||||
|
||||
cv2.imshow("Output", dst0)
|
||||
cv2.waitKey()
|
||||
cv.imshow("Output", dst0)
|
||||
cv.waitKey()
|
||||
|
||||
t = time.time()
|
||||
## [kern]
|
||||
@@ -82,17 +82,17 @@ def main(argv):
|
||||
[0, -1, 0]], np.float32) # kernel should be floating point type
|
||||
## [kern]
|
||||
## [filter2D]
|
||||
dst1 = cv2.filter2D(src, -1, kernel)
|
||||
dst1 = cv.filter2D(src, -1, kernel)
|
||||
# ddepth = -1, means destination image has depth same as input image
|
||||
## [filter2D]
|
||||
|
||||
t = (time.time() - t) / 1000
|
||||
print("Built-in filter2D time passed in seconds: %s" % t)
|
||||
|
||||
cv2.imshow("Output", dst1)
|
||||
cv.imshow("Output", dst1)
|
||||
|
||||
cv2.waitKey(0)
|
||||
cv2.destroyAllWindows()
|
||||
cv.waitKey(0)
|
||||
cv.destroyAllWindows()
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
import numpy as np
|
||||
|
||||
input_image = np.array((
|
||||
@@ -16,23 +16,23 @@ kernel = np.array((
|
||||
[1, -1, 1],
|
||||
[0, 1, 0]), dtype="int")
|
||||
|
||||
output_image = cv2.morphologyEx(input_image, cv2.MORPH_HITMISS, kernel)
|
||||
output_image = cv.morphologyEx(input_image, cv.MORPH_HITMISS, kernel)
|
||||
|
||||
rate = 50
|
||||
kernel = (kernel + 1) * 127
|
||||
kernel = np.uint8(kernel)
|
||||
|
||||
kernel = cv2.resize(kernel, None, fx = rate, fy = rate, interpolation = cv2.INTER_NEAREST)
|
||||
cv2.imshow("kernel", kernel)
|
||||
cv2.moveWindow("kernel", 0, 0)
|
||||
kernel = cv.resize(kernel, None, fx = rate, fy = rate, interpolation = cv.INTER_NEAREST)
|
||||
cv.imshow("kernel", kernel)
|
||||
cv.moveWindow("kernel", 0, 0)
|
||||
|
||||
input_image = cv2.resize(input_image, None, fx = rate, fy = rate, interpolation = cv2.INTER_NEAREST)
|
||||
cv2.imshow("Original", input_image)
|
||||
cv2.moveWindow("Original", 0, 200)
|
||||
input_image = cv.resize(input_image, None, fx = rate, fy = rate, interpolation = cv.INTER_NEAREST)
|
||||
cv.imshow("Original", input_image)
|
||||
cv.moveWindow("Original", 0, 200)
|
||||
|
||||
output_image = cv2.resize(output_image, None , fx = rate, fy = rate, interpolation = cv2.INTER_NEAREST)
|
||||
cv2.imshow("Hit or Miss", output_image)
|
||||
cv2.moveWindow("Hit or Miss", 500, 200)
|
||||
output_image = cv.resize(output_image, None , fx = rate, fy = rate, interpolation = cv.INTER_NEAREST)
|
||||
cv.imshow("Hit or Miss", output_image)
|
||||
cv.moveWindow("Hit or Miss", 500, 200)
|
||||
|
||||
cv2.waitKey(0)
|
||||
cv2.destroyAllWindows()
|
||||
cv.waitKey(0)
|
||||
cv.destroyAllWindows()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import sys
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
|
||||
def main(argv):
|
||||
@@ -14,7 +14,7 @@ def main(argv):
|
||||
filename = argv[0] if len(argv) > 0 else "../data/chicky_512.png"
|
||||
|
||||
# Load the image
|
||||
src = cv2.imread(filename)
|
||||
src = cv.imread(filename)
|
||||
|
||||
# Check if image is loaded fine
|
||||
if src is None:
|
||||
@@ -26,25 +26,25 @@ def main(argv):
|
||||
while 1:
|
||||
rows, cols, _channels = map(int, src.shape)
|
||||
## [show_image]
|
||||
cv2.imshow('Pyramids Demo', src)
|
||||
cv.imshow('Pyramids Demo', src)
|
||||
## [show_image]
|
||||
k = cv2.waitKey(0)
|
||||
k = cv.waitKey(0)
|
||||
|
||||
if k == 27:
|
||||
break
|
||||
## [pyrup]
|
||||
elif chr(k) == 'i':
|
||||
src = cv2.pyrUp(src, dstsize=(2 * cols, 2 * rows))
|
||||
src = cv.pyrUp(src, dstsize=(2 * cols, 2 * rows))
|
||||
print ('** Zoom In: Image x 2')
|
||||
## [pyrup]
|
||||
## [pyrdown]
|
||||
elif chr(k) == 'o':
|
||||
src = cv2.pyrDown(src, dstsize=(cols // 2, rows // 2))
|
||||
src = cv.pyrDown(src, dstsize=(cols // 2, rows // 2))
|
||||
print ('** Zoom Out: Image / 2')
|
||||
## [pyrdown]
|
||||
## [loop]
|
||||
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
return 0
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import sys
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
import numpy as np
|
||||
|
||||
# Global Variables
|
||||
@@ -14,13 +14,13 @@ window_name = 'Smoothing Demo'
|
||||
|
||||
|
||||
def main(argv):
|
||||
cv2.namedWindow(window_name, cv2.WINDOW_AUTOSIZE)
|
||||
cv.namedWindow(window_name, cv.WINDOW_AUTOSIZE)
|
||||
|
||||
# Load the source image
|
||||
imageName = argv[0] if len(argv) > 0 else "../data/lena.jpg"
|
||||
|
||||
global src
|
||||
src = cv2.imread(imageName, 1)
|
||||
src = cv.imread(imageName, 1)
|
||||
if src is None:
|
||||
print ('Error opening image')
|
||||
print ('Usage: smoothing.py [image_name -- default ../data/lena.jpg] \n')
|
||||
@@ -40,7 +40,7 @@ def main(argv):
|
||||
|
||||
## [blur]
|
||||
for i in range(1, MAX_KERNEL_LENGTH, 2):
|
||||
dst = cv2.blur(src, (i, i))
|
||||
dst = cv.blur(src, (i, i))
|
||||
if display_dst(DELAY_BLUR) != 0:
|
||||
return 0
|
||||
## [blur]
|
||||
@@ -51,7 +51,7 @@ def main(argv):
|
||||
|
||||
## [gaussianblur]
|
||||
for i in range(1, MAX_KERNEL_LENGTH, 2):
|
||||
dst = cv2.GaussianBlur(src, (i, i), 0)
|
||||
dst = cv.GaussianBlur(src, (i, i), 0)
|
||||
if display_dst(DELAY_BLUR) != 0:
|
||||
return 0
|
||||
## [gaussianblur]
|
||||
@@ -62,7 +62,7 @@ def main(argv):
|
||||
|
||||
## [medianblur]
|
||||
for i in range(1, MAX_KERNEL_LENGTH, 2):
|
||||
dst = cv2.medianBlur(src, i)
|
||||
dst = cv.medianBlur(src, i)
|
||||
if display_dst(DELAY_BLUR) != 0:
|
||||
return 0
|
||||
## [medianblur]
|
||||
@@ -74,7 +74,7 @@ def main(argv):
|
||||
## [bilateralfilter]
|
||||
# Remember, bilateral is a bit slow, so as value go higher, it takes long time
|
||||
for i in range(1, MAX_KERNEL_LENGTH, 2):
|
||||
dst = cv2.bilateralFilter(src, i, i * 2, i / 2)
|
||||
dst = cv.bilateralFilter(src, i, i * 2, i / 2)
|
||||
if display_dst(DELAY_BLUR) != 0:
|
||||
return 0
|
||||
## [bilateralfilter]
|
||||
@@ -89,16 +89,16 @@ def display_caption(caption):
|
||||
global dst
|
||||
dst = np.zeros(src.shape, src.dtype)
|
||||
rows, cols, ch = src.shape
|
||||
cv2.putText(dst, caption,
|
||||
cv.putText(dst, caption,
|
||||
(int(cols / 4), int(rows / 2)),
|
||||
cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255))
|
||||
cv.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255))
|
||||
|
||||
return display_dst(DELAY_CAPTION)
|
||||
|
||||
|
||||
def display_dst(delay):
|
||||
cv2.imshow(window_name, dst)
|
||||
c = cv2.waitKey(delay)
|
||||
cv.imshow(window_name, dst)
|
||||
c = cv.waitKey(delay)
|
||||
if c >= 0 : return -1
|
||||
return 0
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
import numpy as np
|
||||
|
||||
img = cv2.imread('../data/sudoku.png')
|
||||
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
|
||||
edges = cv2.Canny(gray,50,150,apertureSize = 3)
|
||||
img = cv.imread('../data/sudoku.png')
|
||||
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
|
||||
edges = cv.Canny(gray,50,150,apertureSize = 3)
|
||||
|
||||
lines = cv2.HoughLines(edges,1,np.pi/180,200)
|
||||
lines = cv.HoughLines(edges,1,np.pi/180,200)
|
||||
for line in lines:
|
||||
rho,theta = line[0]
|
||||
a = np.cos(theta)
|
||||
@@ -17,6 +17,6 @@ for line in lines:
|
||||
x2 = int(x0 - 1000*(-b))
|
||||
y2 = int(y0 - 1000*(a))
|
||||
|
||||
cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)
|
||||
cv.line(img,(x1,y1),(x2,y2),(0,0,255),2)
|
||||
|
||||
cv2.imwrite('houghlines3.jpg',img)
|
||||
cv.imwrite('houghlines3.jpg',img)
|
||||
|
||||
+7
-7
@@ -1,12 +1,12 @@
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
import numpy as np
|
||||
|
||||
img = cv2.imread('../data/sudoku.png')
|
||||
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
|
||||
edges = cv2.Canny(gray,50,150,apertureSize = 3)
|
||||
lines = cv2.HoughLinesP(edges,1,np.pi/180,100,minLineLength=100,maxLineGap=10)
|
||||
img = cv.imread('../data/sudoku.png')
|
||||
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
|
||||
edges = cv.Canny(gray,50,150,apertureSize = 3)
|
||||
lines = cv.HoughLinesP(edges,1,np.pi/180,100,minLineLength=100,maxLineGap=10)
|
||||
for line in lines:
|
||||
x1,y1,x2,y2 = line[0]
|
||||
cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)
|
||||
cv.line(img,(x1,y1),(x2,y2),(0,255,0),2)
|
||||
|
||||
cv2.imwrite('houghlines5.jpg',img)
|
||||
cv.imwrite('houghlines5.jpg',img)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import sys
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
## [global_variables]
|
||||
use_mask = False
|
||||
@@ -23,14 +23,14 @@ def main(argv):
|
||||
## [load_image]
|
||||
global img
|
||||
global templ
|
||||
img = cv2.imread(sys.argv[1], cv2.IMREAD_COLOR)
|
||||
templ = cv2.imread(sys.argv[2], cv2.IMREAD_COLOR)
|
||||
img = cv.imread(sys.argv[1], cv.IMREAD_COLOR)
|
||||
templ = cv.imread(sys.argv[2], cv.IMREAD_COLOR)
|
||||
|
||||
if (len(sys.argv) > 3):
|
||||
global use_mask
|
||||
use_mask = True
|
||||
global mask
|
||||
mask = cv2.imread( sys.argv[3], cv2.IMREAD_COLOR )
|
||||
mask = cv.imread( sys.argv[3], cv.IMREAD_COLOR )
|
||||
|
||||
if ((img is None) or (templ is None) or (use_mask and (mask is None))):
|
||||
print 'Can\'t read one of the images'
|
||||
@@ -38,19 +38,19 @@ def main(argv):
|
||||
## [load_image]
|
||||
|
||||
## [create_windows]
|
||||
cv2.namedWindow( image_window, cv2.WINDOW_AUTOSIZE )
|
||||
cv2.namedWindow( result_window, cv2.WINDOW_AUTOSIZE )
|
||||
cv.namedWindow( image_window, cv.WINDOW_AUTOSIZE )
|
||||
cv.namedWindow( result_window, cv.WINDOW_AUTOSIZE )
|
||||
## [create_windows]
|
||||
|
||||
## [create_trackbar]
|
||||
trackbar_label = 'Method: \n 0: SQDIFF \n 1: SQDIFF NORMED \n 2: TM CCORR \n 3: TM CCORR NORMED \n 4: TM COEFF \n 5: TM COEFF NORMED'
|
||||
cv2.createTrackbar( trackbar_label, image_window, match_method, max_Trackbar, MatchingMethod )
|
||||
cv.createTrackbar( trackbar_label, image_window, match_method, max_Trackbar, MatchingMethod )
|
||||
## [create_trackbar]
|
||||
|
||||
MatchingMethod(match_method)
|
||||
|
||||
## [wait_key]
|
||||
cv2.waitKey(0)
|
||||
cv.waitKey(0)
|
||||
return 0
|
||||
## [wait_key]
|
||||
|
||||
@@ -63,32 +63,32 @@ def MatchingMethod(param):
|
||||
img_display = img.copy()
|
||||
## [copy_source]
|
||||
## [match_template]
|
||||
method_accepts_mask = (cv2.TM_SQDIFF == match_method or match_method == cv2.TM_CCORR_NORMED)
|
||||
method_accepts_mask = (cv.TM_SQDIFF == match_method or match_method == cv.TM_CCORR_NORMED)
|
||||
if (use_mask and method_accepts_mask):
|
||||
result = cv2.matchTemplate(img, templ, match_method, None, mask)
|
||||
result = cv.matchTemplate(img, templ, match_method, None, mask)
|
||||
else:
|
||||
result = cv2.matchTemplate(img, templ, match_method)
|
||||
result = cv.matchTemplate(img, templ, match_method)
|
||||
## [match_template]
|
||||
|
||||
## [normalize]
|
||||
cv2.normalize( result, result, 0, 1, cv2.NORM_MINMAX, -1 )
|
||||
cv.normalize( result, result, 0, 1, cv.NORM_MINMAX, -1 )
|
||||
## [normalize]
|
||||
## [best_match]
|
||||
_minVal, _maxVal, minLoc, maxLoc = cv2.minMaxLoc(result, None)
|
||||
_minVal, _maxVal, minLoc, maxLoc = cv.minMaxLoc(result, None)
|
||||
## [best_match]
|
||||
|
||||
## [match_loc]
|
||||
if (match_method == cv2.TM_SQDIFF or match_method == cv2.TM_SQDIFF_NORMED):
|
||||
if (match_method == cv.TM_SQDIFF or match_method == cv.TM_SQDIFF_NORMED):
|
||||
matchLoc = minLoc
|
||||
else:
|
||||
matchLoc = maxLoc
|
||||
## [match_loc]
|
||||
|
||||
## [imshow]
|
||||
cv2.rectangle(img_display, matchLoc, (matchLoc[0] + templ.shape[0], matchLoc[1] + templ.shape[1]), (0,0,0), 2, 8, 0 )
|
||||
cv2.rectangle(result, matchLoc, (matchLoc[0] + templ.shape[0], matchLoc[1] + templ.shape[1]), (0,0,0), 2, 8, 0 )
|
||||
cv2.imshow(image_window, img_display)
|
||||
cv2.imshow(result_window, result)
|
||||
cv.rectangle(img_display, matchLoc, (matchLoc[0] + templ.shape[0], matchLoc[1] + templ.shape[1]), (0,0,0), 2, 8, 0 )
|
||||
cv.rectangle(result, matchLoc, (matchLoc[0] + templ.shape[0], matchLoc[1] + templ.shape[1]), (0,0,0), 2, 8, 0 )
|
||||
cv.imshow(image_window, img_display)
|
||||
cv.imshow(result_window, result)
|
||||
## [imshow]
|
||||
pass
|
||||
|
||||
|
||||
+22
-22
@@ -4,14 +4,14 @@
|
||||
"""
|
||||
import numpy as np
|
||||
import sys
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
|
||||
def show_wait_destroy(winname, img):
|
||||
cv2.imshow(winname, img)
|
||||
cv2.moveWindow(winname, 500, 0)
|
||||
cv2.waitKey(0)
|
||||
cv2.destroyWindow(winname)
|
||||
cv.imshow(winname, img)
|
||||
cv.moveWindow(winname, 500, 0)
|
||||
cv.waitKey(0)
|
||||
cv.destroyWindow(winname)
|
||||
|
||||
|
||||
def main(argv):
|
||||
@@ -23,7 +23,7 @@ def main(argv):
|
||||
return -1
|
||||
|
||||
# Load the image
|
||||
src = cv2.imread(argv[0], cv2.IMREAD_COLOR)
|
||||
src = cv.imread(argv[0], cv.IMREAD_COLOR)
|
||||
|
||||
# Check if image is loaded fine
|
||||
if src is None:
|
||||
@@ -31,13 +31,13 @@ def main(argv):
|
||||
return -1
|
||||
|
||||
# Show source image
|
||||
cv2.imshow("src", src)
|
||||
cv.imshow("src", src)
|
||||
# [load_image]
|
||||
|
||||
# [gray]
|
||||
# Transform source image to gray if it is not already
|
||||
if len(src.shape) != 2:
|
||||
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
|
||||
gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
|
||||
else:
|
||||
gray = src
|
||||
|
||||
@@ -47,9 +47,9 @@ def main(argv):
|
||||
|
||||
# [bin]
|
||||
# Apply adaptiveThreshold at the bitwise_not of gray, notice the ~ symbol
|
||||
gray = cv2.bitwise_not(gray)
|
||||
bw = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, \
|
||||
cv2.THRESH_BINARY, 15, -2)
|
||||
gray = cv.bitwise_not(gray)
|
||||
bw = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_MEAN_C, \
|
||||
cv.THRESH_BINARY, 15, -2)
|
||||
# Show binary image
|
||||
show_wait_destroy("binary", bw)
|
||||
# [bin]
|
||||
@@ -66,11 +66,11 @@ def main(argv):
|
||||
horizontal_size = cols / 30
|
||||
|
||||
# Create structure element for extracting horizontal lines through morphology operations
|
||||
horizontalStructure = cv2.getStructuringElement(cv2.MORPH_RECT, (horizontal_size, 1))
|
||||
horizontalStructure = cv.getStructuringElement(cv.MORPH_RECT, (horizontal_size, 1))
|
||||
|
||||
# Apply morphology operations
|
||||
horizontal = cv2.erode(horizontal, horizontalStructure)
|
||||
horizontal = cv2.dilate(horizontal, horizontalStructure)
|
||||
horizontal = cv.erode(horizontal, horizontalStructure)
|
||||
horizontal = cv.dilate(horizontal, horizontalStructure)
|
||||
|
||||
# Show extracted horizontal lines
|
||||
show_wait_destroy("horizontal", horizontal)
|
||||
@@ -82,11 +82,11 @@ def main(argv):
|
||||
verticalsize = rows / 30
|
||||
|
||||
# Create structure element for extracting vertical lines through morphology operations
|
||||
verticalStructure = cv2.getStructuringElement(cv2.MORPH_RECT, (1, verticalsize))
|
||||
verticalStructure = cv.getStructuringElement(cv.MORPH_RECT, (1, verticalsize))
|
||||
|
||||
# Apply morphology operations
|
||||
vertical = cv2.erode(vertical, verticalStructure)
|
||||
vertical = cv2.dilate(vertical, verticalStructure)
|
||||
vertical = cv.erode(vertical, verticalStructure)
|
||||
vertical = cv.dilate(vertical, verticalStructure)
|
||||
|
||||
# Show extracted vertical lines
|
||||
show_wait_destroy("vertical", vertical)
|
||||
@@ -94,7 +94,7 @@ def main(argv):
|
||||
|
||||
# [smooth]
|
||||
# Inverse vertical image
|
||||
vertical = cv2.bitwise_not(vertical)
|
||||
vertical = cv.bitwise_not(vertical)
|
||||
show_wait_destroy("vertical_bit", vertical)
|
||||
|
||||
'''
|
||||
@@ -107,20 +107,20 @@ def main(argv):
|
||||
'''
|
||||
|
||||
# Step 1
|
||||
edges = cv2.adaptiveThreshold(vertical, 255, cv2.ADAPTIVE_THRESH_MEAN_C, \
|
||||
cv2.THRESH_BINARY, 3, -2)
|
||||
edges = cv.adaptiveThreshold(vertical, 255, cv.ADAPTIVE_THRESH_MEAN_C, \
|
||||
cv.THRESH_BINARY, 3, -2)
|
||||
show_wait_destroy("edges", edges)
|
||||
|
||||
# Step 2
|
||||
kernel = np.ones((2, 2), np.uint8)
|
||||
edges = cv2.dilate(edges, kernel)
|
||||
edges = cv.dilate(edges, kernel)
|
||||
show_wait_destroy("dilate", edges)
|
||||
|
||||
# Step 3
|
||||
smooth = np.copy(vertical)
|
||||
|
||||
# Step 4
|
||||
smooth = cv2.blur(smooth, (2, 2))
|
||||
smooth = cv.blur(smooth, (2, 2))
|
||||
|
||||
# Step 5
|
||||
(rows, cols) = np.where(edges != 0)
|
||||
|
||||
@@ -1,28 +1,28 @@
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
import numpy as np
|
||||
|
||||
SZ=20
|
||||
bin_n = 16 # Number of bins
|
||||
|
||||
|
||||
affine_flags = cv2.WARP_INVERSE_MAP|cv2.INTER_LINEAR
|
||||
affine_flags = cv.WARP_INVERSE_MAP|cv.INTER_LINEAR
|
||||
|
||||
## [deskew]
|
||||
def deskew(img):
|
||||
m = cv2.moments(img)
|
||||
m = cv.moments(img)
|
||||
if abs(m['mu02']) < 1e-2:
|
||||
return img.copy()
|
||||
skew = m['mu11']/m['mu02']
|
||||
M = np.float32([[1, skew, -0.5*SZ*skew], [0, 1, 0]])
|
||||
img = cv2.warpAffine(img,M,(SZ, SZ),flags=affine_flags)
|
||||
img = cv.warpAffine(img,M,(SZ, SZ),flags=affine_flags)
|
||||
return img
|
||||
## [deskew]
|
||||
|
||||
## [hog]
|
||||
def hog(img):
|
||||
gx = cv2.Sobel(img, cv2.CV_32F, 1, 0)
|
||||
gy = cv2.Sobel(img, cv2.CV_32F, 0, 1)
|
||||
mag, ang = cv2.cartToPolar(gx, gy)
|
||||
gx = cv.Sobel(img, cv.CV_32F, 1, 0)
|
||||
gy = cv.Sobel(img, cv.CV_32F, 0, 1)
|
||||
mag, ang = cv.cartToPolar(gx, gy)
|
||||
bins = np.int32(bin_n*ang/(2*np.pi)) # quantizing binvalues in (0...16)
|
||||
bin_cells = bins[:10,:10], bins[10:,:10], bins[:10,10:], bins[10:,10:]
|
||||
mag_cells = mag[:10,:10], mag[10:,:10], mag[:10,10:], mag[10:,10:]
|
||||
@@ -31,7 +31,7 @@ def hog(img):
|
||||
return hist
|
||||
## [hog]
|
||||
|
||||
img = cv2.imread('digits.png',0)
|
||||
img = cv.imread('digits.png',0)
|
||||
if img is None:
|
||||
raise Exception("we need the digits.png image from samples/data here !")
|
||||
|
||||
@@ -49,13 +49,13 @@ hogdata = [map(hog,row) for row in deskewed]
|
||||
trainData = np.float32(hogdata).reshape(-1,64)
|
||||
responses = np.repeat(np.arange(10),250)[:,np.newaxis]
|
||||
|
||||
svm = cv2.ml.SVM_create()
|
||||
svm.setKernel(cv2.ml.SVM_LINEAR)
|
||||
svm.setType(cv2.ml.SVM_C_SVC)
|
||||
svm = cv.ml.SVM_create()
|
||||
svm.setKernel(cv.ml.SVM_LINEAR)
|
||||
svm.setType(cv.ml.SVM_C_SVC)
|
||||
svm.setC(2.67)
|
||||
svm.setGamma(5.383)
|
||||
|
||||
svm.train(trainData, cv2.ml.ROW_SAMPLE, responses)
|
||||
svm.train(trainData, cv.ml.ROW_SAMPLE, responses)
|
||||
svm.save('svm_data.dat')
|
||||
|
||||
###### Now testing ########################
|
||||
|
||||
+21
-21
@@ -35,7 +35,7 @@ from __future__ import print_function
|
||||
import numpy as np
|
||||
from numpy import pi, sin, cos
|
||||
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
# built-in modules
|
||||
from time import clock
|
||||
@@ -49,14 +49,14 @@ class VideoSynthBase(object):
|
||||
self.bg = None
|
||||
self.frame_size = (640, 480)
|
||||
if bg is not None:
|
||||
self.bg = cv2.imread(bg, 1)
|
||||
self.bg = cv.imread(bg, 1)
|
||||
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 = cv2.resize(self.bg, self.frame_size)
|
||||
self.bg = cv.resize(self.bg, self.frame_size)
|
||||
|
||||
self.noise = float(noise)
|
||||
|
||||
@@ -75,8 +75,8 @@ class VideoSynthBase(object):
|
||||
|
||||
if self.noise > 0.0:
|
||||
noise = np.zeros((h, w, 3), np.int8)
|
||||
cv2.randn(noise, np.zeros(3), np.ones(3)*255*self.noise)
|
||||
buf = cv2.add(buf, noise, dtype=cv2.CV_8UC3)
|
||||
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):
|
||||
@@ -85,26 +85,26 @@ class VideoSynthBase(object):
|
||||
class Book(VideoSynthBase):
|
||||
def __init__(self, **kw):
|
||||
super(Book, self).__init__(**kw)
|
||||
backGr = cv2.imread('../data/graf1.png')
|
||||
fgr = cv2.imread('../data/box.png')
|
||||
backGr = cv.imread('../data/graf1.png')
|
||||
fgr = cv.imread('../data/box.png')
|
||||
self.render = TestSceneRender(backGr, fgr, speed = 1)
|
||||
|
||||
def read(self, dst=None):
|
||||
noise = np.zeros(self.render.sceneBg.shape, np.int8)
|
||||
cv2.randn(noise, np.zeros(3), np.ones(3)*255*self.noise)
|
||||
cv.randn(noise, np.zeros(3), np.ones(3)*255*self.noise)
|
||||
|
||||
return True, cv2.add(self.render.getNextFrame(), noise, dtype=cv2.CV_8UC3)
|
||||
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(cv2.imread('../data/pca_test1.jpg'), deformation = True, speed = 1)
|
||||
self.render = TestSceneRender(cv.imread('../data/pca_test1.jpg'), deformation = True, speed = 1)
|
||||
|
||||
def read(self, dst=None):
|
||||
noise = np.zeros(self.render.sceneBg.shape, np.int8)
|
||||
cv2.randn(noise, np.zeros(3), np.ones(3)*255*self.noise)
|
||||
cv.randn(noise, np.zeros(3), np.ones(3)*255*self.noise)
|
||||
|
||||
return True, cv2.add(self.render.getNextFrame(), noise, dtype=cv2.CV_8UC3)
|
||||
return True, cv.add(self.render.getNextFrame(), noise, dtype=cv.CV_8UC3)
|
||||
|
||||
class Chess(VideoSynthBase):
|
||||
def __init__(self, **kw):
|
||||
@@ -130,10 +130,10 @@ class Chess(VideoSynthBase):
|
||||
self.t = 0
|
||||
|
||||
def draw_quads(self, img, quads, color = (0, 255, 0)):
|
||||
img_quads = cv2.projectPoints(quads.reshape(-1, 3), self.rvec, self.tvec, self.K, self.dist_coef) [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:
|
||||
cv2.fillConvexPoly(img, np.int32(q*4), color, cv2.LINE_AA, shift=2)
|
||||
cv.fillConvexPoly(img, np.int32(q*4), color, cv.LINE_AA, shift=2)
|
||||
|
||||
def render(self, dst):
|
||||
t = self.t
|
||||
@@ -186,11 +186,11 @@ def create_capture(source = 0, fallback = presets['chess']):
|
||||
try: cap = Class(**params)
|
||||
except: pass
|
||||
else:
|
||||
cap = cv2.VideoCapture(source)
|
||||
cap = cv.VideoCapture(source)
|
||||
if 'size' in params:
|
||||
w, h = map(int, params['size'].split('x'))
|
||||
cap.set(cv2.CAP_PROP_FRAME_WIDTH, w)
|
||||
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, h)
|
||||
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:
|
||||
@@ -216,14 +216,14 @@ if __name__ == '__main__':
|
||||
for i, cap in enumerate(caps):
|
||||
ret, img = cap.read()
|
||||
imgs.append(img)
|
||||
cv2.imshow('capture %d' % i, img)
|
||||
ch = cv2.waitKey(1)
|
||||
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)
|
||||
cv2.imwrite(fn, img)
|
||||
cv.imwrite(fn, img)
|
||||
print(fn, 'saved')
|
||||
shot_idx += 1
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
@@ -19,7 +19,7 @@ Keyboard shortcuts:
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
from multiprocessing.pool import ThreadPool
|
||||
from collections import deque
|
||||
@@ -50,11 +50,11 @@ if __name__ == '__main__':
|
||||
|
||||
def process_frame(frame, t0):
|
||||
# some intensive computation...
|
||||
frame = cv2.medianBlur(frame, 19)
|
||||
frame = cv2.medianBlur(frame, 19)
|
||||
frame = cv.medianBlur(frame, 19)
|
||||
frame = cv.medianBlur(frame, 19)
|
||||
return frame, t0
|
||||
|
||||
threadn = cv2.getNumberOfCPUs()
|
||||
threadn = cv.getNumberOfCPUs()
|
||||
pool = ThreadPool(processes = threadn)
|
||||
pending = deque()
|
||||
|
||||
@@ -70,7 +70,7 @@ if __name__ == '__main__':
|
||||
draw_str(res, (20, 20), "threaded : " + str(threaded_mode))
|
||||
draw_str(res, (20, 40), "latency : %.1f ms" % (latency.value*1000))
|
||||
draw_str(res, (20, 60), "frame interval : %.1f ms" % (frame_interval.value*1000))
|
||||
cv2.imshow('threaded video', res)
|
||||
cv.imshow('threaded video', res)
|
||||
if len(pending) < threadn:
|
||||
ret, frame = cap.read()
|
||||
t = clock()
|
||||
@@ -81,9 +81,9 @@ if __name__ == '__main__':
|
||||
else:
|
||||
task = DummyTask(process_frame(frame, t))
|
||||
pending.append(task)
|
||||
ch = cv2.waitKey(1)
|
||||
ch = cv.waitKey(1)
|
||||
if ch == ord(' '):
|
||||
threaded_mode = not threaded_mode
|
||||
if ch == 27:
|
||||
break
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
@@ -17,51 +17,51 @@ Keys:
|
||||
# Python 2/3 compatibility
|
||||
from __future__ import print_function
|
||||
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
|
||||
def decode_fourcc(v):
|
||||
v = int(v)
|
||||
return "".join([chr((v >> 8 * i) & 0xFF) for i in range(4)])
|
||||
|
||||
font = cv2.FONT_HERSHEY_SIMPLEX
|
||||
font = cv.FONT_HERSHEY_SIMPLEX
|
||||
color = (0, 255, 0)
|
||||
|
||||
cap = cv2.VideoCapture(0)
|
||||
cap.set(cv2.CAP_PROP_AUTOFOCUS, False) # Known bug: https://github.com/opencv/opencv/pull/5474
|
||||
cap = cv.VideoCapture(0)
|
||||
cap.set(cv.CAP_PROP_AUTOFOCUS, False) # Known bug: https://github.com/opencv/opencv/pull/5474
|
||||
|
||||
cv2.namedWindow("Video")
|
||||
cv.namedWindow("Video")
|
||||
|
||||
convert_rgb = True
|
||||
fps = int(cap.get(cv2.CAP_PROP_FPS))
|
||||
focus = int(min(cap.get(cv2.CAP_PROP_FOCUS) * 100, 2**31-1)) # ceil focus to C_LONG as Python3 int can go to +inf
|
||||
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
|
||||
|
||||
cv2.createTrackbar("FPS", "Video", fps, 30, lambda v: cap.set(cv2.CAP_PROP_FPS, v))
|
||||
cv2.createTrackbar("Focus", "Video", focus, 100, lambda v: cap.set(cv2.CAP_PROP_FOCUS, v / 100))
|
||||
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))
|
||||
|
||||
while True:
|
||||
status, img = cap.read()
|
||||
|
||||
fourcc = decode_fourcc(cap.get(cv2.CAP_PROP_FOURCC))
|
||||
fourcc = decode_fourcc(cap.get(cv.CAP_PROP_FOURCC))
|
||||
|
||||
fps = cap.get(cv2.CAP_PROP_FPS)
|
||||
fps = cap.get(cv.CAP_PROP_FPS)
|
||||
|
||||
if not bool(cap.get(cv2.CAP_PROP_CONVERT_RGB)):
|
||||
if not bool(cap.get(cv.CAP_PROP_CONVERT_RGB)):
|
||||
if fourcc == "MJPG":
|
||||
img = cv2.imdecode(img, cv2.IMREAD_GRAYSCALE)
|
||||
img = cv.imdecode(img, cv.IMREAD_GRAYSCALE)
|
||||
elif fourcc == "YUYV":
|
||||
img = cv2.cvtColor(img, cv2.COLOR_YUV2GRAY_YUYV)
|
||||
img = cv.cvtColor(img, cv.COLOR_YUV2GRAY_YUYV)
|
||||
else:
|
||||
print("unsupported format")
|
||||
break
|
||||
|
||||
cv2.putText(img, "Mode: {}".format(fourcc), (15, 40), font, 1.0, color)
|
||||
cv2.putText(img, "FPS: {}".format(fps), (15, 80), font, 1.0, color)
|
||||
cv2.imshow("Video", img)
|
||||
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 = cv2.waitKey(1)
|
||||
k = cv.waitKey(1)
|
||||
|
||||
if k == 27:
|
||||
break
|
||||
elif k == ord('g'):
|
||||
convert_rgb = not convert_rgb
|
||||
cap.set(cv2.CAP_PROP_CONVERT_RGB, convert_rgb)
|
||||
cap.set(cv.CAP_PROP_CONVERT_RGB, convert_rgb)
|
||||
|
||||
@@ -26,12 +26,12 @@ Keys
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import cv2 as cv
|
||||
from common import Sketcher
|
||||
|
||||
class App:
|
||||
def __init__(self, fn):
|
||||
self.img = cv2.imread(fn)
|
||||
self.img = cv.imread(fn)
|
||||
if self.img is None:
|
||||
raise Exception('Failed to load image file: %s' % fn)
|
||||
|
||||
@@ -49,14 +49,14 @@ class App:
|
||||
|
||||
def watershed(self):
|
||||
m = self.markers.copy()
|
||||
cv2.watershed(self.img, m)
|
||||
cv.watershed(self.img, m)
|
||||
overlay = self.colors[np.maximum(m, 0)]
|
||||
vis = cv2.addWeighted(self.img, 0.5, overlay, 0.5, 0.0, dtype=cv2.CV_8UC3)
|
||||
cv2.imshow('watershed', vis)
|
||||
vis = cv.addWeighted(self.img, 0.5, overlay, 0.5, 0.0, dtype=cv.CV_8UC3)
|
||||
cv.imshow('watershed', vis)
|
||||
|
||||
def run(self):
|
||||
while cv2.getWindowProperty('img', 0) != -1 or cv2.getWindowProperty('watershed', 0) != -1:
|
||||
ch = cv2.waitKey(50)
|
||||
while cv.getWindowProperty('img', 0) != -1 or cv.getWindowProperty('watershed', 0) != -1:
|
||||
ch = cv.waitKey(50)
|
||||
if ch == 27:
|
||||
break
|
||||
if ch >= ord('1') and ch <= ord('7'):
|
||||
@@ -72,7 +72,7 @@ class App:
|
||||
self.markers[:] = 0
|
||||
self.markers_vis[:] = self.img
|
||||
self.sketch.show()
|
||||
cv2.destroyAllWindows()
|
||||
cv.destroyAllWindows()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
Reference in New Issue
Block a user