溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何使用Python+OpenCV實現(xiàn)拖拽虛擬方塊效果

發(fā)布時間:2023-05-16 11:35:12 來源:億速云 閱讀:82 作者:iii 欄目:編程語言

本篇內(nèi)容主要講解“如何使用Python+OpenCV實現(xiàn)拖拽虛擬方塊效果”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“如何使用Python+OpenCV實現(xiàn)拖拽虛擬方塊效果”吧!

一、核心流程

1、openCV讀取視頻流、在每一幀圖片上畫一個矩形。

2、使用mediapipe獲取手指關(guān)鍵點坐標。

3、根據(jù)手指坐標位置和矩形的坐標位置,判斷手指點是否在矩形上,如果在則矩形跟隨手指移動。

二、代碼流程

環(huán)境準備:

python: 3.8.8

opencv: 4.2.0.32

mediapipe: 0.8.10.1

注:

1、opencv版本過高或過低可能出現(xiàn)一些如攝像頭打不開、閃退等問題,python版本影響opencv可選擇的版本。

2、pip install mediapipe 后可能導致openCV無法正常使用,卸了重新下載,習慣了就好。

1. 讀取攝像頭視頻,畫矩形
import cv2
import time
import numpy as np
 
 
# 調(diào)用攝像頭 0 默認攝像頭 
cap = cv2.VideoCapture(0)
 
# 初始方塊數(shù)據(jù)
x = 100
y = 100
w = 100
h = 100
 
# 讀取一幀幀照片
while True:
    # 返回frame圖片
    rec,frame = cap.read()
    
    # 鏡像
    frame = cv2.flip(frame,1)
    
    # 畫矩形 
    cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 255), -1)
 
    # 顯示畫面
    cv2.imshow('frame',frame)
    
    # 退出條件
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    
cap.release()
cv2.destroyAllWindows()

這是很基礎(chǔ)的一步操作,此時我們運行這段代碼,攝像頭打開,我們會驚訝地看到自己英俊的臉龐,且左上角有個100*100的紫色矩形。

2. 導入mediapipe處理手指坐標
pip install mediapipe

此時可能出現(xiàn)一些問題,比如openCV突然用不了了,沒關(guān)系,卸載了重新下。

mediapipe詳細信息:Hands - mediapipe (google.github.io)

如何使用Python+OpenCV實現(xiàn)拖拽虛擬方塊效果

簡單來說,它會返回給我們21個手指關(guān)鍵點的坐標,即它在視頻畫面的位置比例( 0~1 ),我們乘以對應畫面的寬高,就能得到手指對應的坐標了。

本次用到食指和中指指尖,也就是8號和12號。

2.1 配置一些基礎(chǔ)信息

import cv2
import time
import numpy as np
import mediapipe as mp
 
 
mp_drawing = mp.solutions.drawing_utils
mp_drawing_styles = mp.solutions.drawing_styles
mp_hands = mp.solutions.hands
 
hands =  mp_hands.Hands(
    static_image_mode=True,
    max_num_hands=2,
    min_detection_confidence=0.5)

2.2 在處理每一幀圖像時,加入

    frame.flags.writeable = False
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    # 返回結(jié)果
    results = hands.process(frame)
 
    frame.flags.writeable = True
    frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)

當我們在視頻流中讀取每一幀圖片時,將其從BGR轉(zhuǎn)為RGB供給mediapipe生成的hands對象讀取,它會返回這張圖片中手指關(guān)鍵點的信息,我們只需要繼續(xù)對其作畫,畫在每一幀圖片上。

    # 如果結(jié)果不為空
    if results.multi_hand_landmarks:
 
        # 遍歷雙手(根據(jù)讀取順序,一只只手遍歷、畫畫)
        for hand_landmarks in results.multi_hand_landmarks:
            mp_drawing.draw_landmarks(
                frame,
                hand_landmarks,
                mp_hands.HAND_CONNECTIONS,
                mp_drawing_styles.get_default_hand_landmarks_style(),
                mp_drawing_styles.get_default_hand_connections_style())

2.3 至此步驟完整代碼

import cv2
import time
import numpy as np
import mediapipe as mp
 
 
mp_drawing = mp.solutions.drawing_utils
mp_drawing_styles = mp.solutions.drawing_styles
mp_hands = mp.solutions.hands
 
hands =  mp_hands.Hands(
    static_image_mode=True,
    max_num_hands=2,
    min_detection_confidence=0.5)
 
 
# 調(diào)用攝像頭 0 默認攝像頭 
cap = cv2.VideoCapture(0)
 
# 方塊初始數(shù)組
x = 100
y = 100
w = 100
h = 100
 
 
# 讀取一幀幀照片
while True:
    # 返回frame圖片
    rec,frame = cap.read()
    
    # 鏡像
    frame = cv2.flip(frame,1)
    
    
    
    frame.flags.writeable = False
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    # 返回結(jié)果
    results = hands.process(frame)
 
    frame.flags.writeable = True
    frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
    
    
    # 如果結(jié)果不為空
    if results.multi_hand_landmarks:
 
        # 遍歷雙手(根據(jù)讀取順序,一只只手遍歷、畫畫)
        # results.multi_hand_landmarks n雙手
        # hand_landmarks 每只手上21個點信息
        for hand_landmarks in results.multi_hand_landmarks:
            mp_drawing.draw_landmarks(
                frame,
                hand_landmarks,
                mp_hands.HAND_CONNECTIONS,
                mp_drawing_styles.get_default_hand_landmarks_style(),
                mp_drawing_styles.get_default_hand_connections_style())
    
    
    # 畫矩形 
    cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 255), -1)
 
    # 顯示畫面
    cv2.imshow('frame',frame)
    
    # 退出條件
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    
cap.release()
cv2.destroyAllWindows()
3. 位置計算

我們這個實驗要求拖動方塊,那肯定也有不拖動的時候,因此不妨根據(jù)上一步獲取食指(8)和中指(12)指尖的位置,如果這倆離得近,我們就在他與方塊重合的時候,根據(jù)手指的位置改變方塊的坐標。

如何使用Python+OpenCV實現(xiàn)拖拽虛擬方塊效果

完整代碼

如何使用Python+OpenCV實現(xiàn)拖拽虛擬方塊效果

import cv2
import time
import math
import numpy as np
import mediapipe as mp
 
# mediapipe配置
mp_drawing = mp.solutions.drawing_utils
mp_drawing_styles = mp.solutions.drawing_styles
mp_hands = mp.solutions.hands
hands =  mp_hands.Hands(
    static_image_mode=True,
    max_num_hands=2,
    min_detection_confidence=0.5)
 
 
# 調(diào)用攝像頭 0 默認攝像頭 
cap = cv2.VideoCapture(0)
 
# cv2.namedWindow("frame", 0)
# cv2.resizeWindow("frame", 960, 640)
 
 
# 獲取畫面寬度、高度
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
 
 
# 方塊初始數(shù)組
x = 100
y = 100
w = 100
h = 100
 
L1 = 0
L2 = 0
 
on_square = False
square_color = (0, 255, 0)
 
# 讀取一幀幀照片
while True:
    # 返回frame圖片
    rec,frame = cap.read()
    
    # 鏡像
    frame = cv2.flip(frame,1)
    
    
    
    frame.flags.writeable = False
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    # 返回結(jié)果
    results = hands.process(frame)
 
    frame.flags.writeable = True
    frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
    
    
    # 如果結(jié)果不為空
    if results.multi_hand_landmarks:
 
 
        # 遍歷雙手(根據(jù)讀取順序,一只只手遍歷、畫畫)
        # results.multi_hand_landmarks n雙手
        # hand_landmarks 每只手上21個點信息
        for hand_landmarks in results.multi_hand_landmarks:
            mp_drawing.draw_landmarks(
                frame,
                hand_landmarks,
                mp_hands.HAND_CONNECTIONS,
                mp_drawing_styles.get_default_hand_landmarks_style(),
                mp_drawing_styles.get_default_hand_connections_style())
            
            # 記錄手指每個點的x y 坐標
            x_list = []
            y_list = []
            for landmark in hand_landmarks.landmark:
                x_list.append(landmark.x)
                y_list.append(landmark.y)
                
            
            # 獲取食指指尖
            index_finger_x, index_finger_y = int(x_list[8] * width),int(y_list[8] * height)
 
            # 獲取中指
            middle_finger_x,middle_finger_y = int(x_list[12] * width), int(y_list[12] * height)
 
 
            # 計算兩指尖距離
            finger_distance = math.hypot((middle_finger_x - index_finger_x), (middle_finger_y - index_finger_y))
 
            # 如果雙指合并(兩之間距離近)
            if finger_distance < 60:
 
                # X坐標范圍 Y坐標范圍
                if (index_finger_x > x and index_finger_x < (x + w)) and (
                        index_finger_y > y and index_finger_y < (y + h)):
 
                    if on_square == False:
                        L1 = index_finger_x - x
                        L2 = index_finger_y - y
                        square_color = (255, 0, 255)
                        on_square = True
 
            else:
                # 雙指不合并/分開
                on_square = False
                square_color = (0, 255, 0)
 
            # 更新坐標
            if on_square:
                x = index_finger_x - L1
                y = index_finger_y - L2
            
            
 
    # 圖像融合 使方塊不遮擋視頻圖片
    overlay = frame.copy()
    cv2.rectangle(frame, (x, y), (x + w, y + h), square_color, -1)
    frame = cv2.addWeighted(overlay, 0.5, frame, 1 - 0.5, 0)
    
 
    # 顯示畫面
    cv2.imshow('frame',frame)
    
    # 退出條件
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    
cap.release()
cv2.destroyAllWindows()

到此,相信大家對“如何使用Python+OpenCV實現(xiàn)拖拽虛擬方塊效果”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI