I have written a code in python opencv. I am trying to write the processed image back to disk but the image is not getting saved and it is not showing any error(runtime and comp
If you want to have the paths in your code portable, look into pathlib.
https://docs.python.org/3/library/pathlib.html
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.
As Jean suggested, the error is due to the \ being interpretted as an escape sequence. It is hence always safer to use os.path.join()
as it is more cross platform and you need not worry about the escape sequence problem. For instance, in your case, you further need not worry about the first few arguments, as that is your home directory
import os
cv2.imwrite(os.path.join(os.path.expanduser('~'),'Desktop','tropical_image_sig5.bmp'), img2)
os.path.expanduser('~')
will directly return your home directory.