python打包成可執行文件、只要會 Python 就能寫安卓 App,無需安卓開發基礎,無需編譯
手機上也有交互式 Python 解釋器,直接調試 Python 代碼
可以使用各種 Python 庫,包括 numpy/opencv 等機器學習包
python3.8下載。可以與安卓接口交互,使用手機硬件,比如攝像頭
# 在電腦上連接手機,注意這里ip需要替換成AirPort顯示的ipssh -p 8000 admin@192.168.31.101#?輸入密碼,這里密碼是固定為:meteorixmeteorix
然后你就可以在手機上盡情使用 Python 了。3、攝像頭的 App
在?kivy 的官方文檔中,我們可以找到這樣一個攝像頭的 example
代碼非常簡單,Builder.load_string 函數加載了一段配置,這是 kivy 提供的 UI 定義語言 kivy language。點擊 UI 上創建的 Capture 按鈕,回調 CameraClick.capture() 函數,用 Python 實現函數功能。from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
import time
Builder.load_string('''
:
orientation: 'vertical'
Camera:
id: camera
resolution: (640, 480)
play: False
ToggleButton:
text: 'Play'
on_press: camera.play = not camera.play
size_hint_y: None
height: '48dp'
Button:
text: 'Capture'
size_hint_y: None
height: '48dp'
on_press: root.capture()
''')
class CameraClick(BoxLayout):
def capture(self):
'''
Function to capture the images and give them the names
according to their captured time and date.
'''
camera = self.ids['camera']
timestr = time.strftime("%Y%m%d_%H%M%S")
camera.export_to_png("IMG_{}.png".format(timestr))
print("Captured")
class TestCamera(App):
def build(self):
return CameraClick()
TestCamera().run()
怎么把python打包成一個程序,將這段代碼保存為 kvmain.py 文件,我們可以直接在電腦上運行,如果你的電腦有攝像頭,就可以看到攝像頭 App 的效果。
4、推送代碼到安卓手機
這一步需要做的就是,把這個攝像頭 App 推送到安卓手機上,然后啟動 AirPort 應用,將 kvmain.py 推送到手機 /sdcard/kv/kvmain.py 路徑,然后啟動 AirPort 應用,就會加載這個路徑下的 Python 代碼。adb shell mkdir -p /sdcard/kvadb push kvmain.py /sdcard/kv/kvmain.py
重新啟動手機上的 AirPort 應用,即可看到我們的攝像頭 App 運行在手機上了。5、增加人臉識別功能這一步,我們主要用到了 opencv 的人臉識別接口。import cv2
detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
img = cv2.imread('faces.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = detector.detectMultiScale(gray, 1.3, 5)
print(faces)
最后修改 App 代碼,讀取攝像頭的圖片,調用 opencv 人臉識別接口,將識別出來的人臉坐標,畫到手機屏幕的對應位置上。bbox = BoundingBox(name=face_name, size_hint=(None, None))
...
for loc in faces:
# calculate position of the face
x, y, w, h = loc
t = int(anchor_t - y*sh)
b = int(anchor_t - (y+h)*sh)
r = int(anchor_l + x*sw)
l = int(anchor_l + (x+w)*sw)
# update bounding box
bbox.pos = (int(l), int(b))
bbox.size = (int(r-l), int(t-b))
...
當然,我們還需要針對安卓手機進行一些調試,我們再次推送代碼到手機上。adb push src/* /sdcard/kv/
重啟應用就可以看到上文展示的 GIF 效果了。我已經將全部源碼,包含文中使用的可執行文件一起上傳到后臺,關注公眾號后回復「?人臉識別?」即可獲得下載鏈接,另外原文的 APK 回復「?airport?」獲取下載鏈接。
python3哪個版本好用、
THANDKS
- End -
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态