简体   繁体   English

无法在OpenCV中使用imwrite编写灰度图像

[英]Unable to write Grayscale image with imwrite in OpenCV

I tried to convert RGB image into grayscale, conversion is successfull and i can display it with imshow. 我试图将RGB图像转换为灰度,转换成功,我可以用imshow显示它。 Yet, i cannot write it with imwrite, imwrite function returns NULL. 然而,我不能用imwrite写它,imwrite函数返回NULL。 My original image is 1920*1080 JPEG file with UINT8. 我的原始图像是带有UINT8的1920 * 1080 JPEG文件。 Here is the code 这是代码

#include <opencv\cv.h>
#include <opencv\highgui.h>

using namespace cv;

int main(int argc, char** argv)
{
char* imageName = argv[1];

Mat image;
image = imread(imageName, 1);

if (argc != 2 || !image.data)
{
    printf(" No image data \n ");
    return -1;
}

Mat gray_image;
cvtColor(image, gray_image, CV_BGR2GRAY);

if (imwrite("../../images/Gray_Image.jpg", gray_image) ==NULL) {
    printf( "Writing image is not successfull!");       
}

namedWindow(imageName, CV_WINDOW_AUTOSIZE);
namedWindow("Gray image", CV_WINDOW_AUTOSIZE);

imshow(imageName, image);
imshow("Gray image", gray_image);

waitKey(0);
return 0;
}

Why imwrite returns NULL? 为什么imwrite返回NULL?

The #include directive supports forward slashes. #include指令支持正斜杠。 Use forward slashes there, for portability. 在那里使用正斜杠,以便携带。 And for sanity. 为了理智。

File handling functions generally don't support forward slashes in Windows. 文件处理函数通常不支持Windows中的正斜杠。 Use backward slashes there. 在那里使用反斜杠。 Or, better, use some path handling class (such classes often support forward slashes, since they need to be portable, and automatically convert to backward slash in Windows). 或者,更好的是,使用一些路径处理类(这类通常支持正斜杠,因为它们需要是可移植的,并且在Windows中自动转换为反斜杠)。

In short, 简而言之,

  • /\\ to fix the immediate problem. /\\来解决眼前的问题。

That said, the OpenCV imwrite probably does not support automatic folder creation, so you'd better make sure that … 也就是说,OpenCV imwrite可能不支持自动创建文件夹,所以你最好确保......

  • the specified folder exists, and 指定的文件夹存在,和

  • for a relative path (as you have), that the program execution's current folder is where you imagined the relative path starting. 对于相对路径(如您所知),程序执行的当前文件夹是您想象的相对路径的起始位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM