0

I tried to convert RGB image into grayscale, conversion is successfull and i can display it with imshow. Yet, i cannot write it with imwrite, imwrite function returns NULL. My original image is 1920*1080 JPEG file with UINT8. 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?

3
  • 1
    The return type of cv:imwrite is bool. Commented Mar 9, 2014 at 20:22
  • Are you on windows? I noticed you used backslashes for the #include paths, but forward slashes for the image path you are writing. Commented Mar 9, 2014 at 20:22
  • Thanks @VaughnCato I need to be more careful :) Commented Mar 9, 2014 at 20:26

1 Answer 1

2

The #include directive supports forward slashes. Use forward slashes there, for portability. And for sanity.

File handling functions generally don't support forward slashes in 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).

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 …

  • 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, as you said it is related with backslash and automatic folder creation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.