Created
July 2, 2022 10:09
-
-
Save Sanix-Darker/27ec19f51efab3d6702d0020514d7ef3 to your computer and use it in GitHub Desktop.
ascii-cam.py (with open-cv)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
try: | |
import cv2 | |
except ImportError: | |
from cv2 import cv2 | |
import numpy as np | |
def toASCII(frame, cols=120, rows=35): | |
frame = cv2.cvtColor(frame, cv2.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): | |
outer_left = int(i * cell_height) | |
inner_left = min(int((i + 1) * cell_height), height) | |
inner_right = int(j * cell_width) | |
outer_right = min(int((j + 1) * cell_width), width) | |
frame_ = frame[outer_left:inner_left, inner_right:outer_right] | |
gray = np.mean(frame_) | |
result += grayToChar(gray) | |
result += '\n' | |
return result | |
def grayToChar(gray): | |
CHAR_LIST = ' .:-=+*#%@' | |
num_chars = len(CHAR_LIST) | |
return CHAR_LIST[min(int(gray * num_chars / 255), num_chars - 1)] | |
def main(): | |
vc = cv2.VideoCapture('/dev/video4') | |
if vc.isOpened(): | |
rval, frame = vc.read() | |
else: | |
rval = False | |
while rval: | |
rval, frame = vc.read() | |
print(toASCII(frame)) | |
key = cv2.waitKey(50) # 50ms pause -> ~20fps | |
# Press echap to end | |
if key == 27: | |
break | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment