1

I am working on a code to save an image. Instead of saving image cv2.imwrite function is returning false. I have reproduced the problem in the below code:

Uni_ID = 123
cam=cv2.VideoCapture(0)
rett, img = cam.read()

now = datetime.now()
dtString =  now.strftime('%d-%m-%Y')
timeString = now.strftime('%H:%M:%S')
path = 'IMG'
name = path + '/' + dtString
#     print(name)
if not os.path.exists(name):
    os.makedirs(name)
imgName = name + '/'+ str(Uni_ID) + '_' + timeString + '.jpg'
print(imgName)
cv2.imwrite(imgName, img)

Instead of saving image, the cv2.imwrite function on the last line is returning false. The output of the code is :

IMG/03-09-2020/123_17:59:58.jpg
False
1
  • I guess you are using windows, that's why you get the problem since filenames with ':' are not considered. Instead you can use / or -, just change the now.strftime('%H-%M-%S') Commented Sep 3, 2020 at 14:00

1 Answer 1

5

You can't use : in file name.

>>> cv2.imwrite(r'123_17:59:58.jpg', np.array(i))
False
>>> cv2.imwrite(r'123_17_59_58.jpg', np.array(i))
True

If you're not sure whether a filename would be valid or not - try opening it first.

>>> f = open(r'123_17:59:58.jpg', 'wt')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
OSError: [Errno 22] Invalid argument: '123_17:59:58.jpg'

>>> f = open(r'123_17_59_58.jpg', 'wt')
>>>
Sign up to request clarification or add additional context in comments.

7 Comments

Nope, cv2.imwrite(r'123_17:59:58.jpg', np.array(i)) is a perfectly valid command
Not in windows.
Ok, I didn't know that (I'm on Linux, it worked fine for me). But I think the true issue here are the slashes in the name
I agree on that. TBH I think cv2 need to raise error instead of returning False. That's not pythonic -
Agree that cv2 should throw more descriptive error. This same behavior in my case was caused by something totally different - the file name being too long.
|

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.