python—openCV实时追踪乒乓球

"""
张耀
2021年08月20日
"""
import cv2
import numpy as np


cap = cv2.VideoCapture(0)
while cap.isOpened():
    # 获取摄像头图像
    r, img = cap.read()
    # 截获乒乓球颜色
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    miny = np.array([5, 100, 250])
    maxy = np.array([25, 255, 255])
    # 乒乓球掩膜
    mask = cv2.inRange(hsv, miny, maxy)
    yellow = cv2.bitwise_and(img, img, mask=mask)
    # 图像处理
    gray_y = cv2.cvtColor(yellow, cv2.COLOR_BGR2GRAY)
    r, threading_y = cv2.threshold(gray_y, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
    k = np.ones((10, 10), np.uint8)
    threading_y = cv2.morphologyEx(threading_y, cv2.MORPH_CLOSE, k, iterations=2)
    # 获取轮廓
    r, counter, h = cv2.findContours(threading_y, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    n = len(counter)
    if n != 0:
        loc = []
        ri = []
        for i in range(n):
            (x, y), r = cv2.minEnclosingCircle(counter[i])
            loc.append((int(x), int(y)))
            ri.append(int(r))
        # 筛选轮廓
        dex = ri.index(max(ri))
        # 描绘轮廓
        cv2.circle(img, loc[dex], ri[dex], (0, 0, 255), 2)
    cv2.imshow('i', img)
    c = cv2.waitKey(1)
    if c == 27:
        break
cap.release()
cv2.destroyAllWindows()

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值