範例下載
>
...
Privacy
...
Python
thonny下載
滑鼠控制指令產生器
滑鼠查看工具
教學影片
0
0
0
0
0
0
0
0
0
0
0
0
0
0
A
L
time
random
randint
#隨機取0~9之間的整數
=
r
randint
0
9
mic
record
filename="1.wav",dur=25,TH=0.02,SilenceNum=50
foo
n,m=1
node
object
__init__
self
a=1
.
self
a
a
v
q
e
==
line
break
random
#隨機生成0~3的整數指定給i
i
random.randint
0
3
#如果i等於0
==
i
0
end="\n"
i等於0
#否則如果i等於1
==
i
1
end="\n"
i等於1
#否則(以上條件皆沒發生)
end="\n"
其它狀況
# 重複無限次
True
# 重複指定次數
i
5
# i=0,1,2,3,4 共重複5次
i
0
5
# 繼續迴圈,跳過下方敘述
# 跳出迴圈
# 範例:偵測到p鍵按後,跳出重窮迴圈
import keyboard
True
==
keyboard.is_pressed
'p'
True
v
0
check
True
temp
123
1
1
9
45
'''
Note:字串和數值兩種型態可以互相轉換
str(123) ==>把數值123轉換為字串"123"
int("123") ==>把字串"123"轉換為數值123
'''
# split範例
# 把字串 "1 2 3 4" 按預設的空白字元分割成陣列 ['1','2','3','4' ]
A
1 2 3 4
end="\n"
A
# 把字串 "1234" 轉換成整數 1234 回存變數v
v
int
1234
# 使用者輸入以字串的型式存入A
A
輸入後按下enter
# 字串A按預設的空白字元分割成陣列後回存
A
1 2 3 4
A
# map 範例
# 把串列A中的所有元素皆套入int( )函式,變成一個int串列
A
map
int
A
list
# 使用者輸入以空格分割整數的型式存入串列容器
A
list
map
int
1 2 3 4
# 使用者輸入以空格分開以整數的型式存入多個變數
map
int
1 2 3 4
#一維串列生成式
int(x)
for
x
# 二維串列生成
a_list
i
5
temp
int(x)
for
x
a_list
temp
'''
傳入「函式」的「參數」要用逗號隔開
每個「函式」都會有名稱,ex:下面範例的函式名稱叫做Sum
'''
# 自訂義函式 Sum,傳入 a, b 回傳 a+b
Sum
a
b
# 回傳
ADD
1
a
1
b
# 呼叫 Sum 把 2 和 3 相加得到 5 並印出來
end="\n"
Sum
2
3
temp
min
3
1
2
print
123
whereisthemouse
.
whereisthemouse
start
whereisthemouse滑鼠定位工具下載
https://nlacsoft.net/whereisthemouse
#使用pyautogui前,一定要先import它
time
#等待0.5秒程式再往下
time.sleep
0.5
#滑鼠0.3秒移動到(10,10)
10
10
0.3
#滑鼠點擊(10,10)
10
10
#按下滑鼠左鍵
#放開滑鼠左鍵
#鍵盤按下「上」並放開
up
#鍵盤按往「shift」
#鍵盤放開「shift」
keyUp('shift')
#直接由鍵盤輸入字串"123456789"
pyautogui
.
write
123456789
#取得鼠標位置
=
x
y
#螢幕截圖存入img
=
img
#取得圖像 img 於 (20,20) 處像素RGB值存入pix
=
pix
img
20
20
#取得(10,10)處像素RGB值放進 pix 中
pix
10
10
#取得螢幕擷圖,存檔至 1.png, 擷圖區域左上座標(0,0)長300寬200
=
img
"1.png",region=(0,0,300,200)
#定位 1.png 於螢幕上之位置
=
x
y
1.png
#定位 1.png 於螢幕上之位置,設定圖片比對有5%的容錯(confidence=0.95)
=
X
Y
1.png
"1.png"
confidence
0.95
#函式:在 img 中找到所有和目標顏色(targetColor)相近的YX座標, 並回傳串列
findColorYXs
img
targetColor
255
0
0
TH=20
A
img
dtype
int
B
targetColor
dtype
int
dist
np.linalg.norm
-
A
B
axis
-1
np.argwhere
<
dist
TH
#函式呼叫:找到螢幕上和目標顏色targetColor相近的座標 x,y
=
YXs
findColorYXs
targetColor
255
0
0
TH=20
>
len
YXs
0
=
y
x
YXs
0
#pyautogui無法控制或反應速度太慢的狀況可改試pydirectinput
pydirectinput
#外掛滑鼠點擊指定座標
.
pydirectinput
click
200
300
#外掛按鍵控制
.
pydirectinput
press
x
# 使用 需事先引入下列package
time
autobf
bf
autobf
Yc
Xc
# 滑鼠點擊指定座標,重複repeat次,每次間隔delay秒
bf
.
click
Xc
Yc
repeat
1
delay
0
# 滑鼠滾輪 滾動量:-500 , 重複repeat次
bf
.
zoom
scroll
-500
repeat
10
# 拉到最頂端視角
bf
.
zoom2max
# 切換武器:可傳入字串 '1','2','3','4'
bf
.
switchOn
1
# 按往Q鍵滑行指定次數,上:''下左右
bf
.
slide
w
1
# 按下指定按鍵,重複repeat次,每次間隔delay秒
bf
.
press
x
repeat
10
delay
0
# 重置遊戲
bf
.
reset
# 找出螢幕上所有顏色類似 color 的像素所在位置,看是否有接近 (x,y) ,若有則回傳真
# color_tolorance:顏色容錯範圍
# XY_tolorance:座標容錯範圍
check
.
bf
checkColorByXY
x
233
y
519
color
255
255
255
color_tolorance
25
XY_tolorance
8
# 按下滑鼠指定鍵(button)並在指定座標(x,y)上做位移,可藉此改變視角或安置遊戲游標
# dx:x方向位移
# dy:y方向位移
bf
.
row
Xc
Yc
dx
0
dy
0
button
right
# 接近指定顏色,offsetX:X方向位移 ; offsetY:Y方向位移
.
bf
close2Color
241
234
41
offsetX
0
offsetY
45
# 取得任務(預設開啟第一個任務)
bf
.
getMission
mission
1
# 在見聞色下瞄準紅色的敵人 LOW:敵人距離的下限(太近的不瞄準)
bf
.
aimEnemy
LOW
100
# 偵測任務是否完成
=
missionOK
bf
.
isComplete
targetImgPath='goal.png'
keyboard.is_pressed
'p'
keyboard
True
keyboard
is_pressed
e
end="\n"
按下了 e 鍵
pass
keyboard
#監聽 hotkey : 'p'鍵按下時觸發下列函式
def on_hotkey_triggered():
pass
keyboard.add_hotkey
'p'
on_hotkey_triggered
keyboard.wait
r
#colab範例連結如下(Note:20240708發現pytube有問題暫時切換至pytubefix)
#https://colab.research.google.com/drive/17t9mJhrGt54heYSscWvDxo3cEXmT54gG?usp=sharing
#youtube mp3下載
os
=
cwd
os
getcwd
pytubefix
YouTube
=
yt
YouTube
此處貼上Youtube網址
end="\n"
下載中…
yt
streams
filter().get_audio_only()
download
filename
1.mp3
end="\n"
已下載至下列位置
end="\n"
+
cwd
+
/
1.mp3
#youtube mp4下載
os
=
cwd
os
getcwd
pytubefix
YouTube
=
yt
YouTube
此處貼上Youtube網址
end="\n"
下載中…
yt
streams.filter()
get_highest_resolution()
download
filename
1.mp4
end="\n"
已下載至下列位置
end="\n"
+
cwd
+
/
1.mp4
pyMicVoiceDetection
mic
#偵測音量,有聲段自動編號儲存,5秒後結束錄音,能量門檻值0.08
#能量門檻值0.08
#連續10個音框之能量小於門檻值時才做音訊切割
mic
recordSerialAndPlot
dur=5
,
TH=0.08
,SilenceNum=
10
#連續語音辨識
pyMicVoiceDetection
mic
speech_recognition
sr
while True:
#偵測音量,有聲段存至 1.wav
mic
record
filename="1.wav"
,
dur=25
,
TH=0.02
,SilenceNum=
50
sr
Recognizer
r
#由1.wav 讀出待辨識 audio
with
sr.WavFile("1.wav") as
source
=
audio
.
r
record
source
#取得google語音有中文辨識結果
=
result
.
r
recognize_google
audio
,language=
'zh-TW'
end="\n"
result
e
pass
#使用gtts產生語音
gtts
gTTS
=
tts
gTTS
好的請稍後
lang='zh-TW'
.
tts
save
temp.mp3
time
temp.mp3
#播放函式,unblocked
play()
.
time
sleep
5
#釋放mixer物件,關閉已開啟之音檔
pygame.mixer.quit
keyboard
1.mp3
#監聽 hotkey : 'p'鍵按下時觸發下列函式
play()
def on_hotkey_triggered():
#如果音樂正在播放就暫停,否則繼續
pause()
unpause()
keyboard.add_hotkey
'p'
on_hotkey_triggered
keyboard.wait
#載入 selenium chromedriver 各種工具包
selenium
webdriver
#載入必要項目
selenium.webdriver.support
expected_conditions as EC
selenium.webdriver.support.ui
WebDriverWait
selenium.webdriver.common.by
By
#取得chromedriver自動開啟瀏器
driver
webdriver.Chrome
driver
get
https://www.google.com
#getElementByXPATH函式定義:由XPATH在瀏覽器driver裡面找到對應的元素並回傳
getElementByXPATH
driver
xpath
func
EC.visibility_of_element_located
By.XPATH
xpath
element
WebDriverWait
driver
5
until
func
element
#指定XPATH內容
xpath
//*[@id="APjFqb"]
#由XPATH在瀏覽器driver裡面找到對應的元素並回傳
element
getElementByXPATH
driver
xpath
#元素截圖
element
screenshot
1.png'
#瀏覽器螢幕截圖
driver
get_screenshot_as_file
screenshot.png'
#輸入123456
element
send_keys
123456
#滑鼠點一下
element
click
'''
selenium 開啟 google 首頁
使用XPATH找到搜尋輸入框後
使用send_keys輸入pclearn0915
網頁元素XPATH的取得方法可參考下列網址
https://ithelp.ithome.com.tw/articles/10191811?sc=rss.iron
'''
#載入 selenium chromedriver 各種工具包
selenium
webdriver
#載入必要項目
selenium.webdriver.support
expected_conditions as EC
selenium.webdriver.support.ui
WebDriverWait
selenium.webdriver.common.by
By
#取得chromedriver自動開啟瀏器
driver
webdriver.Chrome
driver
get
https://www.google.com
xpath
//*[@id="APjFqb"]
func
EC.visibility_of_element_located
By.XPATH
xpath
element
WebDriverWait
driver
5
until
func
#輸入123456
element
send_keys
pclearn0915
#透過OCR網站做文字辨識
pyperclip
time
os
#載入 selenium chromedriver 各種工具包
selenium
webdriver
selenium.webdriver.chrome.service
as
Service
ChromeService
webdriver_manager.chrome
ChromeDriverManager
#載入必要項目
selenium.webdriver.support.ui
WebDriverWait
selenium.webdriver.common.by
By
OCR
imFullPath
':' not in
imFullPath
imFullPath
+
os.getcwd()
+
/
imFullPath
driver
webdriver.Chrome
service
ChromeService
ChromeDriverManager().install()
driver
get
https://www.gaitubao.com/hk/ocr
element
driver.find_element
By.XPATH
//*[@id="file-upload"]
element
send_keys
imFullPath
.
time
sleep
3
element
driver.find_element
By.XPATH
//*[@id="btn-copy"]
element
click
driver
close
OCR
code.png
temp
pyperclip.paste()
#去除不必要字元如.*,空白
temp
"".join(c for c in
temp
if c.isalnum())
end="\n"
temp
requests
webbrowser
#search_youtube函式:傳入關鍵字,回傳youtube搜尋到的第一個網址
def
search_youtube
keyword
=
params
"search_query":
keyword
=
res
.
requests
get
"https://www.youtube.com/results"
,
params
=
i
.
res
text.find
/watch?v=
0
=
j
.
res
text.find
\u0026
i
=
vid
.
res
text
0
i
0
j
+
"https://www.youtube.com"
vid
webbrowser
open
search_youtube
五月天的突然好想你
webbrowser
webbrowser
open
https://github.com/ai-ky/blocks
PIL
Image
#載入圖片
=
img
Image
open
screenshot.png
#rect=left,top,right,bottom
rect
10
10
200
200
#圖片裁切(Crop)
=
img
img
crop
rect
#裁切後圖片儲存
.
img
save
crop.png
#載入teachablemachine imgage模型並做測試
0
cv2.CAP_DSHOW
model
keras_model.h5
labels.txt
class_names
#webcam影像貼圖迴圈
while True:
ret
img
=
img
1
img
#調整圖片大小並做正規化
=
fv
cv2.INTER_AREA
img
224
224
=
fv
-
/
fv
127
1
#*特徵向量要多一個維度,因為predict的功能是同時預測多個特徵向量
=
fv
fv
1
224
224
3
#取得辨識結果class_name
prediction
model
fv
verbose
0
class_name
class_names
0
prediction
#顯示文字
cv2.FONT_HERSHEY_SIMPLEX
1
(0,0,255)
img
class_name
30
30
==
50
q
break
img
0
cv2.CAP_DSHOW
model
keras_model.h5
labels.txt
class_names
#webcam影像貼圖迴圈
while True:
ret
img
=
img
1
img
#調整圖片大小並做正規化
=
fv
cv2.INTER_AREA
img
224
224
=
fv
-
/
fv
127
1
#*特徵向量要多一個維度,因為predict的功能是同時預測多個特徵向量
=
fv
fv
1
224
224
3
#取得辨識結果class_name
prediction
model
fv
verbose
0
class_name
class_names
0
prediction
#顯示文字
cv2.FONT_HERSHEY_SIMPLEX
1
(0,0,255)
img
class_name
30
30
==
50
q
break
img
10
10
200
#畫矩形框
(0,0,255)
img
0
0
50
50
2
img
img
img
img
img
255
#由(0,0) 到 (99,99)畫一條紅線寬度為3
cv2
line
img
0
0
99
99
255
0
0
3
#顯示文字
cv2.FONT_HERSHEY_SIMPLEX
1
(0,0,255)
img
0
0
img
50
50
img
img
50
50
=
img
img
numpy練習與webcam影像處理
參考下列colab連結
https://colab.research.google.com/drive/1WUlLJkMW493Usn9bS7OgmOZt0YWVbSYq?usp=sharing
TeachableMachine示範
參考下列colab連結
https://colab.research.google.com/drive/1Gb5JStf-UQxUaNd2wJPzQcefUSbZf8yY?usp=sharing
pyFaceTrace Colab 範例
搭配 KNN 做性別辨識
https://colab.research.google.com/drive/1VKhaYcqjcjcVpidEKFwGFZnPH90ZnjOs?usp=sharing
#Step1
#下載各種照片樣本至TRAIN資料夾
pyFaceTrace
ft
ft
downloadImageSamples
#Step2
#開啟webcam視窗將辨識到的人臉ID標示出來
PIL
ImageFont
pyFaceTrace
ft
#至train資料夾載入樣本,欲辨識之目標圖片可放入 train資料夾
ft
loadDB
FONT
ImageFont
truetype
kaiu.ttf
50
index
0
0
cv2.CAP_DSHOW
#webcam影像貼圖迴圈
while True:
ret
img
=
img
1
img
rects
ft
detector
img
1
rect
rects
fv
ft
getFeatureVector
img
rect
tag
dist
ft
predictFromDB
fv
#畫人臉矩形框
(0,0,255)
img
0
rect.left()
0
rect.top()
50
rect.right()
50
rect.bottom()
3
#顯示文字:人臉ID
img
ft
addText2Img_cv2
img
tag
FONT
position
0
rect.left()
0
MINUS
1
rect.top()
1
FONT.size
==
50
q
break
img
0
cv2.CAP_DSHOW
True
ret
img
=
img
1
img
=
img
cv2.COLOR_BGR2RGB
img
img
False
result
img
img
True
=
img
cv2.COLOR_RGB2BGR
img
multi_hand_landmarks
result
hand_landmarks
multi_hand_landmarks
result
abc
hand_landmarks
y
8
8
取 index finger y座標
img
hand_landmarks
==
50
q
break
mediapipe hands demo
img
img
img
result
img
result
hand_landmarks
result
0
img
hand_landmarks
0
cv2.CAP_DSHOW
True
ret
img
ret
=
img
1
img
img
False
poseResult
img
img
True
poseLandmarks
poseResult
poseLandmarks
poseLandmarks
img
abc
poseLandmarks
y
16
EQ
50
q
break
img
img
0
img
tkinter
*
mouseDown
event
isClick
=
isClick
True
mouseUp
event
=
isClick
False
mouseMove
event
isClick
root.geometry
+{event.x_root - 20}+{event.y_root - 20}
=
root
Tk
root
withdraw
#窗體置頂
root
wm_attributes
-topmost
1
=
img
PhotoImage
file
欲顯示圖片之檔案路徑
#圖片Label初始設定
=
lab1
Label
root
image
img
bd
0
lab1
place
x
0
y
0
lab1
bind
<Button-1>
mouseDown
lab1
bind
<ButtonRelease-1>
mouseUp
lab1
bind
<B1-Motion>
mouseMove
#文字Label初始設定
=
lab2
Label
root
text
顯示文字
bd
0
bg
#FFFAFA
lab2
place
x
100
y
0
#root初始設定:視窗無標題欄
root
overrideredirect
True
#root初始設定:白色為透明色
root
wm_attributes
-transparentcolor
#FFFFFF
root
update
root
geometry
200x300+100+400
root
configure
bg
#FFFFFF
root
wm_deiconify
root
mainloop
def
thread_job
10
10
1
thread1
thread_job
thread1
thread2
pyautogui.press
Up
thread2
lock
lock
asyncio
async def task_a():
end="\n"
task_a
i
10
end="\n"
i
await
.
asyncio
sleep
1
async def task_b():
end="\n"
task_b
await
.
asyncio
sleep
4
end="\n"
task_b結束
=
event_loop
.
asyncio
get_event_loop
.
asyncio
ensure_future
task_a()
loop
event_loop
.
asyncio
ensure_future
task_b()
loop
event_loop
.
event_loop
run_forever
檔名
encoding
utf-8
=
f
open
檔名
encoding
utf-8
f
close
serialPort
COM3
9600
serialPort
serialPort
serialPort
serialPort
apdu
time
#開啟COM埠
serialPort
COM3
9600
=
i
0
WHILE
True
GT
serialPort
0
#讀取序列埠傳來之資料解碼後並印出
=
line
'utf-8'
serialPort
end="\n"
line
req:
line
#讀取序列埠傳來之資料包含 "req:" 時才回應
serialPort
#回應資料為 "res:" + str(i) + "\n" 編碼後送出
serialPort
'utf-8'
res:{ i }\n
time
sleep
0.1
+=
i
1
1
#開啟COM埠,遂次讀取一行由COM埠傳來的訊息每隔20
serialPort
COM3
9600
=
i
0
WHILE
True
GT
serialPort
0
#每隔20行,顯示一次讀入之訊息以免顯示速度跟不上傳送速度
=
line
serialPort
==
%
i
20
0
end=""
line
=
i
ADD
1
i
1
0.0.0.0
0.0.0.0
adhoc
#httpServer Hello World!!
app
Flask
__name__
#定義瀏覽根目錄 "/" 時觸發的事件
@app.route
/
hello
helloWorld!!
80
0.0.0.0
value
#可先使用瀏覽器做測試 ex: http://192.168.0.1/999
#上述通訊 httpReq 中之value=999
end="\n"
value
res:
value
80
0.0.0.0
X
Y
0
model
0
0
model
dense
model
model
x_train
y_train
80
64
loss
accuracy
model
x_test
y_test
model
model
x_test
y_train
5
x_train
y_train
x_test
L
A
A
A
A
A
0
0
A
0
0
0
A
0
0
0
0
A
img
0
255
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
A
0
L
compressXML
.
compressXML
start
#遊戲把手usb中介伺服器,先確認連線哪個COM
time
#偵測Xp,Yp所在位置的像素內容
Xp
Yp
1448
898
#開啟COM埠
serialPort
COM3
9600
#設定欲偵測的顏色
D_COLOR
255
0
0
=
vMotorPow
0
=
value
1,1
#副程式:根據http客戶端(遊戲把手)傳來的按鈕btn 及 tt馬達轉動發電大小roll決定按鍵輸出
handleKeyboard
btn
roll
=
roll
roll
==
roll
0
keyDown('Down')
keyUp('Down')
#按鈕 PIN設定為INPUT_PULLUP 輸出 0 時代表有按下
==
btn
0
keyDown('e')
keyUp('e')
>
roll
500
keyDown('3')
keyUp('1')
keyUp('2')
keyDown('Up')
>
roll
300
keyDown('2')
keyUp('3')
keyUp('1')
keyDown('Up')
>
roll
200
keyDown('1')
keyUp('3')
keyUp('2')
keyDown('Up')
keyUp('1')
keyUp('2')
keyUp('3')
keyUp('Up')
e
end="\n"
e
vMotorPow
0
#副程式:執行緒工作
def
thread_job
vMotorPow
value
#副程式:定義http伺服器接收訊息後如何回應
True
GT
serialPort
0
#讀取序列埠傳來之資料解碼後並印出
=
value
'utf-8'
serialPort
#回應資料為 vMotorPow轉換為字串後加上換行符號 編碼後送出
serialPort
serialPort
'utf-8'
ADD
1
vMotorPow
1
\n
e
pass
#創造並啟動執行緒,讓http伺服端平行執行
thread1
thread_job
thread1
#偵測Xp,Yp所在的像素內容並輸出振動馬達振動的大小 vMotorPow
time
True
#取得硬體端傳來的按鈕訊息及旋轉發電量 btn,roll
btn
roll
","
value
end="\n"
btn
roll
vMotorPow
#另開執行緒處理鍵盤外掛
thread2
handleKeyboard
btn
roll
thread2
#偵測Xp,Yp所在的像素內容並輸出振動馬達振動的大小 vMotorPow
==
1448
Xp
898
Yp
D_COLOR
vMotorPow
255
vMotorPow
0
time.sleep
0.01
#遊戲把手http中介伺服器,執行後可得url位置>>開ArduinoIDE設定並燒錄
#偵測Xp,Yp所在位置的像素內容
Xp
Yp
1448
898
#設定偵測目標顏色 D_COLOR
D_COLOR
255
0
0
#副程式:根據http客戶端(遊戲把手)傳來的按鈕btn 及 tt馬達轉動發電大小roll決定按鍵輸出
handleKeyboard
btn
roll
=
roll
roll
==
roll
0
keyDown('Down')
keyUp('Down')
#按鈕 PIN設定為INPUT_PULLUP 輸出 0 時代表有按下
==
btn
0
keyDown('e')
keyUp('e')
>
roll
500
keyDown('3')
keyUp('1')
keyUp('2')
keyDown('Up')
>
roll
300
keyDown('2')
keyUp('3')
keyUp('1')
keyDown('Up')
>
roll
200
keyDown('1')
keyUp('3')
keyUp('2')
keyDown('Up')
keyUp('1')
keyUp('2')
keyUp('3')
keyUp('Up')
e
end="\n"
e
vMotorPow
0
V
1,1
#副程式:執行緒工作
def
thread_job
vMotorPow
V
#副程式:定義http伺服器接收訊息後如何回應
value
vMotorPow
V
in
,
value
V
value
0
vMotorPow
#啟動http伺服端
80
0.0.0.0
#創造並啟動執行緒,讓http伺服端平行執行
thread1
thread_job
thread1
#偵測Xp,Yp所在的像素內容並輸出振動馬達振動的大小 vMotorPow
time
True
btn
roll
','
V
thread2
handleKeyboard
btn
roll
thread2
end="\n"
btn
roll
vMotorPow
==
1448
Xp
898
Yp
D_COLOR
vMotorPow
255
vMotorPow
0
time.sleep
0.1
e
end="\n"
e