步驟1:安裝Anaconda和需要的軟件包
Anaconda本質上是一個包裝精美的Python IDE,隨附了大量有用的軟件包,如NumPy,Pandas,IPython筆記本等似乎在科學界的各個地方都值得推薦。查看Anaconda以安裝它。
所需的軟件包:
PyAutoGUI
OpenCv
安裝上述軟件包:
OpenCV:
點擊此鏈接逐步安裝for opencv
PyAutoGUI:
PyAutoGUI是一個Python模塊,用于以編程方式控制鼠標和鍵盤。
PyAutoGUI可以從 pip 工具中安裝
打開你的anaconda命令提示并粘貼它:
pip install PyAutoGUI
現在我們準備好了代碼。..。..
第2步:技術概述
它本質上是一個程序,它應用圖像處理,檢索必要的數據,并根據預定義的概念將其實現到計算機的鼠標接口。
代碼是用Python編寫的。它使用跨平臺圖像處理模塊OpenCV,并使用Python特定庫PyAutoGUI實現鼠標操作。
處理網絡攝像頭的視頻捕獲,僅提取三個彩色指尖。他們的中心是用矩量法計算的,根據它們的相對位置決定要執行什么動作。
第3步:視頻入門
目標一:
cv2.VideoCapture()
從中捕獲視頻相機
通常,我們必須使用相機捕捉直播。 OpenCV為此提供了一個非常簡單的接口。讓我們從相機中捕捉視頻(我正在使用筆記本電腦的內置網絡攝像頭),將其轉換為灰度視頻并顯示它。入門只是一項簡單的任務。要捕獲視頻,您需要創建一個VideoCapture對象。它的參數可以是設備索引或視頻文件的名稱。設備索引只是指定哪個攝像頭的數量。通常會連接一臺攝像機(如我的情況)。所以我只傳遞0(或-1)。您可以通過傳遞1來選擇第二個攝像頭,依此類推。之后,您可以逐幀捕獲。但最后,不要忘記發布捕獲。
我們要做的第一件事就是將捕獲的視頻轉換為HSV格式。
代碼:
# All packages needed for the program are imported ahead
import cv2
cap = cv2.VideoCapture(0)
while(1):
# Capture frame-by-frame
_, frameinv = cap.read()
# flip horizontaly to get mirror image in camera
frame = cv2.flip( frameinv, 1)
# Our operations on the frame come here
hsv = cv2.cvtColor( frame, cv2.COLOR_BGR2HSV)
# Display the resulting frame
cv2.imshow(‘Frame’, hsv)
k = cv2.waitKey(10) & 0xFF
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
第4步:顏色范圍
目標二:
calibrateColor()
校準顏色范圍
現在,用戶可以分別校準他的三個手指的顏色范圍。這可以通過在程序開頭三次調用 calibrateColor()函數來完成。
用戶也可以選擇使用默認設置。
代碼:
import cv2
import numpy as np
def nothing(x):
pass
# Create a black image, a window
kernel = np.zeros((300,512,3), np.uint8)
name = ‘Calibrate’
cv2.namedWindow(name)
# create trackbars for color change
cv2.createTrackbar(‘Hue’, name, 0, 255, nothing)
cv2.createTrackbar(‘Sat’, name, 0, 255, nothing)
cv2.createTrackbar(‘Val’, name, 0, 255, nothing)
# create switch for ON/OFF functionality
switch = ‘0 : OFF 1 : ON’
cv2.createTrackbar(switch, name,0,1,nothing)
while(1):
cv2.imshow(name,kernel)
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
# get current positions of four trackbars
hue = cv2.getTrackbarPos(‘Hue’, name)
sat = cv2.getTrackbarPos(‘Sat’, name)
val = cv2.getTrackbarPos(‘Val’, name)
s = cv2.getTrackbarPos(switch,name)
if s == 0:
kernel[:] = 0
else:
kernel[:] = [hue,sat,val]
cv2.destroyAllWindows()
第5步:刪除噪音&在視頻源中定義函數
取決于校準,只使用 cv2.inRange()功能逐一從視頻中提取三個指尖。為了消除視頻輸入中的噪聲,我們應用兩步態射,即侵蝕和擴張。 然后發送程序中稱為掩碼的噪聲濾波圖像以定位中心。
# cv2.inRange function is used to filter out a particular color from the frame
# The result then undergoes morphosis i.e. erosion and dilation
# Resultant frame is returned as mask
def makeMask(hsv_frame, color_Range):
mask = cv2.inRange( hsv_frame, color_Range[0], color_Range[1])
# Morphosis next 。..
eroded = cv2.erode( mask, kernel, iterations=1)
dilated = cv2.dilate( eroded, kernel, iterations=1)
return dilated
三個中心的位置包括:
在與該顏色范圍相關的遮罩中查找輪廓。
使用區域過濾器丟棄不相關區域的輪廓。
在剩余的輪廓中找到最大的輪廓,并應用力矩的方法找到它的中心。
然后是定義光標在屏幕上的位置的步驟。黃色的拇指負責光標的位置。為此目的使用了以下技術:
?通常我們使用的網絡攝像頭以640x480像素的分辨率捕獲視頻。假設此幀線性映射到1920x1080像素顯示屏幕。如果我們有一個慣用右手的用戶,他會發現與右邊緣相比,訪問屏幕的左邊緣會感覺不舒服。訪問屏幕的底部也會在手腕處產生壓力。
我們意識到,不是將整個視頻幀映射到屏幕,我們寧愿考慮更偏向右側的矩形子部分(考慮右手用戶)和幀的上部以便改進安慰。測量480x270像素的子部分然后以比例因子4線性映射到屏幕。
# Contours on the mask are detected.。 Only those lying in the previously set area
# range are filtered out and the centroid of the largest of these is drawn and returned
def drawCentroid(vid, color_area, mask, showCentroid):
contour, _ = cv2.findContours( mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
l=len(contour)
area = np.zeros(l)
# filtering contours on the basis of area rane specified globally
for i in range(l):
if cv2.contourArea(contour[i])》color_area[0] and cv2.contourArea(contour[i])
# bringing contours with largest valid area to the top
for i in range(l):
for j in range(1):
if area[i] == a[j]:
swap( contour, i, j)
if l 》 0 :
# finding centroid using method of ‘moments’
M = cv2.moments(contour[0])
if M[‘m00’] != 0:
cx = int(M[‘m10’]/M[‘m00’])
cy = int(M[‘m01’]/M[‘m00’])
center = (cx,cy)
if showCentroid:
cv2.circle( vid, center, 5, (0,0,255), -1)
return center
else:
# return error handling values
return (-1,-1)
?由于網絡攝像頭捕獲的噪聲和手中的振動,中心保持不變圍繞一個平均位置振動。在按比例放大時,這些振動會對光標位置的準確性產生很多問題。為了減少光標中的抖動,我們使用光標的差分位置分配。我們將新中心與光標的先前位置進行比較。如果差異小于5個像素,則通常是由于噪聲。因此,新光標位置更傾向于前一個。但是,先前位置和新中心的較大差異被視為自愿移動,新光標位置設置為接近新中心。有關詳細信息,請通過代碼中的setCursorPosition()函數。
‘’‘
This function takes as input the center of yellow region (yc) and
the previous cursor position (pyp)。 The new cursor position is calculated
in such a way that the mean deviation for desired steady state is reduced.
’‘’
def setCursorPos( yc, pyp):
yp = np.zeros(2)
if abs(yc[0]-pyp[0])《5 and abs(yc[1]-pyp[1])《5:
yp[0] = yc[0] + .7*(pyp[0]-yc[0])
yp[1] = yc[1] + .7*(pyp[1]-yc[1])
else:
yp[0] = yc[0] + .1*(pyp[0]-yc[0])
yp[1] = yc[1] + .1*(pyp[1]-yc[1])
return yp
現在發送三個中心,根據
的相對位置決定需要執行哪些操作。這是在代碼中的chooseAction()函數中完成的。根據其輸出,performAction()函數使用PyAutoGUI庫執行以下任一操作:
自由光標移動
左鍵單擊
右鍵單擊
拖動/選擇
向上滾動
向下滾動
# Depending upon the relative positions of the three centroids, this function chooses whether
# the user desires free movement of cursor, left click, right click or dragging
def chooseAction(yp, rc, bc):
out = np.array([‘move’, ‘false’])
if rc[0]!=-1 and bc[0]!=-1:
if distance(yp,rc)《50 and distance(yp,bc)《50 and distance(rc,bc)《50 :
out[0] = ‘drag’
out[1] = ‘true’
return out
elif distance(rc,bc)《40:
out[0] = ‘right’
return out
elif distance(yp,rc)《40:
out[0] = ‘left’
return out
elif distance(yp,rc)》40 and rc[1]-bc[1]》120:
out[0] = ‘down’
return out
elif bc[1]-rc[1]》110:
out[0] = ‘up’
return out
else:
return out
else:
out[0] = -1
return out def performAction( yp, rc, bc, action, drag, perform):
if perform:
cursor[0] = 4*(yp[0]-110)
cursor[1] = 4*(yp[1]-120)
if action == ‘move’:
if yp[0]》110 and yp[0]《590 and yp[1]》120 and yp[1]《390:
pyautogui.moveTo(cursor[0],cursor[1])
elif yp[0]《110 and yp[1]》120 and yp[1]《390:
pyautogui.moveTo( 8 , cursor[1])
elif yp[0]》590 and yp[1]》120 and yp[1]《390:
pyautogui.moveTo(1912, cursor[1])
elif yp[0]》110 and yp[0]《590 and yp[1]《120:
pyautogui.moveTo(cursor[0] , 8)
elif yp[0]》110 and yp[0]《590 and yp[1]》390:
pyautogui.moveTo(cursor[0] , 1072)
elif yp[0]《110 and yp[1]《120:
pyautogui.moveTo(8, 8)
elif yp[0]《110 and yp[1]》390:
pyautogui.moveTo(8, 1072)
elif yp[0]》590 and yp[1]》390:
pyautogui.moveTo(1912, 1072)
else:
pyautogui.moveTo(1912, 8)
elif action == ‘left’:
pyautogui.click(button = ‘left’)
elif action == ‘right’:
pyautogui.click(button = ‘right’)
time.sleep(0.3)
elif action == ‘up’:
pyautogui.scroll(5)
# time.sleep(0.3)
elif action == ‘down’:
pyautogui.scroll(-5)
# time.sleep(0.3)
elif action == ‘drag’ and drag == ‘true’:
global y_pos
drag = ‘false’
pyautogui.mouseDown()
while(1):
k = cv2.waitKey(10) & 0xFF
changeStatus(k)
_, frameinv = cap.read()
# flip horizontaly to get mirror image in camera
frame = cv2.flip( frameinv, 1)
hsv = cv2.cvtColor( frame, cv2.COLOR_BGR2HSV)
b_mask = makeMask( hsv, blue_range)
r_mask = makeMask( hsv, red_range)
y_mask = makeMask( hsv, yellow_range)
py_pos = y_pos
b_cen = drawCentroid( frame, b_area, b_mask, showCentroid)
r_cen = drawCentroid( frame, r_area, r_mask, showCentroid)
y_cen = drawCentroid( frame, y_area, y_mask, showCentroid)
if py_pos[0]!=-1 and y_cen[0]!=-1:
y_pos = setCursorPos(y_cen, py_pos)
performAction(y_pos, r_cen, b_cen, ‘move’, drag, perform)
cv2.imshow(‘Frame’, frame)
if distance(y_pos,r_cen)》60 or distance(y_pos,b_cen)》60 or distance(r_cen,b_cen)》60:
break
pyautogui.mouseUp()
-
鼠標
+關注
關注
6文章
591瀏覽量
39909 -
手勢控制
+關注
關注
4文章
44瀏覽量
21839
發布評論請先 登錄
相關推薦
評論