主要是记录一下自己做板球系统的过程
采用opencv usb摄像头 提取小球位置 并串口输出给单片机
借鉴了很多网上的资源 实在没法一一列举,引用 了
对开源精神表示感谢 室友的美背出镜。。
# -*- coding:utf-8 -*-
import serial
import numpy as np
import cv2
# 读 取 图 片
cap = cv2.VideoCapture(0)
color = [
([35, 63, 66], [77, 255, 255]) # ([10, 73, 76], [15, 255, 255]) # 蓝色范围~这个是我自己试验的范围,可根据实际情况自行调整~注意:数值按[b,g,r]排布
]
# 如果color中定义了几种颜色区间,都可以分割出来
# for (lower, upper) in color:
# 创建NumPy数组
lower = np.array(color[0][0], dtype="uint8") # 颜色下限
upper = np.array(color[0][1], dtype="uint8") # 颜色上限
a=0
while 1:
#im = cv2.imread('2.jpg')
_, img = cap.read()
if _:
# continue
##img = cv2.imread('/home/lqy/Data/lv/漏底20180901091938对照样本.jpg') # 直接读为灰度图像
# 缩小图像10倍(因为我的图片太大,所以要缩小10倍方便看看效果)
# height, width = img.shape[:2]
# size = (int(width * 2), int(height * 2)) # bgr
# img = cv2.resize(img, size, interpolation=cv2.INTER_AREA)
#BGR转化为HSV
HSV=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)#COLOR_BGR2HSV)
# cv2.imshow("imageHSV",HSV)
# cv2.imshow("imageHSV",HSV)
# cv2.imshow('image',img)
# 根据阈值找到对应颜色
mask = cv2.inRange(HSV, lower, upper) #查找处于范围区间的
# mask = 255-mask #留下铝材区域
### # output = cv2.bitwise_and(img, img, mask=mask) #获取铝材区域
#bgroutput = cv2.cvtColor(output,cv2.COLOR_HSV2BGR)
# 展示图片
# cv2.imshow("images", np.hstack([img, output]))
mask = cv2.erode(mask, None, iterations=4)
mask = cv2.dilate(mask, None, iterations=4)
# cv2.imshow("detect", mask)
contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)#CHAIN_APPROX_SIMPLE)
# print(mask.shape)
# print(mask[0])
# print(len(contours))
if len(contours) > 0:
c = max(contours, key=cv2.contourArea)
else:
cv2.imshow("chanle", img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
continue
cv2.drawContours(img, c, -1, (0, 0, 255), 1)#画轮廓
# for i in contours:
# print(cv2.contourArea(i)) # 计算缺陷区域面积
# x, y, w, h = cv2.boundingRect(c) # 画矩形框
# cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 1)
# cv2.circle(img, (x + int(w/2), y + int(h/2)), 5, (0, 255, 0), -1)#外接矩形
# ((x, y), radius) = cv2.minEnclosingCircle(c) #外接圆
# cv2.circle(img, (int(x), int(y)), int(radius), (0, 255, 255), 2)
# cv2.circle(img, (int(x), int(y)), 5, (0, 255, 255), -1)
# cv.imwrite(show_result_path, match_img_color)
# 计算轮廓的矩
M = cv2.moments(c) #矩阵秩
# 计算轮廓的重心
center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
cv2.circle(img, center, 5, (0, 0, 255), -1)
print(center)
# cv2.imshow("detect",img)
cv2.imshow("chanle", img)
# cv2.waitKey(0)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放清理
cap.release()
cv2.destroyAllWindows()