当视频帧变为灰度时,写在帧上的文本也会变为灰色

时间:2017-12-16 14:07:52

标签: python-3.x opencv bgr

我正在构建一个运动检测器应用程序。为了使运动检测算法工作,我将帧转换为灰度,所以现在应用程序能够检测到运动。但是当我尝试在框架上放置文本时发布像“MOVING”这样的消息,即使文字已经变成灰色而且几乎看不到。如何在视频帧上绘制彩色文字?

以下是我的动作检测应用程序代码

import cv2
import numpy as np
from skimage.measure import compare_ssim
from twilio.rest import Client

#we can compare two images using Structural Similarity
#so a small change in pixel value won't prompt this method to term both images as dissimilar
#the closer the value is to 1,the more similar two images are
def ssim(A, B):
    return compare_ssim(A, B, data_range=A.max() - A.min())

#capture a video either from a file or a live video stream
cap = cv2.VideoCapture(0)
first_frame = True
prev_frame = None
current_frame = None
#we keep a count of the frames
frame_counter = 0
while True:
    if frame_counter == 0:
        #prev_frame will always trail behind the current_frame
        prev_frame = current_frame
    #get a frame from the video
    ret, current_frame = cap.read()
    #if we reach the end of the video in case of a video file,stop reading
    if current_frame is None:
        break

    #convert the image to grayscale
    current_frame = cv2.cvtColor(current_frame,cv2.COLOR_BGR2GRAY)
    if first_frame:
        #for the first time prev_frame and current_frame will be the same
        prev_frame = current_frame
        first_frame = False

    if frame_counter == 9:
        #compare two images based on SSIM
        ssim_val = ssim(current_frame, prev_frame)
        print(ssim_val)
        #if there is a major drop in the SSIM value ie it has detected an object
        if ssim_val < 0.8:
            # Here I want to put a colored text to the screen
            cv2.putText(current_frame, "MOVING", (100, 300),
                        cv2.FONT_HERSHEY_TRIPLEX, 4, (255, 0, 0))
        frame_counter = -1

    #show the video as a series of frames
    cv2.imshow("Motion Detection",current_frame) #(name of the window,image file)
    frame_counter += 1

    key = cv2.waitKey(1) & 0xFF  #cv2.waitKey(1) returns a value of -1 which is masked using & 0xFF to get char value
    if key == ord('q'): #gives ASCII value of 'q'
        break

#release the resources allocated to the video file or video stream
cap.release()
#destroy all the windows
cv2.destroyAllWindows()

我在线搜索,我得到了这段代码,基本上建议将灰度转换回BGR

backtorgb = cv2.cvtColor(current_frame, cv2.COLOR_GRAY2RGB)

但是这不起作用。我甚至在转换为灰度帧之前拍摄了当前帧的副本,然后尝试在复制的彩色帧上书写,但文本仍然是灰色的而不是彩色的。我应该怎么做?

0 个答案:

没有答案