如何使用openCV查找帧的时间

时间:2019-10-14 07:07:25

标签: python opencv

我正在尝试使用openCV查找视频帧的颜色。使用HSV方法检测颜色。我的代码如下。

read_video.py

import cv2
from detect_color import color_detection

def video_camera():
    video = cv2.VideoCapture("video_file.mp4")
    success, image = self.video.read()
    if success: 
        image = color_detection(image)
        ret, jpeg = cv2.imencode('.jpg', image)        
        return jpeg.tobytes()

而且,颜色检测检测代码是

import cv2
import numpy as np

def detectGreen(frame):
    # Convert BGR to HSV
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # define range of green color in HSV
    lower_green = np.array([65,60,60])
    upper_green = np.array([80,255,255])

    # Threshold the HSV image to get only green colors
    mask = cv2.inRange(hsv, lower_green, upper_green)

    kernel = np.ones((5,5),'int')
    dilated = cv2.dilate(mask,kernel)

    # Bitwise-AND mask and original image
    res = cv2.bitwise_and(frame,frame, mask=mask)
    ret,thrshed = cv2.threshold(cv2.cvtColor(res,cv2.COLOR_BGR2GRAY),3,255,cv2.THRESH_BINARY)    
    contours,hier = cv2.findContours(thrshed,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

    area = [0]
    for cnt in contours:
        #Contour area is taken
        area.append(cv2.contourArea(cnt))
    return max(area)

def detectRed(frame):
    ## Similar Code to find out RED color

def color_detection(frame):
    green_area = detectGreen(frame)
    red_area = detectRed(frame)

    if red_area > 500 and \
        red_area > green_area:
        cv2.putText(frame, "Red Object", (5,45), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 1)
        cv2.rectangle(frame,(3,15),(255,55),(0,255,255),2)

    elif green_area > 500 and \
        green_area > red_area:
        cv2.putText(frame, "Green Object", (5,45), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 1)
        cv2.rectangle(frame,(3,15),(255,55),(0,255,255),2)

    return frame

我使用带注释的框架正确获得结果。但是我需要找出在什么时候播放视频,出现哪种颜色。所以我需要展示,

second 1 - Red Color
second 2 - Red Color
second 3 - Green Color  like this.

任何人都可以帮忙。

1 个答案:

答案 0 :(得分:1)

您可以使用

cframe = video.get(CV_CAP_PROP_POS_FRAMES) # retrieves the current frame number
tframe = video.get(CV_CAP_PROP_FRAME_COUNT) # get total frame count
fps = video.get(CV_CAP_PROP_FPS)  #get the FPS of the videos

因此,一旦有了这些数据,您就可以通过简单的

来获得时间(以秒为单位)
time = cframe / fps

注意:   如果CV_CAP_PROP_FRAME_COUNT个剂量工作正常,请尝试等效的数字(id)

相关问题