Reputation: 877
I'm trying to save an image with the same name after editing on opencv. I can save with the same name. But I can't save in different file. So, this is my code:
import cv2
import numpy as np
import glob
filename = [img for img in glob.glob("./mypath_1/*.jpg")]
flist=sorted(filename)
images = []
path='./mypath_2/'
for image in flist:
img= cv2.imread(image)
alpha=2
beta=-420
img2=cv2.addWeighted(img,alpha,np.zeros(img.shape,img.dtype),0,beta)
hsv = cv2.cvtColor(img2, cv2.COLOR_BGR2HSV)
cv2.imwrite( path+image, hsv)
Additionally, I tried this: cv2.imwrite( './mypath_2/'+image, hsv)
.
I do not save the image and I do not have a message error in this code.
Some suggestion?
Upvotes: 3
Views: 2076
Reputation: 331
You can do it using 3 lines of code using nipath
import ntpath
filename = ntpath.basename("D:\coding\python\Sample Photos\1.jpg")
cv2.imwrite("D:\coding\python\Sample Photos\"+filename, img)
Upvotes: 1
Reputation: 424
import numpy as np
import cv2
import os
import sys
from pathlib import Path
if __name__ == "__main__":
#get alpha and beta values
alpha, beta =2, -420
# get directory path where the images are stored
image_dir = "/path/to/image read directory/"
# get directory path where you want to save the images
output_dir = "/path/to/image write directory/"
#iterate through all the files in the image directory
for _, _, image_names in os.walk(image_dir):
#iterate through all the files in the image_dir
for image_name in image_names:
# check for extension .jpg
if '.jpg' in image_name:
# get image read path(path should not contain spaces in them)
filepath = os.path.join(image_dir, image_name)
# get image write path
dstpath = os.path.join(output_dir, image_name)
print(filepath, dstpath)
# read the image
image = cv2.imread(filepath)
# do your processing
image2 = cv2.addWeighted(image, alpha,np.zeros_like(image),0,beta)
hsv = cv2.cvtColor(image2, cv2.COLOR_BGR2HSV)
# write the image in a different path with the same name
cv2.imwrite(dstpath, hsv)
print(image.shape, image2.shape, hsv.shape)
Upvotes: 2