OpenCV自学笔记10:视频中分割出圆形

来源:互联网 发布:c语言入门免费书籍 编辑:程序博客网 时间:2024/06/06 09:51

视频中分割出圆形

import cv2import numpy as npcap = cv2.VideoCapture('video/video.avi')low_range = np.array([0, 123, 100])high_range = np.array([5, 255, 255])lastX = 0lastY = 0deltaX = 0deltaY = 0while True:    ret, frame = cap.read()    # change bgr to hsv    hue_image = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)    # set threshold, the white area is the ball    threshold_img = cv2.inRange(hue_image, low_range, high_range)    # find contours to get center of the ball    image, contour, hierarchy = cv2.findContours(threshold_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)    if contour:        circles = cv2.HoughCircles(image, cv2.HOUGH_GRADIENT, 1, 100, \                                   param1=20, param2=10, minRadius=10, maxRadius=20)        if circles is not None:            circle = circles[0][0]            x = circle[0]            y = circle[1]            radius = circle[2]            center = (x, y)            deltaX = int(x) - lastX            deltaY = int(y) - lastY            lastX = int(x)            lastY = int(y)            if radius > 5 and lastX != 0 and lastY != 0 and np.abs(deltaX - lastX) > 5 and np.abs(deltaY - lastY) > 5 :                img = cv2.circle(frame, center, radius, (0, 255, 0), 2)                img = cv2.line(frame, (lastX, lastY), (lastX + deltaX, lastY + deltaY), (0, 255, 0), 2)    cv2.imshow('video2', frame)    if cv2.waitKey(100) & 0xFF == ord('q'):        breakcap.release()cv2.destroyAllWindows()