import cv2 as cv
import numpy as np
def read_rgb_img(img_name):
rgb_img = cv.imread(img_name,cv.IMREAD_COLOR)
cv.imshow("rgb img",rgb_img)
return rgb_img
def convert_rgb2gray(img):
gray_img = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
# 采用高斯滤波去掉噪点
gray_img = cv.GaussianBlur(gray_img,(5,5),0)
cv.imshow("gray img", gray_img)
return gray_img
def convert_gray2binary(img):
binary_img = cv.adaptiveThreshold(img,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,cv.THRESH_BINARY_INV,5,2)
cv.imshow("binary img", binary_img)
return binary_img
def filter_tenis(img,lower_color,upper_color):
hsv_img = cv.cvtColor(img,cv.COLOR_BGR2HSV)
# 查找颜色
mask_img = cv.inRange(hsv_img, lower_color, upper_color)
cv.imshow("mask img",mask_img)
return mask_img
def getContours(img):
_,contours,hierarchy = cv.findContours(img,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)
print(contours,hierarchy)
return contours
def process_tenis_contours(rgb_img,contours):
black_img = np.zeros([rgb_img.shape[0],rgb_img.shape[1],3],np.uint8)
for c in contours:
# 计算面积
area = cv.contourArea(c)
# 该函数计算曲线长度或闭合轮廓周长。
perimeter = cv.arcLength(c,True)
# 获取最小的外切圆
((x,y),radius) = cv.minEnclosingCircle(c)
# 绘制轮廓
cv.drawContours(rgb_img,[c],-1,(150,250,150),2)
cv.drawContours(black_img,[c],-1,(150,250,150),2)
# 获取轮廓中心点
# cx,cy = get_contour_center(c)
# print(cx,cy)
x = int(x)
y = int(y)
cv.circle(rgb_img,(x,y),int(radius),(0,0,255),2)
cv.circle(black_img,(x,y),int(radius),(0,0,255),2)
print("Area:{},primeter:{}".format(area,perimeter))
print("number of contours:{}".format(len(contours)))
cv.imshow("rgb img contours",rgb_img)
cv.imshow("black img contours",black_img)
if __name__ == '__main__':
img_name = "assets/tenis1.jpg"
# 定义范围
lower_color = (30, 120, 130)
upper_color = (60, 255, 255)
rgb_img = read_rgb_img(img_name)
binary_imgage = filter_tenis(rgb_img,lower_color,upper_color)
contours = getContours(binary_imgage)
process_tenis_contours(rgb_img,contours)
cv.waitKey(0)
cv.destroyAllWindows()