Skip to content

Instantly share code, notes, and snippets.

@FindHao
Last active January 10, 2018 14:35
Show Gist options
  • Save FindHao/afd28f44eb85448b45c2c44e2fc472f3 to your computer and use it in GitHub Desktop.
Save FindHao/afd28f44eb85448b45c2c44e2fc472f3 to your computer and use it in GitHub Desktop.
西瓜视频百万英雄有奖竞答一类直播节目的ocr工具。实现的功能,通过adb获取截图,然后ocr出文字,并通过浏览器打开搜索结果。
import pytesseract
import time
from PIL import Image
import os
import webbrowser
path = "/home/find/d/filerecv/xigua.png"
import subprocess
def get_screen_shot(path):
# 这里获取截图,目前的方法太慢了
# p = subprocess.Popen('adb shell screencap -p | sed s/\\r$// > ' + path, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
p = subprocess.Popen('adb shell /system/bin/screencap -p /sdcard/screenshot.png ', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
# 需要等两秒,否则数据出错
time.sleep(2)
p = subprocess.Popen('adb pull /sdcard/screenshot.png ' + path, shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
print(line)
retval = p.wait()
def crop_img(path):
# open image
image = Image.open(path)
# 图片的宽度和高度
img_size = image.size
print("图片宽度和高度分别是{}".format(img_size))
height = img_size[1]
width = img_size[0]
height_margin_top = height * 0.1
height_margin_bottom = height * 0.7
width_margin = width * 0.1
width_margin = width * 0.1
new_image = image.crop((0, height_margin_top, width, height_margin_bottom))
new_image.save("a.png")
return new_image
def ocr(img):
# @todo 这个api识别太慢了
code = pytesseract.image_to_string(img, lang='chi_sim')
print(code)
# text = code.split("\n")[0]
text = code.replace("\n", " ")
return text
def work():
get_screen_shot(path)
img = crop_img(path)
# 目前只是简单的打开浏览器百度结果
webbrowser.open('https://www.baidu.com/s?wd=%s' % ocr(img))
work()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment