将相机帧转换为灰度图像和显示

时间:2014-02-19 20:09:43

标签: opencv image-processing

实际上我是opencv上的新手,我试图将从相机捕获的帧转换为灰度级并将这些灰度帧显示出来....这里是我的代码 编译我的代码时,它会生成异常

  
    

FYP.exe中0x75942EEC的第一次机会异常:Microsoft C ++异常:cv ::内存位置0x00C0FAA0的异常。     如果存在此异常的处理程序,则可以安全地继续该程序。

  
#include <opencv\highgui.h>
#include <opencv\cv.h>
#include <opencv\cxcore.h>
#include <opencv\ml.h>
#include <opencv\cvaux.h>
#include <opencv\cvwimage.h>

using namespace cv;
using namespace std;
Mat gray_serial(Mat img){
    int rows = img.rows;
    int cols = img.cols;
    Mat gray(rows, cols, CV_8UC1);
    for (int r = 0; r<rows; r++){
        for (int c = 0; c<cols; c++){
            Vec3b bgr = img.at<Vec3b>(r, c);
            double gray_val = 0.144*bgr.val[0] + 0.587*bgr.val[1] + 0.299*bgr.val[2];
            gray.at<unsigned char>(r, c) = (unsigned char)gray_val;
        }
    }
    return gray;
}
void main(int argc, char *argv[])
{
    int c;
    Mat color_img;
    CvCapture* cv_cap = cvCaptureFromCAM(0);
    cvNamedWindow("Video", 1); // create window
    for (;;) {
        color_img = cvQueryFrame(cv_cap); // get frame
        imshow("Video", color_img);
        //cvShowImage("Video", color_img); // show frame
        imshow("img", gray_serial(color_img));
        /*{
            int rows = color_img.rows;
            int cols = color_img.cols;
            Mat gray(rows, cols, CV_8UC1);
            for (int r = 0; r<rows; r++){
                for (int c = 0; c<cols; c++){
                    Vec3b bgr = img.at<Vec3b>(r, c);
                    double gray_val = 0.144*bgr.val[0] + 0.587*bgr.val[1] + 0.299*bgr.val[2];
                    gray.at<unsigned char>(r, c) = (unsigned char)gray_val;
                }
            }
        }*/
        c = cvWaitKey(10); // wait 10 ms or for key stroke

        if (c == 27)
            break; // if ESC, break and quit
    }
    /* clean up */
    cvReleaseCapture(&cv_cap);
    cvDestroyWindow("Video");
}

1 个答案:

答案 0 :(得分:0)

尝试替换此块:

            for (int r = 0; r<rows; r++){
                for (int c = 0; c<cols; c++){
                    Vec3b bgr = img.at<Vec3b>(r, c);
                    double gray_val = 0.144*bgr.val[0] + 0.587*bgr.val[1] + 0.299*bgr.val[2];
                    gray.at<unsigned char>(r, c) = (unsigned char)gray_val;
                }

通过这一功能

cvtColor(color_img,gray,CV_RGB2GRAY);
相关问题