簡體   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