环境: ubuntu 16.04 / HUWEI P10 / android 8.0
1.安装adb
$ sudo apt-get install adb
2.手机通过USB连接到电脑,选择MTP(文件传输)模式,并开启USB调试。
3.测试adb连接
$ adb devices
成功则显示:
List of devices attached
SJE**********659 device
4.通过shell脚本获取手机截屏,并传输至电脑指定文件夹
#! /bin/bash
# get a screen capture
adb shell screencap -p /sdcard/test.png
# set directory and name for images
dir=./
name=${dir}"test.png"
echo "${name}"
# pull image
adb pull /sdcard/test.png "$name"
获取到图片后则可以进行各种后续图像处理,识别工作,也可以通过adb命令向手机发送如点击等操作指令。
介绍一个使用adb,shell和Python脚本玩找五仁月饼游戏的大致实现。游戏的大致内容是屏幕上会出现MxN个排列的月饼,其中一个是五仁月饼,找出后,下一个五仁月饼会变换位置,继续找。
基本思路是用一个Python脚本实现两帧图像之间的差别计算,然后根据帧差图像特点按一定方法找出五仁月饼所在地,使用shell组织游戏流程: 拉取图片,计算位置,更新图片。
Python 脚本
import cv2
test1 = cv2.imread("./test1.png")
test2 = cv2.imread("./test2.png")
# calculate the diff
diff = cv2.absdiff(test1, test2)
# find the change point
img_gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
# resize to speed up
img_gray = cv2.resize(img_gray,(108,192),interpolation=cv2.INTER_CUBIC)
height,width = img_gray.shape
max=0
# position to locate
x = 0
y = 0
for i in range(height):
for j in range(width):
if img_gray[i,j] > max:
x=j
y=i
cv2.circle(diff,(x*10,y*10),22,(0,0,255),5)
cv2.imwrite("./diff.jpg", diff)
# send params to shell via print()
print(str(x*10)+" "+str(y*10))
Shell 脚本
#! /bin/bash
declare -i i=1
while ((i<=40));do
let ++i
# get screen captured image
adb shell screencap -p /sdcard/test.png
dir=./
name=${dir}"test2.png" # need save test1.png in advance
echo "${name}"
adb pull /sdcard/test.png "$name"
# calculate the position
r=`python img_process.py`
echo $r
# send click
adb shell input tap $r
# update image
rm test1.png
mv test2.png test1.png
done