繁体   English   中英

OpenCV imwrite无效

[英]OpenCV imwrite is not working

我有一个简单的OpenCV应用程序,它从网络摄像头获取视频流,当按下spacebar时,它会捕获当前图像并冻结该图像。 当我尝试使用cv::imwrite()方法将图片保存到磁盘时,它不起作用。 代码成功编译但不保存图像。 它也会从通话中返回错误值。 我不确定这是一个图像类型或其他类型的问题,但我似乎很难过。

这是我当前的cpp类的代码:

#include <iostream>

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

using namespace std;
using namespace cv;

Mat picture;
char key;

class FacialRec {

};

int main() {
    //Starting the video
    VideoCapture videoCapture(0);

    if (!videoCapture.isOpened()) {
        cout << "Unable to open video file." << endl;
        return 1;
    }

    namedWindow("Webcam", CV_WINDOW_AUTOSIZE);

    while(true) {
        Mat frame;
        videoCapture.retrieve(frame);
        bool success = videoCapture.read(frame);

        if (!success) {
            cout << "Could not read from video file" << endl;
            return 1;
        }

        imshow("Webcam", frame);
        key = waitKey(30);

        if (key == 27) { //escape key pressed: stop program
            cout << "ESC pressed. Program closing..." << endl;
            break;
        }else if (key == ' ') { //spacebar pressed: take a picture
            picture = frame;
            key = -1;

            while (true) {
                imshow("Webcam", picture);

                key = waitKey(30);

                if (key == 27 || key == 32) {
                    cout << "ESC or SPACE pressed. Returning to video..." << endl;
                    break;
                }

                if (key == 115) {
                    //trying to save to current directory
                    bool maybe = imwrite("/testimage.jpg", picture);
                    // maybe bool is always getting value of 0, or false
                   cout << "s was pressed. saving image " << maybe << endl;
                }   
            }
        }

    }

    return 0;
}

您正在尝试将testimage.jpg写入/目录。 执行程序可能没有足够的权限写入该目录。 根据您的评论,您可能想要

//trying to save to current directory
bool maybe = imwrite("./testimage.jpg", picture);

自从. 表示当前的工作目录。

OpenCV有时会出现写入.jpg图像的问题。 尝试将其更改为.png.bmp ,看看是否会对您的情况产生影响。

如果您在编写图像时遇到其他问题,可以在OpenCV调试它们,方法是添加以下几行代码来显示它们,看看它们是否有效:

// Create a window for display.
namedWindow( "Display window", WINDOW_AUTOSIZE );

// Show our image inside it.
imshow( "Display window", picture );                   

// Wait for a keystroke in the window
waitKey(0);                                         

一些建议。

  1. 尝试不同的文件格式。
  2. 您的IDE是否知道您的目标文件夹/主路径目录?
  3. 你的形象绝对有效吗? 当你imshow()时它会显示出来吗?

暂无
暂无

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

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