openvimwrite path problem

Asked 2 years ago, Updated 2 years ago, 70 views

i = 2 #int
cv2.imwrite([r'C:\Users\Desktop\result (' + str(i) + ').png'], result) #result is 2D 16bit image

'result (2).I want to save the image under the name 'png'.

I'm going to put the imwrite in the for statement because i is caught in the for statement.

However, the above code causes an error when executing.

I'm asking for your help.

cv2.imwrite(r'C:\Users\Desktop\result (' + str(i) + ').png', result)

You can't even try it.

python opencv

2022-09-22 08:12

1 Answers

There are no error-related messages, so it is not known exactly, but the error may be due to the separator character.

You should use the path separator character in the form c:/ instead of c:\.

However, pathlib modules are provided from Python 3.4.

It is easy to find out the absolute path after reading it as a relative path.

from pathlib import Path

file_path = Path('sample.png')

file_path.absolute().as_uri()
Out[15]: 'file:///C:/Users/Administrator/aaaa/sample.png'

If you specify a path with an invalid character, it will correct itself.

from pathlib import Path

file_path = Path('d:\sample.png')

file_path.absolute().as_uri()
Out[17]: 'file:///d:/sample.png'

Also, string interpolation in Python is very convenient. If you use f'' and put a variable or formula between {} as shown below, it will be substituted as it is. You don't need to paste strings one by one by one.

for i in range(10):
    print(f'c:/{i * 2}.jpg')

c:/0.jpg
c:/2.jpg
c:/4.jpg
c:/6.jpg
c:/8.jpg
c:/10.jpg
c:/12.jpg
c:/14.jpg
c:/16.jpg
c:/18.jpg


2022-09-22 08:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.