
Interpret web cam output in halftones! Generate your own cool pictures with py5!
Read more about Halftone: https://en.wikipedia.org/wiki/Halftone
import os
from datetime import datetime
import cv2
import py5
"""
- Simple interactive canvas with realtime webcam imagery.
- Basic commands for clear, save, pause/resume and exit.
- Webcam output is converted to half-tone output.
"""
STEP = 20 # grid spacing in pixels (smaller = denser dots)
DOT_MAX = STEP # max dot diameter
INVERT = False # flip black/white mapping
is_paused = False
def setup():
global webcam
py5.size(py5.display_width, py5.display_height)
py5.window_resizable(True)
webcam = cv2.VideoCapture(0)
def draw():
py5.background(255)
_, frame = webcam.read()
img = py5.create_image_from_numpy(frame, bands="BGR")
# Draw halftone
py5.no_stroke()
# Optionally scale the camera to match the window
py5.push_matrix()
sx = py5.width / img.width
sy = py5.height / img.height
py5.scale(sx, sy)
# Use HSB brightness() mapping
for y in range(0, img.height, STEP):
for x in range(0, img.width, STEP):
c = img.get_pixels(x, y) # color at sample point
b = py5.brightness(c) # 0..100 (in Processing it’s 0..100 by default)
# Map brightness to dot size: dark -> big, light -> small
if INVERT:
d = py5.remap(b, 0, 100, 0.5, DOT_MAX) # light -> bigger
else:
d = py5.remap(b, 0, 100, DOT_MAX, 0.5) # dark -> bigger
py5.fill(0) # black ink
# Center dots in each STEP×STEP cell
py5.circle(x + STEP * 0.5, y + STEP * 0.5, d)
py5.pop_matrix()
def save_artwork():
# Get the directory of the current script
script_dir = os.path.dirname(os.path.abspath(__file__))
# Get the name of the python file without the extension
file_stem = os.path.splitext(os.path.basename(__file__))[0]
# Create a timestamp
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
# Construct the full path and save the frame
save_path = os.path.join(script_dir, f"{file_stem}_{timestamp}.png")
py5.save_frame(save_path)
print(f"Artwork is now saved to {save_path}")
def key_pressed():
global is_paused
if py5.key == 's':
print(f"Save key pressed. Saving artwork...")
save_artwork()
elif py5.key == 'p':
if is_paused:
py5.loop()
print("Sketch resumed.")
else:
py5.no_loop()
print("Sketch paused.")
is_paused = not is_paused
elif py5.key == 'c':
print(f"Clear key pressed. Clearing sketch...")
py5.background(0)
elif py5.key == 'e' or py5.key == 'q' or py5.key == 'esc':
print(f"Exit key pressed. Closing sketch...")
py5.exit_sketch() # This closes the window and ends the program
webcam.release()
else:
print(f"Invalid key pressed...")
py5.run_sketch()