开始一直运行不正确,发现和标准代码有出入。发现是使用img.empty() == 0这个用法是错误的。
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/opencv.hpp>
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
// using namespace std;
using namespace cv;
int main()
{
std::string path = "basketBall.jpg";
Mat img = imread(path,IMREAD_COLOR);
// Mat img = imread("basketBall.jpg",IMREAD_COLOR);
if (img.empty())
{
std::cout << "打开图像失败!" <<std::endl;
return -1;
}
namedWindow("image", CV_WINDOW_AUTOSIZE);
cv::imshow("image", img);
waitKey();
return 0;
}
empty()函数提示
bool cv::Mat::empty() const
Returns true if the array has no elements. The method returns true if Mat::total() is 0 or if Mat::data is NULL. Because of pop_back() and resize() methodsM.total() == 0
does not imply thatM.data == NULL
.
官方给出的样例
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
using namespace cv;
int main()
{
std::string image_path = samples::findFile("basketBall.jpg");
Mat img = imread(image_path, IMREAD_COLOR);
if(img.empty())
{
std::cout << "Could not read the image: " << image_path << std::endl;
return 1;
}
imshow("Display window", img);
int k = waitKey(0); // Wait for a keystroke in the window
if(k == 's')
{
imwrite("starry_night.png", img);
}
return 0;
}