# -*- coding: utf-8 -*-
"""
Created on Wed Mar 17 14:41:06 2021

@author: shsbnu
"""
import cv2

#用数字表示摄像头编号，0表示电脑内置摄像头；若为文件，则表示从视频中读取图像
cap = cv2.VideoCapture("output.mp4")   
def nothing(x):
    pass

cv2.namedWindow('readframe')

cv2.createTrackbar('hmin','readframe',100,125,nothing)
cv2.createTrackbar('smin','readframe',100,200,nothing)
cv2.createTrackbar('vmin','readframe',111,200,nothing)

cv2.createTrackbar('hmax','readframe',129,255,nothing)
cv2.createTrackbar('smax','readframe',198,255,nothing)
cv2.createTrackbar('vmax','readframe',255,255,nothing)
#lcval=(35,43,46)	
#hcval=(77,255,255)

while True:
    #读取视频当前帧
    ret, frame = cap.read() 
    #ret,frame用于存放cap.read()的两个返回值,
    #其中ret是布尔值，如果正确读到视频，则得到True，否则得到False    
    if not ret:
        break
    #获得水平镜像图像
    frame=cv2.flip(frame,3) 
    cv2.imshow("src",frame)
    
    b,g,r=cv2.split(frame)
    hmin=cv2.getTrackbarPos('hmin','readframe')
    smin=cv2.getTrackbarPos('smin','readframe')
    vmin=cv2.getTrackbarPos('vmin','readframe')
    
    hmax=cv2.getTrackbarPos('hmax','readframe')
    smax=cv2.getTrackbarPos('smax','readframe')
    vmax=cv2.getTrackbarPos('vmax','readframe')
    
    
    low_hsv = (hmin,smin,vmin)
    high_hsv = (hmax,smax,vmax)
    
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    cv2.imshow("h",hsv)
        
    newimg = cv2.inRange(hsv,lowerb=low_hsv,upperb=high_hsv)
    
    # 3*3 腐蚀
    erode_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
    raw_img = cv2.erode(newimg, erode_kernel, iterations=1)
    # 7*7 膨胀
    dilate_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 9))
    raw_img = cv2.dilate(raw_img, dilate_kernel, iterations=2)
    # 均值模糊
    #raw_img = cv2.medianBlur(raw_img, 3)
    #rimg= cv2.medianBlur(b,11)
    
    #显示图像
    cv2.imshow("readframe", newimg)
    cv2.imshow("handle",raw_img)
    #等待10毫秒时间的按键
    c = cv2.waitKey(10)
    if c>0:
        print(c)
    
    if c == 27:#按esc，退出程序
        print("视频结束")
        break        

#释放摄像头并销毁所有窗口
cap.release() 
cv2.destroyAllWindows() 