简体   繁体   English

将实时视频帧转换为灰度(OpenCV)

[英]Converting Live Video Frames to Grayscale (OpenCV)

First and foremost, I should say that I'm a beginner to OpenCV. 首先,我应该说我是OpenCV的初学者。 I'm trying to convert a live video stream from my webcam from RGB to Grayscale. 我正在尝试将网络摄像头中的实时视频流从RGB转换为灰度。

I have the following code in my function: 我的函数中有以下代码:

VideoCapture cap(0);

while (true)
{
    Mat frame;
    Mat grayscale;
    cvtColor(frame, grayscale, CV_RGB2GRAY);
    imshow("Debug Window", grayscale);
    if (waitKey(30) >=0)
    {
        cout << "End of Stream";
        break;
    }
}

I know it isn't complete. 我知道它不完整。 I'm trying to find a way to take a frame of the video and send it to frame , manipulate it using cvtColor , then output it back to grayscale so I can display it on my screen. 我正在尝试找到一种方法来拍摄视频帧并将其发送到 ,使用cvtColor进行操作,然后将其输出回灰度,以便我可以在屏幕上显示它。

If anyone could help, it would be much appreciated. 如果有人可以提供帮助,我们将不胜感激。

Please see this example, here the complete code exists, hope this will work for you: 请看这个例子,这里有完整的代码,希望这对你有用:

#include "opencv2/highgui/highgui.hpp"
#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, char* argv[])
{
    VideoCapture cap(0); // open the video camera no. 0

    if (!cap.isOpened())  // if not success, exit program
    {
        cout << "Cannot open the video cam" << endl;
        return -1;
    }


    namedWindow("MyVideo",CV_WINDOW_AUTOSIZE);

    while (1)
    {
        Mat frame;

        bool bSuccess = cap.read(frame); // read a new frame from video

         if (!bSuccess)
        {
             cout << "Cannot read a frame from video stream" << endl;
             break;
        }

        Mat grayscale;
        cvtColor(frame, grayscale, CV_RGB2GRAY); 

        imshow("MyVideo", grayscale); 

        if (waitKey(30) == 27) 
       {
            cout << "esc key is pressed by user" << endl;
            break; 
       }
    }
    return 0;

}

You just initialized the variable "frame" and forgot to assign an image to it. 您刚刚初始化变量“frame”并忘记为其分配图像。 Since the variable "frame" is empty you won't get output. 由于变量“frame”为空,因此无法获得输出。 Grab a image and copy to frame from the video sequence "cap". 从视频序列“cap”中抓取图像并复制到帧。 This piece of code will do the job for you. 这段代码将为您完成这项工作。

    Mat frame;
    bool bSuccess = cap.read(frame); // read a frame from the video
    if (!bSuccess)
    {
         cout << "Cannot read a frame from video stream" << endl;
         break;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM