python opencv 手指檢測

  1. pip設置阿里雲源加速

步驟 pip config list 查看當前 pip 的配置

接着修改配置文件 pip config set global.index-url http://mirrors.aliyun.com/pypi/simple/

pip config set install.trusted-host mirrors.aliyun.com

完成之後可以再使用 pip config list 查看是否已經寫入,如果有顯示我們 設置的信息的話,那麼就設置成功了。

2. 安裝opencv和numpy

pip install opencv-contrib-python

pip install numpy

一般來說, pip提供的opencv的包的類型有四種: opencv-python: 只包含opencv庫的主要模塊. 一般不推薦安裝. opencv-contrib-python: 包含主要模塊和contrib模塊, 功能基本完整, 推薦安裝. opencv-python-headless: 和opencv-python一樣, 但是沒有GUI功能, 無外設系統可用. opencv-contrib-python-headless: 和opencv-contrib-python一樣但是沒有GUI功能. 無外設系統可用.

測試opencv是否安裝成功

import cv2

print(cv2.__version__)

 

3. 待檢測圖片

4. 相關代碼

#參考: https://cloud.tencent.com/developer/article/1701793

import cv2 as cv
import numpy as np
import json

from datetime import datetime


#print('Start: ' + time.strftime("%Y-%m-%d %H:%M:%S", start) )
img_path = "data/palm3.jpg"
img = cv.imread(img_path)

start_time = datetime.now()
#cv.imshow('palm image',img)

#皮膚Mask
#img = cv.GaussianBlur(img,(9,9),15)

hsvim = cv.cvtColor(img, cv.COLOR_BGR2HSV)
lower = np.array([0, 48, 130], dtype = "uint8") 
upper = np.array([20, 255, 255], dtype = "uint8") 
skinRegionHSV = cv.inRange(hsvim, lower, upper)
blurred = cv.blur(skinRegionHSV, (2,2))
ret,thresh = cv.threshold(blurred,0,255,cv.THRESH_BINARY)
#cv.imshow("thresh", thresh)

#輪廓線繪製
#contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
contours, hierarchy = cv.findContours(thresh, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)

print("找到輪廓數量:" + str(len(contours)))

maxContour = max(contours, key=lambda x: cv.contourArea(x))
maxIndex = contours.index(maxContour)
if maxIndex == len(contours):
    contours = contours[:maxIndex]  
else:
    contours = contours[:maxIndex] + contours[maxIndex+1:]  
print("去除人臉後輪廓數量:" + str(len(contours)))
contours = max(contours, key=lambda x: cv.contourArea(x))

print("輪廓類型: " + str(type(contours)))
#print(contours)

#繪製輪廓線
cv.drawContours(img, [contours], -1, (255,255,0), 2)
#cv.imshow("contours", img)

#凸包檢測
hull = cv.convexHull(contours)
cv.drawContours(img, [hull], -1, (0, 255, 255), 2)

#輪廓近似
epsilon = 0.02*cv.arcLength(contours,True)
approx = cv.approxPolyDP(contours,epsilon,True)
cv.polylines(img, [approx], True, (0, 0, 255), 2) #繪製
contours = approx
 
#cv.imshow("hull", img)

#凹陷檢測
hull = cv.convexHull(contours, returnPoints=False)
defects = cv.convexityDefects(contours, hull)

if defects is not None:
    cnt = 0
    for i in range(defects.shape[0]): # calculate the angle
        s, e, f, d = defects[i][0]
        start = tuple(contours[s][0])
        end = tuple(contours[e][0])
        far = tuple(contours[f][0])
        a = np.sqrt((end[0] - start[0]) ** 2 + (end[1] - start[1]) ** 2)
        b = np.sqrt((far[0] - start[0]) ** 2 + (far[1] - start[1]) ** 2)
        c = np.sqrt((end[0] - far[0]) ** 2 + (end[1] - far[1]) ** 2)
        angle = np.arccos((b ** 2 + c ** 2 - a ** 2) / (2 * b * c)) # cosine theorem
        if angle <= np.pi / 2: # angle less than 90 degree, treat as fingers
            cnt += 1
            cv.circle(img, far, 4, [0, 0, 255], -1)
    if cnt > 0:
        cnt = cnt+1
cv.putText(img, str(cnt), (0, 50), cv.FONT_HERSHEY_SIMPLEX,1, (255, 0, 0) , 2, cv.LINE_AA)

end_time = datetime.now()

diff_time = (end_time - start_time)  
print("總用時(毫秒): " + str(diff_time.microseconds / 1000))

cv.imshow('final_result',img)



K = cv.waitKey(0)


5. 結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章