最近在弄无人驾驶的项目,真实开车还是太麻烦了,打算在游戏里实现仿真驾驶,一般的游戏都没有视觉的接口所以选择录屏来解决这个问题。
from PIL import ImageGrab
import threading
import numpy as np
import cv2
import time
import os
class myRecord:
def __init__(self,width,height):
if not os.path.exists("config.txt"):
os.system(r"touch {}".format("config.txt"))
f = open('config.txt',"r")
line = f.readline()
if len(line) != 0:
print(line.split(" "))
self.left = int(line.split(" ")[0])
self.top = int(line.split(" ")[1])
self.right = int(line.split(" ")[2])
self.bottom = int(line.split(" ")[3])
else:
self.left, self.right, self.top, self.bottom = 0,width,0,height
f.close()
self.width = width
self.height = height
self.recordThread = threading.Thread(target=self.record)
self.recordThread.start()
def record(self):
cv2.namedWindow('image')
cv2.namedWindow('tool')
cv2.createTrackbar('left', 'tool', self.left, self.width, self.left_callback)
cv2.createTrackbar('top', 'tool', self.top, self.height, self.top_callback)
cv2.createTrackbar('right', 'tool', self.right , self.width, self.right_callback)
cv2.createTrackbar('bottom', 'tool', self.bottom, self.height, self.bottom_callback)
lastTime = time.time()
write_flag = 0
while True:
im = ImageGrab.grab((self.left,self.top,self.right,self.bottom)) # 获得当前屏幕
imm = cv2.cvtColor(np.array(im), cv2.COLOR_RGB2BGR) # 转为opencv的BGR格式
scale = 1.5
show = cv2.resize(imm,(int(self.right/scale - self.left/scale),int(self.bottom/scale - self.top/scale)))
cv2.putText(show, "delay:" + str(round(time.time() - lastTime,2)) + "s", (50, 300), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (255, 255, 255), 2)
lastTime = time.time()
cv2.imshow('image', show) # 显示
if write_flag == 1:
if not os.path.exists("record"):
os.makedirs("record")
cv2.imwrite("record/" + str(time.time()) + ".jpg",imm)
key = cv2.waitKey(1) & 0xFF
if key == ord('q'): # q键推出
break
elif key == ord('s'): # q键推出
print("开始录制")
write_flag = 1
cv2.destroyAllWindows()
def left_callback(self,x):
self.left = x
if self.left >= self.right:
self.left = self.right - 5
f = open('config.txt',"w")
f.write("{} {} {} {}".format(self.left,self.top,self.right,self.bottom))
f.close()
def right_callback(self,x):
self.right = self.width - x
if self.left >= self.right:
self.right = self.left + 5
f = open('config.txt',"w")
f.write("{} {} {} {}".format(self.left,self.top,self.right,self.bottom))
f.close()
def top_callback(self, x):
self.top = x
if self.top >= self.bottom:
self.top = self.bottom - 5
f = open('config.txt',"w")
f.write("{} {} {} {}".format(self.left,self.top,self.right,self.bottom))
f.close()
def bottom_callback(self, x):
self.bottom = self.height - x
if self.top >= self.bottom:
self.bottom = self.top + 5
f = open('config.txt',"w")
f.write("{} {} {} {}".format(self.left,self.top,self.right,self.bottom))
f.close()
if __name__ == '__main__':
window = ImageGrab.grab() # 获得当前屏幕,存窗口大小
width,height = window.size
r = myRecord(width,height)