python - 使用手势控制鼠标
问题描述
当我运行下面的代码时,我收到以下错误:
回溯(最近一次通话最后):
文件“path\gesture_mouse.py”,第 63 行,在
cv2.circle(img, (cx, cy), (w+h)/4, (0, 0, 255), 2)
TypeError:需要整数参数,得到浮点数
[ WARN:0] terminating async callback
我尝试分别预定义中心和半径。
import cv2
import numpy as np
from pynput.mouse import Button, Controller
import wx
mouse = Controller()
app = wx.App(False)
(sx, sy) = wx.GetDisplaySize()
(camx, camy) = (320, 240)
lowerBound = np.array([33, 80, 40])
upperBound = np.array([102, 255, 255])
cam = cv2.VideoCapture(0)
kernelOpen = np.ones((5, 5))
kernelClose = np.ones((20, 20))
pinchFlag = 0
while True:
ret, img = cam.read()
img=cv2.resize(img, (340, 220))
# convert BGR to HSV
imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# create the Mask
mask = cv2.inRange(imgHSV, lowerBound, upperBound)
# morphology
maskOpen = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernelOpen)
maskClose = cv2.morphologyEx(maskOpen, cv2.MORPH_CLOSE, kernelClose)
maskFinal = maskClose
conts, h = cv2.findContours(maskFinal.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
if len(conts) == 2:
if pinchFlag == 1:
pinchFlag = 0
mouse.release(Button.left)
x1, y1, w1, h1 = cv2.boundingRect(conts[0])
x2, y2, w2, h2 = cv2.boundingRect(conts[1])
cv2.rectangle(img, (x1, y1), (x1+w1, y1+h1), (255, 0, 0), 2)
cv2.rectangle(img, (x2, y2), (x2+w2, y2+h2), (255, 0, 0), 2)
cx1 = x1+w1/2
cy1 = y1+h1/2
cx2 = x2+w2/2
cy2 = y2+h2/2
cx = (cx1+cx2)/2
cy = (cy1+cy2)/2
cv2.line(img, (cx1, cy1), (cx2, cy2), (255, 0, 0), 2)
cv2.circle(img, (cx, cy), 2, (0, 0, 255), 2)
mouseLoc = (sx-(cx*sx/camx), cy*sy/camy)
mouse.position = mouseLoc
while mouse.position != mouseLoc:
pass
elif len(conts) == 1:
x, y, w, h = cv2.boundingRect(conts[0])
if pinchFlag == 0:
pinchFlag = 1
mouse.press(Button.left)
cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
cx = x+w/2
cy = y+h/2
cv2.circle(img, (cx, cy), (w+h)/4, (0, 0, 255), 2)
mouseLoc = (sx-(cx*sx/camx), cy*sy/camy)
mouse.position = mouseLoc
while mouse.position != mouseLoc:
pass
cv2.imshow("cam", img)
cv2.waitKey(5)
我期待当两个绿色对象出现在框架中时,它们将被划入一个蓝色框,并且从两个框的中心出现一条蓝线,其中将出现一个红点,表示光标的位置(鼠标)。
解决方案
就像错误所说的那样,该函数需要 int 作为输入,但您输入的是浮点数。这是因为这些值是除法计算的结果。
print(type(10)) #<class 'int'>
print(type(5)) #<class 'int'>
print(type(10/5)) #<class 'float'>
print(10/5) #2.0
解决方案是将计算值转换为整数:
cv2.circle(img, (int(cx), int(cy), int((w+h)/4), (0, 0, 255), 2)
推荐阅读
- fortran - 函数声明警告:函数“f”在 (1) 处的返回值未设置 [-Wreturn-type]
- python - Python TK 库水平滚动条未显示
- amazon-web-services - 从 EC2 实例以编程方式确定可用区
- swift - Swift-NumberFormatter
- amazon-web-services - 文件从 Amazon S3 中消失
- json - 正则表达式替换 - json中的双引号
- github - 2 PR for 2 commits on github
- linux - linux 测试模块构建失败,来自 gcc 的“无输入文件”
- javascript - React 应用程序在本地运行,但在推送到 heroku(产品)时因意外令牌“<”而失败
- r - 如何应用 3 个函数来创建一个新的数据框