所以我链接了 OpenCV 的所有库,我添加了它工作所需的所有 .lib 和 .dll,但是当我尝试获取图片以显示它时,它说图片不存在。所有路径都是正确的,图像位于解决方案的主目录中,这是代码。
Mat color = imread("wall.jpg");
也尝试过:
D:\\wall.jpg
和D:\wall.jpg
D:/wall.jpg
和D://wall.jpg
#include<opencv2/opencv.hpp>
#include<opencv2/imgcodecs.hpp>
using namespace std;
using namespace cv;
int main()
{
Mat color = imread("wall.jpg");
if (color.empty())
{
cout << "image is empty" << endl;
system("pause");
exit(-1);
}
else
{
cout << "image is displayed" << endl;
imshow("window", color);
}
waitKey();
}
代码输出
image is empty 按任意键继续。 . .
它应该说
显示的图像
最佳答案
我的回答假设您使用的是 Windows,因为您在描述中使用了“解决方案”一词。
至少有一项是正确的:
- 您的路径不正确。如果您是从 visual studio 运行代码,则使用像
"wall.jpg"
这样的相对路径会使用工作目录,这不一定是解决方案目录。- 使用另一个机制来验证您的路径是否正确,例如在 Windows 上从命令行运行以下命令:
start D:\wall.jpg
。如果该命令返回找不到文件错误,则说明您的路径有误。
- 使用另一个机制来验证您的路径是否正确,例如在 Windows 上从命令行运行以下命令:
- 您正在使用不受支持的文件格式。
- 确保您可以打开并查看文件。
- 确保它是 JPEG、TIFF 或 PNG。扩展名可能不正确。如果您不确定,请尝试使用您知道属于这些类型之一的文件。
- 您没有读取该文件的权限。
- 打开文件并确认您可以查看它。如果可以,并且您的 opencv 进程以同一用户身份运行,您应该没问题。
来自imread docs :
Loads an image from a file.
The function
imread
loads an image from the specified file and returns it. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix (Mat::data==NULL
)....
On Microsoft Windows* OS and MacOSX*, the codecs shipped with an OpenCV image (libjpeg, libpng, libtiff, and libjasper) are used by default. So, OpenCV can always read JPEGs, PNGs, and TIFFs.
...
Note
- The function determines the type of an image by the content, not by the file extension.
命令行工作目录
如果从命令行运行,工作目录就是你所在的目录。如果你在你的操作系统上运行文件列表命令并且可以看到你的“wall.jpg”
图像,那么你在正确的地方。从这里使用类似 .\path\to\my\opencv-program.exe
的相对路径运行您的 OpenCV 可执行文件。
Visual Studio 调试工作目录
关于c++ - OpenCV 不会加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57684526/