开始一直运行不正确,发现和标准代码有出入。发现是使用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() == 0does 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;
}

本文档指出在OpenCV代码中,使用`img.empty()==0`来检查图像是否加载成功是错误的。正确的做法是直接使用`img.empty()`。示例代码展示了如何正确读取和显示图像,以及在图像无法加载时的错误处理。通过修正这一错误,可以确保程序正确运行并避免因空指针导致的问题。
741





