forked from Karenw1004/Deeppicar-v3
-
Notifications
You must be signed in to change notification settings - Fork 4
/
camera-webcam.py
67 lines (56 loc) · 1.46 KB
/
camera-webcam.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
66
67
import cv2
from threading import Thread,Lock
import time
use_thread = False
need_flip = False
cap = None
frame = None
# public API
# init(), read_frame(), stop()
def init(res=(320, 240), fps=30, threading=True):
print ("Initilize camera.")
global cap, use_thread, frame, cam_thr
cap = cv2.VideoCapture(0)
cap.set(3, res[0]) # width
cap.set(4, res[1]) # height
cap.set(5, fps)
# start the camera thread
if threading:
use_thread = True
cam_thr = Thread(target=__update, args=())
cam_thr.start()
print ("start camera thread")
time.sleep(1.0)
else:
print ("No camera threading.")
if need_flip == True:
print ("camera is Flipped")
print ("camera init completed.")
def __update():
global frame
while use_thread:
ret, tmp_frame = cap.read() # blocking read
if need_flip == True:
frame = cv2.flip(tmp_frame, -1)
else:
frame = tmp_frame
print ("Camera thread finished...")
cap.release()
def read_frame():
global frame
if not use_thread:
ret, frame = cap.read() # blocking read
return frame
def stop():
global use_thread
print ("Close the camera.")
use_thread = False
if __name__ == "__main__":
init()
while True:
frame = read_frame()
cv2.imshow('frame', frame)
ch = cv2.waitKey(1) & 0xFF
if ch == ord('q'):
stop()
break