本文禁止转载,如需转载需征得本人同意。
前言
为什么要将代码模块化呢?
代码模块化之后,我们就可以在项目中直接调用需要的东西,不必再重复进行没有必要重复的操作,将变得非常方便。
文章大部分问题可以在以下几个链接中解决:
https://www.liaoxuefeng.com/wiki/1016959663602400
(廖雪峰Python教程)
(opencv简单入门)
https://google.github.io/mediapipe/solutions/hands.html
(mediapipe参考)
https://www.cnblogs.com/chengd/articles/7287528.html
(Python入门类)
1.上篇代码回顾
先附上上篇教程中的手势识别代码,详情实现可见本人主页文章的教程(一)手势识别基础入门。
import cv2
import mediapipe as mp
import time
cap = cv2.VideoCapture(0)
mpHands = mp.solutions.hands
hands = mpHands.Hands()
mpDraw = mp.solutions.drawing_utils
pTime = 0
cTime = 0
while True:
success, img = cap.read()
imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # 2 = to
results = hands.process(imgRGB)
# print(results.multi_hand_landmarks)//检查手坐标输出
if results.multi_hand_landmarks:
for handLms in results.multi_hand_landmarks:
for id, lm in enumerate(handLms.landmark):
# print(id, lm)
h, w, c = img.shape
cx, cy = int(lm.x * w), int(lm.y * h)
print(id, cx, cy)
# if id == 4:
cv2.circle(img, (cx, cy), 15, (255, 0, 255), cv2.FILLED)
mpDraw.draw_landmarks(img, handLms, mpHands.HAND_CONNECTIONS)
cTime = time.time()
fps = 1 / (cTime - pTime)
pTime = cTime
cv2.putText(img, str(int(fps)), (10, 70), cv2.FONT_HERSHEY_PLAIN, 3,
(255, 255, 255), 2)
cv2.imshow("Image", img)
cv2.waitKey(1)
2.代码模块化
首先新建文件,我们将它命名为"HandTrackingModule"
回车确认后,我们先将原来Min中的代码全部复制到新的py文件中,以便进行下一步改造。
接着,我们在底部加上代码
if __name__ == "__main__":
main()
#当运行“if __name__=='__main__':”语句时,如果当前模块时被直接执行,__name__的值就是__main__,
#条件判断的结果为True,“if __name__=='__main__':”下面的代码块就会被执行
就是这样
接着用def main(),将上面的代码剪切下来
def main():
pTime = 0
cTime = 0
cap