Skip to content

Commit 43ff131

Browse files
committed
Merge pull request #1483 from alalek:python_cv2_to_cv
2 parents b0fc85b + 57ff363 commit 43ff131

File tree

25 files changed

+252
-252
lines changed

25 files changed

+252
-252
lines changed

modules/bgsegm/samples/evaluation.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import argparse
2-
import cv2
2+
import cv2 as cv
33
import glob
44
import numpy as np
55
import os
@@ -12,15 +12,15 @@
1212

1313

1414
ALGORITHMS_TO_EVALUATE = [
15-
(cv2.bgsegm.createBackgroundSubtractorMOG, 'MOG', {}),
16-
(cv2.bgsegm.createBackgroundSubtractorGMG, 'GMG', {}),
17-
(cv2.bgsegm.createBackgroundSubtractorCNT, 'CNT', {}),
18-
(cv2.bgsegm.createBackgroundSubtractorLSBP, 'LSBP-vanilla', {'nSamples': 20, 'LSBPRadius': 4, 'Tlower': 2.0, 'Tupper': 200.0, 'Tinc': 1.0, 'Tdec': 0.05, 'Rscale': 5.0, 'Rincdec': 0.05, 'LSBPthreshold': 8}),
19-
(cv2.bgsegm.createBackgroundSubtractorLSBP, 'LSBP-speed', {'nSamples': 10, 'LSBPRadius': 16, 'Tlower': 2.0, 'Tupper': 32.0, 'Tinc': 1.0, 'Tdec': 0.05, 'Rscale': 10.0, 'Rincdec': 0.005, 'LSBPthreshold': 8}),
20-
(cv2.bgsegm.createBackgroundSubtractorLSBP, 'LSBP-quality', {'nSamples': 20, 'LSBPRadius': 16, 'Tlower': 2.0, 'Tupper': 32.0, 'Tinc': 1.0, 'Tdec': 0.05, 'Rscale': 10.0, 'Rincdec': 0.005, 'LSBPthreshold': 8}),
21-
(cv2.bgsegm.createBackgroundSubtractorLSBP, 'LSBP-camera-motion-compensation', {'mc': 1}),
22-
(cv2.bgsegm.createBackgroundSubtractorGSOC, 'GSOC', {}),
23-
(cv2.bgsegm.createBackgroundSubtractorGSOC, 'GSOC-camera-motion-compensation', {'mc': 1})
15+
(cv.bgsegm.createBackgroundSubtractorMOG, 'MOG', {}),
16+
(cv.bgsegm.createBackgroundSubtractorGMG, 'GMG', {}),
17+
(cv.bgsegm.createBackgroundSubtractorCNT, 'CNT', {}),
18+
(cv.bgsegm.createBackgroundSubtractorLSBP, 'LSBP-vanilla', {'nSamples': 20, 'LSBPRadius': 4, 'Tlower': 2.0, 'Tupper': 200.0, 'Tinc': 1.0, 'Tdec': 0.05, 'Rscale': 5.0, 'Rincdec': 0.05, 'LSBPthreshold': 8}),
19+
(cv.bgsegm.createBackgroundSubtractorLSBP, 'LSBP-speed', {'nSamples': 10, 'LSBPRadius': 16, 'Tlower': 2.0, 'Tupper': 32.0, 'Tinc': 1.0, 'Tdec': 0.05, 'Rscale': 10.0, 'Rincdec': 0.005, 'LSBPthreshold': 8}),
20+
(cv.bgsegm.createBackgroundSubtractorLSBP, 'LSBP-quality', {'nSamples': 20, 'LSBPRadius': 16, 'Tlower': 2.0, 'Tupper': 32.0, 'Tinc': 1.0, 'Tdec': 0.05, 'Rscale': 10.0, 'Rincdec': 0.005, 'LSBPthreshold': 8}),
21+
(cv.bgsegm.createBackgroundSubtractorLSBP, 'LSBP-camera-motion-compensation', {'mc': 1}),
22+
(cv.bgsegm.createBackgroundSubtractorGSOC, 'GSOC', {}),
23+
(cv.bgsegm.createBackgroundSubtractorGSOC, 'GSOC-camera-motion-compensation', {'mc': 1})
2424
]
2525

2626

@@ -54,14 +54,14 @@ def evaluate_algorithm(gt, frames, algo, algo_arguments):
5454
t_start = time.time()
5555

5656
for i in range(len(gt)):
57-
frame = np.uint8(cv2.imread(frames[i], cv2.IMREAD_COLOR))
57+
frame = np.uint8(cv.imread(frames[i], cv.IMREAD_COLOR))
5858
mask.append(bgs.apply(frame))
5959

6060
average_duration = (time.time() - t_start) / len(gt)
6161
average_precision, average_recall, average_f1, average_accuracy = [], [], [], []
6262

6363
for i in range(len(gt)):
64-
gt_mask = np.uint8(cv2.imread(gt[i], cv2.IMREAD_GRAYSCALE))
64+
gt_mask = np.uint8(cv.imread(gt[i], cv.IMREAD_GRAYSCALE))
6565
roi = ((gt_mask == 255) | (gt_mask == 0))
6666
if roi.sum() > 0:
6767
gt_answer, answer = gt_mask[roi], mask[i][roi]

modules/bgsegm/samples/viz.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import numpy as np
2-
import cv2
2+
import cv2 as cv
33
import argparse
44
import os
55

@@ -17,22 +17,22 @@ def main():
1717
f = map(lambda x: os.path.join(args.frames, x), os.listdir(args.frames))
1818
f.sort()
1919

20-
gt = np.uint8(map(lambda x: cv2.imread(x, cv2.IMREAD_GRAYSCALE), gt))
21-
f = np.uint8(map(lambda x: cv2.imread(x, cv2.IMREAD_COLOR), f))
20+
gt = np.uint8(map(lambda x: cv.imread(x, cv.IMREAD_GRAYSCALE), gt))
21+
f = np.uint8(map(lambda x: cv.imread(x, cv.IMREAD_COLOR), f))
2222

2323
if not args.lsbp:
24-
bgs = cv2.bgsegm.createBackgroundSubtractorGSOC()
24+
bgs = cv.bgsegm.createBackgroundSubtractorGSOC()
2525
else:
26-
bgs = cv2.bgsegm.createBackgroundSubtractorLSBP()
26+
bgs = cv.bgsegm.createBackgroundSubtractorLSBP()
2727

2828
for i in xrange(f.shape[0]):
29-
cv2.imshow('Frame', f[i])
30-
cv2.imshow('Ground-truth', gt[i])
29+
cv.imshow('Frame', f[i])
30+
cv.imshow('Ground-truth', gt[i])
3131
mask = bgs.apply(f[i])
3232
bg = bgs.getBackgroundImage()
33-
cv2.imshow('BG', bg)
34-
cv2.imshow('Output mask', mask)
35-
k = cv2.waitKey(0)
33+
cv.imshow('BG', bg)
34+
cv.imshow('Output mask', mask)
35+
k = cv.waitKey(0)
3636
if k == 27:
3737
break
3838

modules/bgsegm/samples/viz_synthetic_seq.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import cv2
1+
import cv2 as cv
22
import argparse
33

44

@@ -9,15 +9,15 @@ def main():
99
argparser.add_argument('-o', '--obj', help='Object image. It must be strictly smaller than background.', required=True)
1010
args = argparser.parse_args()
1111

12-
bg = cv2.imread(args.background)
13-
obj = cv2.imread(args.obj)
14-
generator = cv2.bgsegm.createSyntheticSequenceGenerator(bg, obj)
12+
bg = cv.imread(args.background)
13+
obj = cv.imread(args.obj)
14+
generator = cv.bgsegm.createSyntheticSequenceGenerator(bg, obj)
1515

1616
while True:
1717
frame, mask = generator.getNextFrame()
18-
cv2.imshow('Generated frame', frame)
19-
cv2.imshow('Generated mask', mask)
20-
k = cv2.waitKey(int(1000.0 / 30))
18+
cv.imshow('Generated frame', frame)
19+
cv.imshow('Generated mask', mask)
20+
k = cv.waitKey(int(1000.0 / 30))
2121
if k == 27:
2222
break
2323

modules/bioinspired/doc/retina.markdown

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ Bioinspired Module Retina Introduction {#bioinspired_retina}
44
Retina class overview
55
---------------------
66

7-
@note do not forget that the retina model is included in the following namespace : cv::bioinspired with C++ and in cv2.bioinspired with Python
7+
@note do not forget that the retina model is included in the following namespace : cv::bioinspired with C++ and in cv.bioinspired with Python
88

99
### Introduction
1010

@@ -425,14 +425,14 @@ Python version
425425

426426
@code{.py}
427427
#import OpenCV module
428-
import cv2
428+
import cv2 as cv
429429

430430
#setup webcam reader
431-
videoHandler = cv2.VideoCapture(0)
431+
videoHandler = cv.VideoCapture(0)
432432
succeed, inputImage=videoHandler.read()
433433

434434
#allocate a retina instance with input size equal to the one of the loaded image
435-
retina = cv2.bioinspired.createRetina((inputImage.shape[1], inputImage.shape[0]))
435+
retina = cv.bioinspired.createRetina((inputImage.shape[1], inputImage.shape[0]))
436436

437437
#retina parameters management methods use sample
438438
#-> save current (here default) retina parameters to a xml file (you may use it only one time to get the file and modify it)
@@ -446,7 +446,7 @@ while stillProcess is True:
446446

447447
#grab a new frame and display it
448448
stillProcess, inputImage=videoHandler.read()
449-
cv2.imshow('input frame', inputImage)
449+
cv.imshow('input frame', inputImage)
450450

451451
#run retina on the input image
452452
retina.run(inputImage)
@@ -456,11 +456,11 @@ while stillProcess is True:
456456
retinaOut_magno=retina.getMagno()
457457

458458
#draw retina outputs
459-
cv2.imshow('retina parvo out', retinaOut_parvo)
460-
cv2.imshow('retina magno out', retinaOut_magno)
459+
cv.imshow('retina parvo out', retinaOut_parvo)
460+
cv.imshow('retina magno out', retinaOut_magno)
461461

462462
#wait a little to let the time for figures to be drawn
463-
cv2.waitKey(2)
463+
cv.waitKey(2)
464464
@endcode
465465

466466

modules/bioinspired/tutorials/retina_illusion/retina_illusion.markdown

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -117,10 +117,10 @@ iterations. This is an arbitrary number that we found experimentally to be (more
117117
enough
118118

119119
@code{.py}
120-
import cv2
120+
import cv2 as cv
121121

122-
inputImage = cv2.imread('checkershadow_illusion4med.jpg', 1)
123-
retina = cv2.bioinspired.createRetina((inputImage.shape[1], inputImage.shape[0]))
122+
inputImage = cv.imread('checkershadow_illusion4med.jpg', 1)
123+
retina = cv.bioinspired.createRetina((inputImage.shape[1], inputImage.shape[0]))
124124

125125
# the retina object is created with default parameters. If you want to read
126126
# the parameters from an external XML file, uncomment the next line
@@ -134,15 +134,15 @@ for i in range(20):
134134
retinaOut_parvo = retina.getParvo()
135135

136136
# show both the original image and the processed one
137-
cv2.imshow('image', inputImage)
138-
cv2.imshow('retina parvo out', retinaOut_parvo)
137+
cv.imshow('image', inputImage)
138+
cv.imshow('retina parvo out', retinaOut_parvo)
139139

140140
# wait for a key to be pressed and exit
141-
cv2.waitKey(0)
142-
cv2.destroyAllWindows()
141+
cv.waitKey(0)
142+
cv.destroyAllWindows()
143143

144144
# write the output image on a file
145-
cv2.imwrite('checkershadow_parvo.png', retinaOut_parvo)
145+
cv.imwrite('checkershadow_parvo.png', retinaOut_parvo)
146146
@endcode
147147

148148
Whatever method you used to process the image, you should end up

modules/optflow/samples/motempl.py

Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
#!/usr/bin/env python
22
import numpy as np
3-
import cv2
3+
import cv2 as cv
44

55
MHI_DURATION = 0.5
66
DEFAULT_THRESHOLD = 32
@@ -12,12 +12,12 @@ def nothing(dummy):
1212
pass
1313

1414
def draw_motion_comp(vis, (x, y, w, h), angle, color):
15-
cv2.rectangle(vis, (x, y), (x+w, y+h), (0, 255, 0))
15+
cv.rectangle(vis, (x, y), (x+w, y+h), (0, 255, 0))
1616
r = min(w/2, h/2)
1717
cx, cy = x+w/2, y+h/2
1818
angle = angle*np.pi/180
19-
cv2.circle(vis, (cx, cy), r, color, 3)
20-
cv2.line(vis, (cx, cy), (int(cx+np.cos(angle)*r), int(cy+np.sin(angle)*r)), color, 3)
19+
cv.circle(vis, (cx, cy), r, color, 3)
20+
cv.line(vis, (cx, cy), (int(cx+np.cos(angle)*r), int(cy+np.sin(angle)*r)), color, 3)
2121

2222
if __name__ == '__main__':
2323
import sys
@@ -26,12 +26,12 @@ def draw_motion_comp(vis, (x, y, w, h), angle, color):
2626
except:
2727
video_src = 0
2828

29-
cv2.namedWindow('motempl')
29+
cv.namedWindow('motempl')
3030
visuals = ['input', 'frame_diff', 'motion_hist', 'grad_orient']
31-
cv2.createTrackbar('visual', 'motempl', 2, len(visuals)-1, nothing)
32-
cv2.createTrackbar('threshold', 'motempl', DEFAULT_THRESHOLD, 255, nothing)
31+
cv.createTrackbar('visual', 'motempl', 2, len(visuals)-1, nothing)
32+
cv.createTrackbar('threshold', 'motempl', DEFAULT_THRESHOLD, 255, nothing)
3333

34-
cam = cv2.VideoCapture(video_src)
34+
cam = cv.VideoCapture(video_src)
3535
if not cam.isOpened():
3636
print("could not open video_src " + str(video_src) + " !\n")
3737
sys.exit(1)
@@ -48,27 +48,27 @@ def draw_motion_comp(vis, (x, y, w, h), angle, color):
4848
ret, frame = cam.read()
4949
if ret == False:
5050
break
51-
frame_diff = cv2.absdiff(frame, prev_frame)
52-
gray_diff = cv2.cvtColor(frame_diff, cv2.COLOR_BGR2GRAY)
53-
thrs = cv2.getTrackbarPos('threshold', 'motempl')
54-
ret, motion_mask = cv2.threshold(gray_diff, thrs, 1, cv2.THRESH_BINARY)
55-
timestamp = cv2.getTickCount() / cv2.getTickFrequency()
56-
cv2.motempl.updateMotionHistory(motion_mask, motion_history, timestamp, MHI_DURATION)
57-
mg_mask, mg_orient = cv2.motempl.calcMotionGradient( motion_history, MAX_TIME_DELTA, MIN_TIME_DELTA, apertureSize=5 )
58-
seg_mask, seg_bounds = cv2.motempl.segmentMotion(motion_history, timestamp, MAX_TIME_DELTA)
51+
frame_diff = cv.absdiff(frame, prev_frame)
52+
gray_diff = cv.cvtColor(frame_diff, cv.COLOR_BGR2GRAY)
53+
thrs = cv.getTrackbarPos('threshold', 'motempl')
54+
ret, motion_mask = cv.threshold(gray_diff, thrs, 1, cv.THRESH_BINARY)
55+
timestamp = cv.getTickCount() / cv.getTickFrequency()
56+
cv.motempl.updateMotionHistory(motion_mask, motion_history, timestamp, MHI_DURATION)
57+
mg_mask, mg_orient = cv.motempl.calcMotionGradient( motion_history, MAX_TIME_DELTA, MIN_TIME_DELTA, apertureSize=5 )
58+
seg_mask, seg_bounds = cv.motempl.segmentMotion(motion_history, timestamp, MAX_TIME_DELTA)
5959

60-
visual_name = visuals[cv2.getTrackbarPos('visual', 'motempl')]
60+
visual_name = visuals[cv.getTrackbarPos('visual', 'motempl')]
6161
if visual_name == 'input':
6262
vis = frame.copy()
6363
elif visual_name == 'frame_diff':
6464
vis = frame_diff.copy()
6565
elif visual_name == 'motion_hist':
6666
vis = np.uint8(np.clip((motion_history-(timestamp-MHI_DURATION)) / MHI_DURATION, 0, 1)*255)
67-
vis = cv2.cvtColor(vis, cv2.COLOR_GRAY2BGR)
67+
vis = cv.cvtColor(vis, cv.COLOR_GRAY2BGR)
6868
elif visual_name == 'grad_orient':
6969
hsv[:,:,0] = mg_orient/2
7070
hsv[:,:,2] = mg_mask*255
71-
vis = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
71+
vis = cv.cvtColor(hsv, cv.COLOR_HSV2BGR)
7272

7373
for i, rect in enumerate([(0, 0, w, h)] + list(seg_bounds)):
7474
x, y, rw, rh = rect
@@ -79,16 +79,16 @@ def draw_motion_comp(vis, (x, y, w, h), angle, color):
7979
orient_roi = mg_orient [y:y+rh,x:x+rw]
8080
mask_roi = mg_mask [y:y+rh,x:x+rw]
8181
mhi_roi = motion_history[y:y+rh,x:x+rw]
82-
if cv2.norm(silh_roi, cv2.NORM_L1) < area*0.05:
82+
if cv.norm(silh_roi, cv.NORM_L1) < area*0.05:
8383
continue
84-
angle = cv2.motempl.calcGlobalOrientation(orient_roi, mask_roi, mhi_roi, timestamp, MHI_DURATION)
84+
angle = cv.motempl.calcGlobalOrientation(orient_roi, mask_roi, mhi_roi, timestamp, MHI_DURATION)
8585
color = ((255, 0, 0), (0, 0, 255))[i == 0]
8686
draw_motion_comp(vis, rect, angle, color)
8787

88-
cv2.putText(vis, visual_name, (20, 20), cv2.FONT_HERSHEY_PLAIN, 1.0, (200,0,0))
89-
cv2.imshow('motempl', vis)
88+
cv.putText(vis, visual_name, (20, 20), cv.FONT_HERSHEY_PLAIN, 1.0, (200,0,0))
89+
cv.imshow('motempl', vis)
9090

9191
prev_frame = frame.copy()
92-
if 0xFF & cv2.waitKey(5) == 27:
92+
if 0xFF & cv.waitKey(5) == 27:
9393
break
94-
cv2.destroyAllWindows()
94+
cv.destroyAllWindows()

modules/optflow/src/learn_prior.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import os
44
import sys
55
import numpy as np
6-
import cv2
6+
import cv2 as cv
77
import struct
88
import argparse
99
from math import sqrt
@@ -73,7 +73,7 @@ def load_flo(flo):
7373

7474
def get_w(m):
7575
s = m.shape
76-
w = cv2.dct(m)
76+
w = cv.dct(m)
7777
w *= 2.0 / sqrt(s[0] * s[1])
7878
#w[0,0] *= 0.5
7979
w[:, 0] *= sqrt(0.5)

modules/ovis/samples/aruco_ar_demo.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,35 @@
1-
import cv2
21
import numpy as np
2+
import cv2 as cv
33

44
# aruco
5-
adict = cv2.aruco.Dictionary_get(cv2.aruco.DICT_4X4_50)
6-
cv2.imshow("marker", cv2.aruco.drawMarker(adict, 0, 400))
5+
adict = cv.aruco.Dictionary_get(cv.aruco.DICT_4X4_50)
6+
cv.imshow("marker", cv.aruco.drawMarker(adict, 0, 400))
77

88
# random calibration data. your mileage may vary.
99
imsize = (800, 600)
10-
K = cv2.getDefaultNewCameraMatrix(np.diag([800, 800, 1]), imsize, True)
10+
K = cv.getDefaultNewCameraMatrix(np.diag([800, 800, 1]), imsize, True)
1111

1212
# AR scene
13-
cv2.ovis.addResourceLocation("packs/Sinbad.zip") # shipped with Ogre
13+
cv.ovis.addResourceLocation("packs/Sinbad.zip") # shipped with Ogre
1414

15-
win = cv2.ovis.createWindow("arucoAR", imsize, flags=0)
15+
win = cv.ovis.createWindow("arucoAR", imsize, flags=0)
1616
win.createEntity("figure", "Sinbad.mesh", (0, 0, -5), (-1.57, 0, 0))
1717
win.createLightEntity("sun", (0, 0, -100))
1818

1919
# video capture
20-
cap = cv2.VideoCapture(0)
21-
cap.set(cv2.CAP_PROP_FRAME_WIDTH, imsize[0])
22-
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, imsize[1])
20+
cap = cv.VideoCapture(0)
21+
cap.set(cv.CAP_PROP_FRAME_WIDTH, imsize[0])
22+
cap.set(cv.CAP_PROP_FRAME_HEIGHT, imsize[1])
2323

24-
while cv2.ovis.renderOneFrame():
24+
while cv.ovis.renderOneFrame():
2525
img = cap.read()[1]
2626
win.setBackground(img)
27-
corners, ids = cv2.aruco.detectMarkers(img, adict)[:2]
27+
corners, ids = cv.aruco.detectMarkers(img, adict)[:2]
2828

29-
cv2.waitKey(1)
29+
cv.waitKey(1)
3030

3131
if ids is None:
3232
continue
3333

34-
rvecs, tvecs = cv2.aruco.estimatePoseSingleMarkers(corners, 5, K, None)[:2]
34+
rvecs, tvecs = cv.aruco.estimatePoseSingleMarkers(corners, 5, K, None)[:2]
3535
win.setCameraPose(tvecs[0].ravel(), rvecs[0].ravel(), invert=True)

0 commit comments

Comments
 (0)