當前位置:網站首頁>opencv檢測乒乓球

opencv檢測乒乓球

2022-01-27 04:07:27 西木康

乒乓球檢測

先上代碼

import cv2#讀取視頻 "D:\\image\\153.mp4"或者相機
import numpy as np
cap = cv2.VideoCapture(1)#從相機獲取視頻
while(cap.isOpened()):
    ret,frame = cap.read()
    if frame is None:#防止後面卡死 或 視頻最後為空
        print("kong")
        break
    hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)#
    minRed = np.array([0,50,50])
    maxRed = np.array([30,255,255])
    mask = cv2.inRange(hsv,minRed,maxRed)
    frame1 = frame.copy()
    res = cv2.bitwise_and(frame1,frame1,mask = mask)
    gray = cv2.cvtColor(res,cv2.COLOR_BGR2GRAY)
    kernel = np.ones((60,60),np.uint8)
    #dst = cv2.erode(mask,kernel,iterations = 4)
    ret,binary1 = cv2.threshold(gray,1,255,cv2.THRESH_BINARY)
    dst = cv2.morphologyEx(binary1,cv2.MORPH_OPEN,kernel)
    contours1,hierarchy = cv2.findContours(dst,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
    
    #cv2.drawContours(frame,contours1,-1,(0,0,255),2)#畫輪廓圖
    if not contours1 :#如果無輪廓後面會卡死
        continue
    (x,y),radius = cv2.minEnclosingCircle(contours1[0])
    center = (int(x),int(y))
    radius = int(radius)
    cv2.circle(frame,center,radius,(0,0,255),5)#輪廓中像素坐標
    print(center)
    cv2.imshow('frame',frame)
    c = cv2.waitKey(25)
    if c == 27:
        break
print("jieshu")
cap.release()
cv2.destroyAllWindows()

只能貼圖片不能弄視頻

版權聲明
本文為[西木康]所創,轉載請帶上原文鏈接,感謝
https://cht.chowdera.com/2022/01/202201270407265174.html

隨機推薦