如何使用OpenCV和C ++裁剪网络摄像头饲料框架

时间:2018-05-15 09:33:59

标签: opencv image-processing

我是OpenCV的初学者,我想自动裁剪网络摄像头,即通过指定矩形的值而不是使用鼠标手柄。我尝试了以下代码,但它显示的是黑屏,而不是网络摄像头。可能是什么原因?

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

using namespace std;
char key;
int main()
{
    cvNamedWindow("Camera_Output", 1);    //Create window

    CvCapture* capture = cvCaptureFromCAM(1);  //Capture using camera 1 connected to system
    cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_WIDTH, 640 );
    cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_HEIGHT, 480 );

    while(1){ //Create loop for live streaming

        IplImage* framein = cvQueryFrame(capture); //Create image frames from capture

        /* sets the Region of Interest  - rectangle area has to be __INSIDE__ the image */
        cvSetImageROI(framein, cvRect(0, 0, 320, 240));

        /* create destination image  - cvGetSize will return the width and the height of ROI */
        IplImage *frameout = cvCreateImage(cvGetSize(framein),  framein->depth, framein->nChannels);

        /* copy subimage */
        cvCopy(framein, frameout, NULL);

        /* always reset the Region of Interest */
        cvResetImageROI(framein);

        cvShowImage("Camera_Output", frameout);   //Show image frames on created window

        key = cvWaitKey(10);     //Capture Keyboard stroke
        if (char(key) == 27){
            break;      //ESC key loop will break.
        }
    }

    cvReleaseCapture(&capture); //Release capture.
    cvDestroyWindow("Camera_Output"); //Destroy Window
    return 0;
}

1 个答案:

答案 0 :(得分:2)

我不喜欢Open CV的C界面,所以我建议您通过Open CV 3.4.0的C ++界面提供一个可能的解决方案

#include <Windows.h>
#include <Vfw.h>
#include <string>
#include <iostream>
#include "opencv2\core\core.hpp"
#include "opencv2\imgproc\imgproc.hpp"
#include "opencv2\imgcodecs\imgcodecs.hpp"
#include "opencv2\highgui\highgui.hpp"

using namespace cv;
using namespace std;

int main()
{

    VideoCapture camera;
    camera.open(0);
    if (!camera.isOpened()) {
        cout << "Failed to open camera." << std::endl;
        return -1;
    }
    Mat frame, oMatCrop;

    while(1){ //Create loop for live streaming

        camera >> frame;
        oMatCrop=frame(cv::Rect(0,0,320,240));

        cv::namedWindow("Image",CV_WINDOW_FREERATIO);
        cv::imshow("Image", frame);

        cv::namedWindow("Cropped image",CV_WINDOW_FREERATIO);
        cv::imshow("Cropped image", oMatCrop);

        if (waitKey(50) == 27) {
            break;
        }
    }
    return 0;
}

我也放在结果下面

enter image description here