Ipython cv2.imwrite() not saving image

前端 未结 3 1808
自闭症患者
自闭症患者 2021-02-05 17:16

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

3条回答
  •  温柔的废话
    2021-02-05 17:54

    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\Desktopropical_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.

提交回复
热议问题