-
Notifications
You must be signed in to change notification settings - Fork 2
/
thresh_mouse_rect.py
65 lines (49 loc) · 1.59 KB
/
thresh_mouse_rect.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import sys
import cv2
import numpy as np
from numba import jit
import ic_utils as ic
@jit
def threshold_impl(src, thresh, maxval):
width = src.shape[1]
height = src.shape[0]
dest = np.zeros_like(src)
for j in range(height):
for i in range(width):
if src[j, i] > thresh:
dest[j, i] = maxval
else:
dest[j, i] = 0
return dest
def main():
cap = ic.select_capture_source(sys.argv)
cv2.namedWindow('result')
cv2.createTrackbar('thresh', 'result', 128, 255, ic.do_nothing)
mstate = {
'selection': 'invalid',
'xybegin': (-1, -1),
'xyend': (-1, -1),
}
cv2.setMouseCallback('result', ic.on_mouse_rect, mstate)
while True:
grabbed, frame = cap.read()
if not grabbed:
break
img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
th = cv2.getTrackbarPos('thresh', 'result')
xbegin, ybegin = mstate['xybegin']
xend, yend = mstate['xyend']
if mstate['selection'] == 'valid':
roi = img[ybegin:yend, xbegin:xend]
thresh_roi = threshold_impl(roi, th, 255)
img[ybegin:yend, xbegin:xend] = thresh_roi
elif mstate['selection'] == 'ongoing':
cv2.rectangle(img, (xbegin, ybegin), (xend, yend),
color=0, thickness=2)
cv2.imshow('result', img)
key = cv2.waitKey(30)
if key == ord('q'):
break
cv2.destroyAllWindows()
if __name__ == '__main__':
main()