Question :
I’m learning OpenCV and Python. I captured some images from my webcam and saved them. But they are being saved by default into the local folder. I want to save them to another folder from direct path. How do I fix it?
Answer #1:
The solution provided by ebeneditos works perfectly.
But if you have cv2.imwrite()
in several sections of a large code snippet and you want to change the path where the images get saved, you will have to change the path at every occurrence of cv2.imwrite()
individually.
As Soltius stated, here is a better way. Declare a path and pass it as a string into cv2.imwrite()
import cv2
import os
img = cv2.imread('1.jpg', 1)
path = 'D:/OpenCV/Scripts/Images'
cv2.imwrite(os.path.join(path , 'waka.jpg'), img)
cv2.waitKey(0)
Now if you want to modify the path, you just have to change the path
variable.
Edited based on solution provided by Kallz
Answer #2:
You can do it with OpenCV’s function imwrite
:
import cv2
cv2.imwrite('Path/Image.jpg', image_name)
Answer #3:
Answer given by Jeru Luke is working only on Windows systems, if we try on another operating system (Ubuntu) then it runs without error but the image is saved on target location or path.
Not working in Ubuntu and working in Windows
import cv2
img = cv2.imread('1.jpg', 1)
path = '/tmp'
cv2.imwrite(str(path) + 'waka.jpg',img)
cv2.waitKey(0)
I run above code but the image does not save the image on target path. Then I found that the way of adding path is wrong for the general purpose we using OS module to add the path.
Example:
import os
final_path = os.path.join(path_1,path_2,path_3......)
working in Ubuntu and Windows
import cv2
import os
img = cv2.imread('1.jpg', 1)
path = 'D:/OpenCV/Scripts/Images'
cv2.imwrite(os.path.join(path , 'waka.jpg'),img)
cv2.waitKey(0)
that code works fine on both Windows and Ubuntu 🙂
Answer #4:
Thank you everyone. Your ways are perfect. I would like to share another way I used to fix the problem. I used the function os.chdir(path)
to change local directory to path. After which I saved image normally.
Answer #5:
You can use this simple code in loop by incrementing count
cv2.imwrite(“C:SharatPythonImagesframe%d.jpg” % count, image)
images will be saved in the folder by name line frame0.jpg, frame1.jpg frame2.jpg etc..
Answer #6:
FOR MAC USERS if you are working with open cv
import cv2
cv2.imwrite('path_to_folder/image.jpg',image)