我有一个简单的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;
}
答案 0 :(得分:2)
您正在尝试将testimage.jpg
写入/
目录。执行程序可能没有足够的权限写入该目录。根据您的评论,您可能想要
//trying to save to current directory
bool maybe = imwrite("./testimage.jpg", picture);
由于.
表示当前工作目录。
答案 1 :(得分:1)
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);
答案 2 :(得分:0)
一些建议。