# -*- coding: utf-8 -*-
"""
Created on Fri Mar 19 10:06:26 2021

@author: shsbnu
"""
import cv2
import numpy as np


cap = cv2.VideoCapture("autodrive.mp4") 
lcval=(100,100,111)	
hcval=(124,255,255)	
# =============================================================================
# row=220
# row1=180
# ls=[]
# 
# =============================================================================
while True:
    #读取视频当前帧
    ret, frame = cap.read() 
    
    #ret,frame用于存放cap.read()的两个返回值,
    #其中ret是布尔值，如果正确读到视频，则得到True，否则得到False    
    if not ret:
        break
    ROI = np.zeros(frame.shape, np.uint8)
    #获得水平镜像图像
    #frame=cv2.flip(frame,1) 
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    newimg = cv2.inRange(hsv,lcval,hcval)

    contours, hier = cv2.findContours(newimg, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    k=len(contours)
    if k<=0:
        continue
    maxi=0
    maxa=0
    for j in range(k):
        tmp=cv2.contourArea(contours[j])
        if tmp>maxa:
            maxa=tmp
            maxi=j
    cv2.drawContours(ROI,contours,maxi,(255,255,255),-1)
    # 膨胀
    #kernel = np.ones((7, 7),dtype="uint8")
    #newimg = cv2.dilate(ROI, kernel, iterations=2)
    newimg=ROI
# =============================================================================
# 
#     up=30
#     down=300 #夹子所在位置230
#     ls=[]#每隔50行，取蓝线上的一个点，存放在该列表中
#     
#     i=0#用于记录点的个数
#     while down>up and i<=5:        
#         rowimg=newimg[down,:]
#         windex=np.where(rowimg==255)
#         a=len(windex[0])
#         if a>0:
#             py=down
#             px=windex[0][int(a/2)]
#             ls.append((px,py))
#             i+=1  
#         down-=50
#     #用于标注各个点坐标    
#     if i==0:
#         cv2.waitKey(0)
#     else:
#         print(i)
#     for px,py in ls:
#         cv2.circle(frame,(px,py),2,(255,255,255),2)   
# 
#     cv2.imshow("src",frame)
# =============================================================================
    cv2.imshow("newimg",newimg)
    c = cv2.waitKey(10) 
    #如果按键是esc，则结束视频
    if c == 27:		
        print("视频结束")
        break
#print(ls)
cv2.destroyAllWindows()
