赞
踩
代码如下,该代码利用hsv空间进行颜色识别,要提前给出阈值范围才可以匹配到
识别到对应色块能以色块为中心画圈,返回值为色块的中心坐标,配合舵机云台可以实现追踪
- #!usr/bin/python
- # -*- coding: utf-8 -*-
- import numpy as np
- import cv2
- import serial
- import time
- #cap = cv2.VideoCapture('D:/Open CV/py/ziliao/zhuizong/VID_20220724_202819.mp4')
- cap = cv2.VideoCapture(0)
- ser = serial.Serial('/dev/ttyAMA0', 9600)
-
- def fenge(x):
- #分割得到的数据,将坐标除以4,得到小于255的数,便于发送,将小数和整数分割
- x_yuchu=x/4
- x_intpart=x//4
- x_fracpart=(x_yuchu-x_intpart)*100
- return (x_intpart,x_fracpart)#返回(整数,小数)
- while (cap.isOpened()):
- start_time = time.time()
- ret, frame1 = cap.read()
- if ser.isOpen == False:
- ser.open() # 打开串口
- if ret == True:
- #frame=cv2.resize(frame1,None,fx=0.5,fy=0.5)
- # 转换BGR2HSV
- hsv = cv2.cvtColor(frame1, cv2.COLOR_BGR2HSV)
- # 设定物体HSV阈值
- upper = np.array([156, 230, 255])
- lower = np.array([[0,116, 237]])
- mask = cv2.inRange(hsv, lower, upper)
- mask = cv2.erode(mask, None, iterations=2)
- mask = cv2.dilate(mask, None, iterations=2)
- # 找最大轮廓,提取质心
- cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
- center = None
- if len(cnts) > 0:
- c = max(cnts, key=cv2.contourArea)
- M = cv2.moments(c)
- center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
- print("cent_x=",center[0])
- print("cent_y=",640-center[1])
- ''' 这里是查看中心图标
- size = mask.shape
- y = size[0]//2
- x = size[1] // 2
- print("img_x=", x)
- print("img_y=",y)
- '''
- size = ser.inWaiting()
- if size != 0:
- res = ser.read(size)
- zuobiao_x=fenge(center[0])
- zuobiao_y=fenge(center[1])
- #发送坐标 0x5b 0xb3 x坐标/4整数 x坐标/4小数 y坐标/4整数 y坐标/4小数
- writebuf = bytearray([0x5b, 0xb3,zuobiao_x[0],zuobiao_x[1],zuobiao_y[0],zuobiao_y[1], 0x5b])
- ser.write(writebuf)# 读取内容并显示
- print(res) #调试用,查看收到的数据
- ser.flushInput() # 情况接收缓存区
- time.sleep(0.5) # 软件延时
- cv2.circle(mask, center, 7, 128, -1)#画点
- cv2.circle(mask,center,30,(0,255,255))#画圆
- # 可以根据质心坐标判断小车左右方向
- # cv2.imshow('frame',frame)
- cv2.imshow('mask', mask)
- cv2.imshow('image', frame1)
- # cv2.imshow('res',res)
- k = cv2.waitKey(5) & 0xFF
- if k == 27: # esc退出
- break
- #print("FPS:", 1.0 / (time.time() - start_time)) # 计算一下处理的帧速
- cap.release()
- cv2.destroyAllWindows()
-
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。