【Python自动驾驶GTA5】1-获取图像

前期准备

  1. 准备去steam购买并安装GTA V
  2. 安装anaconda,我安装的版本是 conda 4.3.30 (python 3.6.1)
  3. 安装openCV,conda install -c conda-forge opencv。这里除了openCV其他的组件anaconda有默认安装
  4. 打开GTA V设置窗口大小为800*600,放置在左上角

获取游戏画面 - part-1-Getting-Visuals.py

使用的组件简介:

  • PIL:图像库,ImageGrab工具用来抓取画面
  • cv2:大名鼎鼎的openCV,最知名的一个computer vision库
  • numpy:著名的科学计算库
  • time:python自带的时间工具
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import numpy as np
from PIL import ImageGrab
import cv2
import time

def screen_record():
last_time = time.time()
while(True):
# 800x600 windowed mode for GTA 5, at the top left position of your main screen.
# 40 px accounts for title bar.
printscreen = np.array(ImageGrab.grab(bbox=(0,40,800,640)))
print('loop took {} seconds'.format(time.time()-last_time))
last_time = time.time()
cv2.imshow('window',cv2.cvtColor(printscreen, cv2.COLOR_BGR2RGB))
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break

screen_record()
  1. screen_record这个函数就是用来获取游戏实时画面。在while循环直到手动推出
  2. cv2.imshow会打开一个新的程序窗口来显示内容

按照sentdex这个程序的方法我发现画面只有大概12帧,大大低于我的预期。于是自己搜索了一番,找到了更好的库,mss。同样是结合OpenCV和Numpy,帧数现在可以提升到40帧以上。

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
import numpy as np
import cv2
import time
import mss

def screen_record():
with mss.mss() as sct:
# Part of the screen to capture
monitor = {'top': 40, 'left': 0, 'width': 800, 'height': 640}

while 'Screen capturing':
last_time = time.time()

# Get raw pixels from the screen, save it to a Numpy array
img = numpy.array(sct.grab(monitor))

# Display the picture
cv2.imshow('OpenCV/Numpy normal', img)

# Display the picture in grayscale
# cv2.imshow('OpenCV/Numpy grayscale',
# cv2.cvtColor(img, cv2.COLOR_BGRA2GRAY))

print('fps: {0}'.format(1 / (time.time()-last_time)))

# Press "q" to quit
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break

screen_record()

这个库可以这么快的原因应该是用了ctypes

Reference

教程的内容大部分来自sentdex的Python plays Grand Theft Auto V系列

聊聊Python ctypes 模块