tracktext / main.py
leafspark's picture
Upload 18 files
1f3202f verified
raw
history blame
1.9 kB
import time
import numpy as np
from PIL import ImageGrab
import keyboard
def capture_screen():
start_time = 0
filename = ''
while True:
if keyboard.is_pressed('F7') and start_time == 0: # Check if F7 is pressed to start capturing
start_time = int(time.time()) # Record start time
filename = 'trainingData_{}.txt'.format(start_time)
break
while True:
try:
if keyboard.is_pressed('F8'): # Check if F7 is pressed to stop capturing
break
# Capture entire screen
screenshot = ImageGrab.grab()
# Resize to 128x128
screenshot = screenshot.resize((128, 64))
# Convert to grayscale
grayscale_img = screenshot.convert('L')
# Convert image to numpy array
grayscale_array = np.array(grayscale_img)
# Normalize pixel values between 0 and 1 and round to 2 decimal places
grayscale_array = np.round(grayscale_array / 255.0, 1)
# Flatten array to 1D
flattened_array = grayscale_array.flatten()
# Save the image with two decimal place precision
screenshot.save('captured_image.png')
# Capture WASD keys
keys = [
int(keyboard.is_pressed(key)) for key in ['w', 'a', 's', 'd']
]
# Append to training data file with Unix time
with open(filename, 'a') as f:
f.write("{data}\n")
f.write(str(flattened_array.tolist()) + '\n')
f.write("{action}\n")
f.write(str(keys) + '\n')
# Wait for 0.1 seconds
time.sleep(0.1)
except KeyboardInterrupt:
print("Stopping screen capture.")
break
if __name__ == "__main__":
while True:
capture_screen()