如何在openCV&Python中实现鼠标指针的移动?

2024-06-16 11:15:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python和OpenCV相当陌生,我正在努力构建一个鼠标指针移动的眼球跟踪系统。到目前为止,我的脚本可以识别瞳孔并跟踪瞳孔的位置,但我不确定如何将鼠标的移动指定给瞳孔的位置。在

我使用的是opencv4.0.0、python2.7和numpy。 我已经找到了一些答案,比如这个How can I move mouse by detected face and Eye using OpenCV and Python,但是我不太确定如何在我的脚本中实现解决方案,因为我没有人脸和眼睛检测功能。在

while True:
    ret, frame = cap.read()
    if ret is False:
        break

    roi = frame[20: 300, 27: 396]
    rows, cols, _ = roi.shape
    gray_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
    #gray_roi = cv2.GaussianBlur(gray_roi, (7, 7), 0)

    _, threshold = cv2.threshold(gray_roi, 22, 255, cv2.THRESH_BINARY_INV)
    contours, hierarchy = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    contours = sorted(contours, key=lambda x: cv2.contourArea(x), reverse=True)

    for cnt in contours:
        (x, y, w, h) = cv2.boundingRect(cnt)

        cv2.drawContours(roi, [cnt], -1, (0, 0, 255), 3)
        cv2.rectangle(roi, (x, y), (x + w, y + h), (255, 0, 0), 2)
        cv2.line(roi, (x + int(w/2), 0), (x + int(w/2), rows), (0, 255, 0), 2)
        cv2.line(roi, (0, y + int(h/2)), (cols, y + int(h/2)), (0, 255, 0), 2)
        break

    cv2.imshow("Threshold", threshold)
    cv2.imshow("gray roi", gray_roi)
    cv2.imshow("Roi", roi)
    key = cv2.waitKey(30)
    if key == 27:
        break

cv2.destroyAllWindows()

感谢任何帮助,谢谢!在


Tags: andkey脚本threshold鼠标cv2opencvint