-
Notifications
You must be signed in to change notification settings - Fork 68
/
cam.py
executable file
·75 lines (58 loc) · 1.4 KB
/
cam.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
import cv2 as cv
import numpy as np
import os
import sys
import platform
from pynput.keyboard import *
def on_press(key):
finish(key)
def on_release(key):
pass
listener = Listener(on_press=on_press, on_release=on_release)
def finish(key):
if key == Key.esc:
listener.stop()
os._exit(0)
def main():
vc = None
if platform.system() == 'Windows':
vc = cv.VideoCapture(0,cv.CAP_DSHOW)
elif platform.system() == 'Linux':
vc = cv.VideoCapture(0)
if vc.isOpened():
rval, frame = vc.read()
else:
rval = False
if rval:
listener.start()
while rval:
rval, frame = vc.read()
print(toASCII(frame))
sys.exit()
def toASCII(frame, cols = 120, rows = 35):
frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
height, width = frame.shape
cell_width = width / cols
cell_height = height / rows
if cols > width or rows > height:
raise ValueError('Too many cols or rows.')
result = ""
for i in range(rows):
for j in range(cols):
gray = np.mean(
frame[int(i * cell_height):min(int((i + 1) * cell_height), height), int(j * cell_width):min(int((j + 1) * cell_width), width)]
)
result += grayToChar(gray)
result += '\n'
return result
def grayToChar(gray):
CHAR_LIST = ' .:-=+*#%@' # Replace by " .',;:clodxkO0KXNWM" if you want more precision.
num_chars = len(CHAR_LIST)
return CHAR_LIST[
min(
int(gray * num_chars / 255),
num_chars - 1
)
]
if __name__ == '__main__':
main()