方法一:目标物体白色,其余黑色
import cv2
import numpy as npdef extrace_object():capture = cv2.VideoCapture("G:/Juptyer_workspace/study/data/yy.mp4")while(True):ret,frame = capture.read()if ret==False:breakhsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)lower = np.array([78,43,46])#由于水杯是青色的故需要根据表格选出hsv对应的min值upper = np.array([99,255,255])#由于水杯是青色的故需要根据表格选出hsv对应的max值mask = cv2.inRange(hsv,lowerb=lower,upperb=upper)cv2.imshow("video",frame)cv2.imshow("mask",mask)c = cv2.waitKey(40)if c==27:breakt1 = cv2.getTickCount()
extrace_object()
t2 = cv2.getTickCount()
time = (t2-t1)/cv2.getTickFrequency()#显示当前运行时间
print("time:%s ms"%(time*1000))#输出当前运行时间单位为ms
cv2.waitKey(0)cv2.destroyAllWindows()
效果图如下:
方法二:目标物体颜色保留,其余黑色
import cv2
import numpy as npdef extrace_object():capture = cv2.VideoCapture("G:/Juptyer_workspace/study/data/yy.mp4")while(True):ret,frame = capture.read()if ret==False:breakhsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)lower = np.array([78,43,46])#由于水杯是青色的故需要根据表格选出hsv对应的min值upper = np.array([99,255,255])#由于水杯是青色的故需要根据表格选出hsv对应的max值mask = cv2.inRange(hsv,lowerb=lower,upperb=upper)dst = cv2.bitwise_and(frame,frame,mask=mask)cv2.imshow("video",frame)#cv2.imshow("mask",mask)cv2.imshow("dst",dst)c = cv2.waitKey(40)if c==27:breakt1 = cv2.getTickCount()
extrace_object()
t2 = cv2.getTickCount()
time = (t2-t1)/cv2.getTickFrequency()#显示当前运行时间
print("time:%s ms"%(time*1000))#输出当前运行时间单位为ms
cv2.waitKey(0)cv2.destroyAllWindows()
效果图如下:
cv2.inRange(hsv,lowerb=lower,upperb=upper)
:对HSV颜色过滤,lowerb和upperb需要查下面的表进行颜色转换
BGR和HSV对应色彩表