Ipython cv2.imwrite() not saving image

As a general and absolute rule, you have to protect your windows path strings (containing backslashes) with r prefix or some characters are interpreted (ex: \n,\b,\v,\x aaaaand \t, full list here):

so when doing this:

cv2.imwrite('C:\Users\Niladri\Desktop\tropical_image_sig5.bmp', img2)

you’re trying to save to C:\Users\Niladri\Desktop<TAB>ropical_image_sig5.bmp

And the annoying thing with imread and imwrite is that those functions don’t throw exceptions on errors, but fail silently. imwrite returns False

>>> cv2.imread("D:/nonexisting.jpg")  # this returns None, no error
>>> s = cv2.imread("D:/sloth_book.jpg")  # this works
>>> s
array([[[250, 250, 250],
        [246, 246, 246],
        [255, 255, 255],
        ...,
>>> cv2.imwrite("inexistent_dir/file.jpg",s)  # dir doesn't exist, write fails
False

So you have to check return value of those functions.

Do this:

if not cv2.imwrite(r'C:\Users\Niladri\Desktop\tropical_image_sig5.bmp', img2):
     raise Exception("Could not write image")

Note: the read works fine because “escaped” uppercase letters have no particular meaning in python 2 (\U and \N have a meaning in python 3 so it wouldn’t have worked)

And if there’s an error, the program now complains loudly.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)