Serob_b
Serob_b

Reputation: 1059

How to check if python cv2.imwrite worked properly

I would like to check if cv2.imwrite executed properly and my file was saved. I tried to use exception handling with try-except, but if, for example, there is no folder named foo/ in any case it would be printed: "Image written"

try:
    cv2.imwrite("foo/img.jpg", myImage)
    print("Image written")
except:
    print("Problem")

P.S. Checking after saving is not an option, because the file could be overwritten.

Upvotes: 11

Views: 7309

Answers (2)

Kishore Konakanti
Kishore Konakanti

Reputation: 31

if cv2.imwrite(<path>, image_data):
     print('Image write succeeded')
else:
     print('Image write failed')

Single line (For fancy coders):

print('Image write:',"Succedded" if cv2.imwrite(<path>, image_data) else "Failed")

Both of them works as of Python v3.7

Upvotes: 2

paisanco
paisanco

Reputation: 4154

Python cv2.imwrite() has a return value, True if the write succeeded, False if it failed.

So do something like

writeStatus = cv2.imwrite("foo/img.jpg", myImage)
if writeStatus is True:
    print("image written")
else:
    print("problem") # or raise exception, handle problem, etc.

Upvotes: 12

Related Questions