-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathex2b.py
88 lines (70 loc) · 2.5 KB
/
ex2b.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import time
import sys
import cv2
import numpy as np
from skimage.util import img_as_float
# from skimage.util import img_as_ubyte
def show_in_moved_window(win_name, img, x, y):
"""
Show an image in a window, where the position of the window can be given
"""
cv2.namedWindow(win_name)
cv2.moveWindow(win_name, x, y)
cv2.imshow(win_name, img)
def capture_from_camera_and_show_images():
print("Starting image capture")
print("Opening connection to camera")
url = 0
use_droid_cam = False
if use_droid_cam:
url = "http://192.168.1.120:4747/video"
cap = cv2.VideoCapture(url)
# cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("Cannot open camera")
sys.exit()
print("Starting camera loop")
# Get first image
ret, frame = cap.read()
# if frame is read correctly, ret is True
if not ret:
print("Can't receive frame")
sys.exit()
# Transform image to gray scale and then to float, so we can do some processing
frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
frame_gray = img_as_float(frame_gray)
# To keep track of frames per second
start_time = time.time()
n_frames = 0
stop = False
while not stop:
ret, new_frame = cap.read()
if not ret:
print("Can't receive frame. Exiting ...")
break
# Transform image to gray scale and then to float, so we can do some processing
new_frame_gray = cv2.cvtColor(new_frame, cv2.COLOR_BGR2GRAY)
new_frame_gray = img_as_float(new_frame_gray)
# Compute difference image
dif_img = np.abs(new_frame_gray - frame_gray)
# Keep track of frames-per-second (FPS)
n_frames = n_frames + 1
elapsed_time = time.time() - start_time
fps = int(n_frames / elapsed_time)
# Put the FPS text on the new_frame
str_out = f"fps: {fps}"
font = cv2.FONT_HERSHEY_COMPLEX
cv2.putText(new_frame, str_out, (100, 100), font, 1, 255, 1)
# Display the resulting frame
show_in_moved_window('Input', new_frame, 0, 10)
show_in_moved_window('Input gray', new_frame_gray, 600, 10)
show_in_moved_window('Difference image', dif_img, 1200, 10)
# Old frame is updated
frame_gray = new_frame_gray
if cv2.waitKey(1) == ord('q'):
stop = True
print("Stopping image loop")
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
capture_from_camera_and_show_images()