Skip to content

PyController

SHEN YIBO edited this page Jun 9, 2023 · 11 revisions

你可以借用selenium通过js来控制网页,来达到自动批量、尽可能多样化地获取数据集

这里给出一个例子(即仓库下/Tool/pycontroller/main.py):

import os
import random
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import time

from selenium.webdriver.common.by import By

download_path = os.path.join(os.getcwd(), "download")  # 下载路径
if not os.path.exists(download_path):
    os.mkdir(download_path)
background_path = os.path.join(os.getcwd(), "background")  # 背景图路径
if not os.path.exists(background_path):
    os.mkdir(background_path)

url = 'https://spphire.github.io/RM-labeling-tool/'

bk_paths = os.listdir(background_path)
new_bk_paths = []
for p in bk_paths:
    if p.endswith('.png') or p.endswith('.jpg') or p.endswith('.jpeg'):
        new_bk_paths.append(p)
bk_paths = new_bk_paths

s = Service('chromedriver.exe')
options = webdriver.ChromeOptions()
prefs = {'profile.default_content_settings.popups': 0,
         'download.default_directory': download_path,
         'profile.default_content_setting_values.automatic_downloads': 1}
options.add_experimental_option('prefs', prefs)

# options.add_argument('--headless')   # 隐藏浏览器

browser = webdriver.Chrome(service=s, options=options)
browser.get(url)
browser.implicitly_wait(15)

while browser.execute_script("return myGameInstance==null"):
    time.sleep(1)

# input
e = browser.find_element(By.ID, 'Temp')
input('ready?')


def run(i: int):
    if (i <= 0):
        i = 0
    timeall = 0
    while (True):
        for _ in range(i):
            browser.execute_script("myGameInstance.SendMessage('GameController','CaptureContinue',0)")
            timeall += 1
            print(timeall)

        browser.execute_script("myGameInstance.SendMessage('GameController','SetVisibleMap',0)")
        e.send_keys(os.path.join(background_path, random.choice(bk_paths)))
        jscm = "myGameInstance.SendMessage('ImgTemp', 'FileSelected', URL.createObjectURL(document.getElementById('Temp').files[0]));"
        browser.execute_script(jscm)


run(10)

python tips

在字符串中夹杂变量

a=1
b=2
c=3
string=f'a={a},b={b},c={c}'

以下是你可能需要知道的函数

用来在run函数里修改你想要的流程

browser.execute_script("myGameInstance.SendMessage('GameController', 'CaptureContinue',0)")

随机角度并拍照一次

建议执行这个指令之前,用sleep暂停一小会主程序,等待unity设置完你自定义的设置(如颜色、背景...)

browser.execute_script("myGameInstance.SendMessage('GameController', 'SetColor', 'r_50_50_50_1')")

设置颜色,参数为字符串'r_50_50_50_1',其中包含四个部分(以下划线分割)

第一个r或者b,指定执行目标红蓝方;

二三四对应rgb,范围0~255;

最后一个是光强,默认为5;

browser.execute_script("myGameInstance.SendMessage('GameController', 'SetVisibleMap', 0)")

使除能量机关面板外的不可见,其中修改0为1即为使其可见。这里可以用随机处理

e.send_keys(os.path.join(background_path, random.choice(bk_paths)))
jscm = "myGameInstance.SendMessage('ImgTemp', 'FileSelected', URL.createObjectURL(document.getElementById('Temp').files[0]));"
browser.execute_script(jscm)

第一句send_keys内加入你本地背景图片地址,最终上传到标注工具中

Clone this wiki locally