Reputation: 757
I am trying to find the color of a video frame using openCV. Detecting color is using HSV approach. My codes are as follows.
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()
And, color detection detecting code is,
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
I am getting results correctly with annotated frames. But I need to find out, at what time of video, which color is present. So I need to showcase like,
second 1 - Red Color
second 2 - Red Color
second 3 - Green Color like this.
Can anybody help.
Upvotes: 0
Views: 1259
Reputation: 1306
You can use
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
so once you have this data you can get time in seconds by doing a simple
time = cframe / fps
Note: if CV_CAP_PROP_FRAME_COUNT dosent work try the number(id) equivalents
Upvotes: 1