头一回发博客,之前也是在CSDN上受益良多,觉得还是把自己的工作梳理一遍比较好
昨天安装了opencv-python,这个安装相当简单,
因为想要做用摄像头识别信号灯,来控制小车找灯,opencv-python相对简单,摄像头还没到,先找一个视频追踪物体先
首先我想找到这个物体的颜色特征,截个屏找图片中物体的HSV范围,通过这段代码实现鼠标点输出HSV
#!usr/bin/python
# -*- coding: utf-8 -*-
import cv2
import numpy as np
from matplotlib import pyplot as plt
image=cv2.imread('/home/zhangxuhnr/图片/2018-07-09 12-18-09屏幕截图.png')
HSV=cv2.cvtColor(image,cv2.COLOR_BGR2HSV)
def getpos(event,x,y,flags,param):
if event==cv2.EVENT_LBUTTONDOWN:
print(HSV[y,x])
#th2=cv2.adaptiveThreshold(imagegray,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)
cv2.imshow("imageHSV",HSV)
cv2.imshow('image',image)
cv2.setMouseCallback("imageHSV",getpos)
k = cv2.waitKey(0)
if k == 27:
# wait for ESC key to exit
cv2.destroyAllWindows()
查找到HSV范围后就可以设置阈值了
#!usr/bin/python
# -*- coding: utf-8 -*-
import numpy as np
import cv2
import time
cap = cv2.VideoCapture('/home/zhangxuhnr/桌面/2923069355b0788a820cc36a09a2c535.mp4')
while (1):
start_time=time.time()
ret,frame=cap.read()
#转换BGR2HSV
hsv=cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
#设定物体HSV阈值
lower=np.array([[13,65,215]])
upper=np.array([[22,95,245]])
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 center
#可以根据质心坐标判断小车左右方向
#cv2.imshow('frame',frame)
cv2.imshow('mask',mask)
#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()