首页 > 解决方案 > 如何删除手部跟踪程序中的 Open cv 错误

问题描述

我的代码中出现此错误

错误:OpenCV(4.5.1) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-oduouqig\opencv\modules\imgproc\src\color.cpp:182:错误:(-215 :Assertion failed) !_src.empty() in function 'cv::cvtColor'

my code

import cv2
import mediapipe as mp
import time

cap = cv2.VideoCapture(1)

mpHands = mp.solutions.hands
hands = mpHands.Hands()
mpDraw = mp.solutions.drawing_utils

ctime = 0
ptime = 0

while True:
    ret, img = cap.read()
    imgRGB = cv2.cvtColor(img , cv2.COLOR_BGR2RGB)
    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==0:
                    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_SIMPLEX, 3 , (255,0,255) , 3)



    cv2.imshow("Image", img)
    cv2.waitKey()

标签: pythonopencv

解决方案


我认为它似乎没有正确读取捕获,尝试对视频文件执行 VideoCapture,并添加if not ret:语句

在这种情况下也cap.isOpened()非常有用

完整代码-

import cv2
import mediapipe as mp
import time

cap = cv2.VideoCapture(1)

mpHands = mp.solutions.hands
hands = mpHands.Hands()
mpDraw = mp.solutions.drawing_utils

ctime = 0
ptime = 0

while cap.isOpened():
    ret, img = cap.read()
    if not ret:
        break
    imgRGB = cv2.cvtColor(img , cv2.COLOR_BGR2RGB)
    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==0:
                    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_SIMPLEX, 3 , (255,0,255) , 3)



    cv2.imshow("Image", img)
    cv2.waitKey()

print('loop is breaking')
cap.release()
cv2.destroyAllWindows()


推荐阅读