i can not images using cv2.imwrite () method - python

I want to copy all the pictures from one folder to another folder. I tried to run this code again and again but it returns me False only instead of saving pictures to other folder.
import cv2
import glob
input_path = 'C:\\Users\\Kazmi-PC\\OneDrive\\Pictures\\1\\*.*'
output_path = 'C:\\Users\\Kazmi-PC\\OneDrive\\Pictures\\2\\*.jpg'
for file in glob.glob(input_path):
print("printing.....")
print(file)
a= cv2.imread(file)
cv2.imwrite(output_path, a)

You can't use * in output filename. You would have to use imwrite inside for loop and use unique filenames in output.
You can use shutil.copy(file, directory) to copy. So you can use output without *.jpg and you don't have to add filename in output.
But you still need to copy every file separatelly.
import glob
import shutil
input_path = 'C:\\Users\\Kazmi-PC\\OneDrive\\Pictures\\1\\*.*'
output_dir = 'C:\\Users\\Kazmi-PC\\OneDrive\\Pictures\\2\\'
for file in glob.glob(input_path):
shutil.copy(file, output_dir)

Related

how can i keep an image name when changing its extention

how can i get the file name without its root and path. only a name so i can save the images i want to convert with the same original name?
import sys
import os,glob
from PIL import Image, ImageFilter
path = os.getcwd()
if not os.path.exists('converted'):
save_to = os.makedirs('converted')
for i in glob.glob(f'{path}/*.jpg'):
img = Image.open(i)
img.save(???????) ######## <---------?????????
#i want to save the imege whith its original name,
# but with a different extention, and i want to save it to a different folder then cwd
Use os.path.basename to get filename without path.
Use os.path.splitext to split filename into stem and suffix.
Did you wanted something like this?
for i in glob.glob(f'{path}/*.png'):
img = Image.open(i)
basename = os.path.basename(i)
root_ext = os.path.splitext(basename)[0]
ext = ".png"
img.save(path+"/converted/" + root_ext + ext)

Converting all files (.jpg to .png) from a directory in Python

I'm trying to convert all files from a directory from .jpg to .png. The name should remain the same, just the format would change.
I've been doing some researches and came to this:
from PIL import Image
import os
directory = r'D:\PATH'
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
im = Image.open(filename)
im.save('img11.png')
print(os.path.join(directory, filename))
continue
else:
continue
I was expecting the loop to go through all my .jpg files and convert them to .png files. So far I was doing only with 1 name: 'img11.png', I haven't succed to build something able to write the adequate names.
The print(os.path.join(directory, filename)) works, it prints all my files but concerning the converting part, it only works for 1 file.
Do you guys have any idea for helping me going through the process?
You can convert the opened image as RGB and then you can save it in any format.
You can try the following code :
from PIL import Image
import os
directory = r'D:\PATH'
c=1
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
im = Image.open(filename)
name='img'+str(c)+'.png'
rgb_im = im.convert('RGB')
rgb_im.save(name)
c+=1
print(os.path.join(directory, filename))
continue
else:
continue
You're explicitly saving every file as img11.png.
You should get the name of your jpg file and then use that to name and save the png file.
name = filename[:-4]
im.save(name + '.png')
I would have used os.rename() function like below.
import os
directory = r'D:\PATH'
for filename in os.listdir(directory):
prefix = filename.split(".jpg")[0]
os.rename(filename, prefix+".png")
Please let me know if this is what you wanted. Try the code with some copied images inside a test folder, before applying to the intended folder. All the best.
from PIL import Image
import os
directory = r'D:\PATH'
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
prefix = filename.split(".jpg")[0]
im = Image.open(filename)
im.save(prefix+'.png')
else:
continue
Please try this one and let me know.

Multiple directory make and specific file into there dirctory

I wrote a code to create multiple folders and specific files into those folders using python.
I have 1920 images and all those images are associated with 20 images files, named as frame01, frame02, frame03.... image96 (1 frame has a 20 image files).
How can i create a new folder and copy specific files into that created folders?
To create directory
if not os.path.exists(directory):
os.makedirs(directory)
To copy file
from shutil import copyfile
copyfile(src, dst)
Just create a loop to copy check and create dir and then as per your condition copy the file using copyfile.
What error you are getting in your code ?
To select and copy files based on the first few characters of the filename, (such as 'frame' or 'image'), see below:
import os
import shutil
exist_dir = 'exist/dir'
new_dir = 'new/dir'
for (dirpath, dirnames, filenames) in os.walk(os.path.join(exist_dir+os.sep)):
for filename in filenames:
if filename.startswith('frame') or filename.startswith('image'):
folderandfile = os.sep.join([dirpath, filename])
folderandfilenew = os.sep.join([new_dir, filename])
shutil.copy2(folderandfile, folderandfile1)

Python getting full path to working zip file

I have a zipfile object:
docx_zip = zipfile.ZipFile(path)
I want to access the full path of that zip file in order to pass that path to ImageTk Image object, so I need the path to that file.
image = Image.open(PATH_TO_IMAGE)
photo = ImageTk.PhotoImage(image)
So I ask: How can I get PATH_TO_IMAGE ?
One method optional is to extract it to the current working directory and give it the new path (the file name), but I was wondering if there is an option to get the full path straight from the zip archive.
Can you try
import os.path
docx_zip = zipfile.ZipFile(path)
print os.path.dirname(path)
I don't think that zipfile allows for this. At least I can't find anything in the docs, but there is a workaround. You can create a ZipInfo object from your ZipFile, which will hold the information you want:
import zipfile
import os
docx_zip = zipfile.ZipFile(zip_path)
docx_info = docx_zip.getinfo(name_of_image_in_zip)
path_to_image = os.path.abspath(docx_info.filename)
# or get all paths:
docx_name_list = docx_zip.infolist()
paths_to_images = [os.path.abspath(x.filename) for x in docx_name_list]
I hope this helps.

Loading multiple images from a text file

I have got 40 images,and I have written their names in a text file. Now I want to call those images one by one in my program,using that text file (in Python).
I have used glob to find all image names,(instead of text file).
glob list contains of names like that:
img=['image0.jpg','image1.jpg',....]
Now If I access any image like img[0],img[1] it is just image0.jpg not 'image0.jpg',
so I have got trouble loading using opencv function to load it.
I want to load it like
cv.LoadImage('image0.jpg')
If your file contains the fully-qualified names of the files. You can do the following
import cv
with open('textFileOfImages.txt','rb') as f:
img = [line.strip() for line in f]
#load the images at you leisure
for image in img:
loadedImage = cv.LoadImage(image)
#manipulate image
If your file contains the relative path from the current working directory then:
import os
import cv
with open('textFileOfImages.txt','rb') as f:
img = ['%s/%s'%(os.getcwd(),line.strip()) for line in f]
Or if your file contains the relative path from directory the current script is running
import os
import cv
with open('textFileOfImages.txt','rb') as f:
img = ['%s/%s'%(os.path.dirname(os.path.abspath(__file__)),line.strip()) for line in f]
Edit
If you need to load image names from multiple files you can easily incorporate this.
Assuming you have the list of file names, then the easiest way is to loop outside the with statement.
listOfFilenames = ['filename1.txt','filename2.txt','filename3.txt']
for filename in listOfFilenames:
with open(filename,'rb') as f:
...
Try using
for _file in img:
cv.LoadImage("{0}".format(_file))
if your file is in other directory,
import os
for _file in img:
cv.LoadImage("{0}".format(os.path.join(directory, _file)))

Categories

Resources