i made python code to convert jpg into webp
from PIL import Image
import PIL
import os
import glob
# Open The Image:
image_path = "D:/..../image_name.jpg"
image = Image.open(image_path)
# Convert the image to RGB Colour:
image = image.convert('RGB')
# Save The Image as webp:
new_image_path = "D:/.../converted_image_name.webp"
image.save(new_image_path, 'webp')
#open converted image for inspection
new_image = Image.open(new_image_path)
new_image.show()
Don't know how to build a function that does the conversion for all files in folder, keeping the orginial file_names.
Here is a working solution to your problem:
from pathlib import Path
from PIL import Image
import PIL
import os
import glob
# the path to the directory containing the images
directory_path = 'D:\PATH'
def convert_images(directory_path):
for image_path in os.listdir(directory_path):
if image_path.endswith(".jpg"):
image = Image.open(os.path.join(directory_path, image_path))
# get image filename without an extension
name = Path(image_path).stem
rgb_image = image.convert('RGB')
new_image_path = f"{name}.webp"
rgb_image.save(os.path.join(directory_path, new_image_path), 'webp')
new_image = Image.open(new_image_path)
new_image.show()
continue
else:
continue
convert_images(directory_path)
final code
from pathlib import Path
from PIL import Image
import PIL
import os
import glob
# the path to the directory containing the images
directory_path = 'D:/Lokale schijf/SS2023/Python_API_imports/'
def convert_images(directory_path):
for image_path in os.listdir(directory_path):
if image_path.endswith(".jpg"):
image = Image.open(os.path.join(directory_path, image_path))
# get image filename without an extension
name = Path(image_path).stem
rgb_image = image.convert('RGB')
new_image_path = f"{name}.webp"
rgb_image.save(os.path.join(directory_path, new_image_path), 'webp')
new_image = Image.open(new_image_path)
new_image.show()
continue
convert_images(directory_path)
Related
I have a python script to procces jpeg on a folder and overwrite the names after done
from PIL import Image, ImageOps, JpegImagePlugin, ImageEnhance
#import jpegs from Repaired folder
im = Image.open('photo_2022-06-09_19-58-19.JPG')
# Crop
im = ImageOps.crop(im, border=17)
# Constract
im = ImageOps.autocontrast(im, cutoff = 1)
#sharpness
enhancer = ImageEnhance.Sharpness(im).enhance(3)
im = ImageOps.posterize(im, bits=8)
#color
enhancer = ImageEnhance.Color(im).enhance(3)
#save all jpegs and overwrite original file names
im.save("photo_2022-06-09_19-58-19.JPG", quality="maximum")
How can i process all jpeg files in that dir have a folder "repaired" and Overwrite the name of each processed file with the original file name?
I would use glob and do something like this:
import glob
from PIL import Image, ImageOps, JpegImagePlugin, ImageEnhance
for fname in glob.glob('./repaired/*.JPG'):
im = Image.open(fname)
im = ImageOps.crop(im, border=17)
im = ImageOps.autocontrast(im, cutoff = 1)
enhancer = ImageEnhance.Sharpness(im).enhance(3)
im = ImageOps.posterize(im, bits=8)
enhancer = ImageEnhance.Color(im).enhance(3)
im.save(fname, quality="maximum")
You can print fname to see what it looks like, and process that string if you need to get the filename out, e.g. to write the file into a different folder.
So it should be like this
import os
from PIL import Image, ImageOps, JpegImagePlugin, ImageEnhance
#import jpegs from Repaired folder
for filename in os.listdir():
if filename.endswith(".jpg"):
im = Image.open(filename)
# Crop
im = ImageOps.crop(im, border=17)
# Constract
im = ImageOps.autocontrast(im, cutoff = 1)
#sharpness
enhancer = ImageEnhance.Sharpness(im).enhance(3)
im = ImageOps.posterize(im, bits=8)
#color
enhancer = ImageEnhance.Color(im).enhance(3)
#save all jpegs and overwrite original file names
im.save(filename, quality="maximum")
else:
continue
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?
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)
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)
In a part of my project for creating a dataset, I have a text file containing a list of a bunch of latex equations . Now I want to convert them into images through python in diffrent font sizes. But i dont know how to do it. Please help.
This is the list of latex symbols I am using:- https://docs.mathpix.com/#vocabulary
#
import shutil
import os
from pdflatex import PDFLaTeX
from pdf2image import convert_from_path
from PIL import Image
def crop(file):
img = Image.open(file)
area = (300,300, 800, 800)
cropped_img = img.crop(area)
cropped_img.save(file)
def save_images(images_names,pdf_path,images_path=""):
# Store Pdf with convert_from_path function
images = convert_from_path(pdf_path)
if len(images_names)==0:
print("names is empty")
return
i=0
for img in images:
img.save(images_path+"/"+images_names[i]+".jpg", 'JPEG')
crop(images_path+"/"+images_names[i]+".jpg")
i+=1
print("Successfully converted")
def create_image_from_latex(image_name,latex):
if "rough" not in os.listdir():
os.mkdir("rough")
if "images_from_latex" not in os.listdir():
os.mkdir("images_from_latex")
f=open("rough/a.tex","w+")
f.write("\\documentclass{article}\n\\usepackage{chemfig}\n\\begin{document}\n")
f.write(latex+"\n")
f.write(r"\end{document}")
f.close()
#print(os.getcwd()+"/a.tex")
#tex="/a.tex"
pdfl = PDFLaTeX.from_texfile('rough/a.tex')
pdf, log, completed_process = pdfl.create_pdf(keep_pdf_file=True, keep_log_file=False)
f=open("rough/a.pdf","wb")
f.write(pdf)
f.close()
save_images([image_name],"a.pdf","images_from_latex")
os.remove("rough/a.pdf")
shutil.rmtree("rough")
#create_image_from_latex("new_image",lat)
def create_images_from_text_file_with_latexes(text_file):
with open(text_file) as f:
latexes=f.readlines()
ind=1
for lat in latexes:
create_image_from_latex("%0.3d_"%ind,lat)
ind+=1
#
I am trying to convert high resolution images to something more manageable for machine learning. Currently I have the code to resize the images to what ever height and width I want however I have to do one image at a time which isn't bad when I'm only doing a 12-24 images but soon I want to scale up to do a few hundred images.
I am trying to read in a directory rather than individual images and save the new images in a new directory. Initial images will vary from .jpg, .png, .tif, etc. but I would like to make all the output images as .png like I have in my code.
import os
from PIL import Image
filename = "filename.jpg"
size = 250, 250
file_parts = os.path.splitext(filename)
outfile = file_parts[0] + '_250x250' + file_parts[1]
try:
img = Image.open(filename)
img = img.resize(size, Image.ANTIALIAS)
img.save(outfile, 'PNG')
except IOError as e:
print("An exception occured '%s'" %e)
Any help with this problem is appreciated.
Assuming the solution you are looking for is to handle multiple images at the same time - here is a solution. See here for more info.
from multiprocessing import Pool
def handle_image(image_file):
print(image_file)
#TODO implement the image manipulation here
if __name__ == '__main__':
p = Pool(5) # 5 as an example
# assuming you know how to prepare image file list
print(p.map(handle_image, ['a.jpg', 'b.jpg', 'c.png']))
You can use this:
#!/usr/bin/python
from PIL import Image
import os, sys
path = "\\path\\to\\files\\"
dirs = os.listdir( path )
def resize():
for item in dirs:
if os.path.isfile(path+item):
im = Image.open(path+item)
f, e = os.path.splitext(path+item)
imResize = im.resize((200,100), Image.ANTIALIAS)
imResize.save(f+'.png', 'png', quality=80)
resize()
You can loop over the contents of a directory with
import os
for root, subdirs, files in os.walk(MY_DIRECTORY):
for f in files:
if f.endswith('png'):
#do something
You can run through all the images inside the directory using glob. And then resize the images with opencv as follows or as you have done with PIL.
import glob
import cv2
import numpy as np
IMG_DIR='home/xx/imgs'
def read_images(directory):
for img in glob.glob(directory+"/*.png"):
image = cv2.imread(img)
resized_img = cv2.resize(image/255.0 , (250 , 250))
yield resized_img
resized_imgs = np.array(list(read_images(IMG_DIR)))
I used:
from PIL import Image
import os, sys
path = os.path.dirname(os.path.abspath(__file__))
dirs = os.listdir( path )
final_size = 244
print(dirs)
def resize_aspect_fit():
for item in dirs:
if ".PNG" in item:
print(item)
im = Image.open(path+"\\"+item)
f, e = os.path.splitext(path+"\\"+item)
size = im.size
print(size)
ratio = float(final_size) / max(size)
new_image_size = tuple([int(x*ratio) for x in size])
im = im.resize(new_image_size, Image.ANTIALIAS)
new_im = Image.new("RGB", (final_size, final_size))
new_im.paste(im, ((final_size-new_image_size[0])//2, (final_size-new_image_size[1])//2))
print(f)
new_im.save(f + 'resized.jpg', 'JPEG', quality=400)# png
resize_aspect_fit()
You can use this code to resize multiple images and save them after conversion in the same folder for let's say dimensions of (200,200):
import os
from PIL import Image
f = r' ' #Enter the location of your Image Folder
new_d = 200
for file in os.listdir(f):
f_img = f+'/'+file
try:
img = Image.open(f_img)
img = img.resize((new_d, new_d))
img.save(f_img)
except IOError:
pass
you can try to use the PIL library to resize images in python
import PIL
import os
import os.path
from PIL import Image
path = r'your images path here'
for file in os.listdir(path):
f_img = path+"/"+file
img = Image.open(f_img)
img = img.resize((100, 100)) #(width, height)
img.save(f_img)
from PIL import Image
import os
images_dir_path=' '
def image_rescaling(path):
for img in os.listdir(path):
img_dir=os.path.join(path,img)
img = Image.open(img_dir)
img = img.resize((224, 224))
img.save(img_dir)
image_rescaling(images_dir_path)
import glob
import cv2
import os
import numpy as np
from PIL import Image
images=[]
images=np.array(images)
path='C:\Users\Quantum\Desktop\test'
count=0
images = [cv2.imread(file,0) for file in glob.glob("E:\homework\Computer vision\Faces\*.jpg")]
for i in range(len(images)):
# im = Image.fromarray(images[i])
# cv2.imwrite(str(path) + '.jpg', images[count])
cv2.imwrite(os.path.join(path, 'pic.jpg'), images[count])
count+=1
Trying to select all the images from a folder and the images are getting selected and are converted to grayscale although I dont know how to write those images to a specific folder.Kindly help
#multiple image conversions
import cv2
import os,glob
from os import listdir,makedirs
from os.path import isfile,join
path = '/root/Desktop/Anil' # Source Folder
dstpath = '/root/Desktop/Anil2' # Destination Folder
try:
makedirs(dstpath)
except:
print ("Directory already exist, images will be written in same folder")
# Folder won't used
files = list(filter(lambda f: isfile(join(path,f)), listdir(path)))
for image in files:
try:
img = cv2.imread(os.path.join(path,image))
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
dstPath = join(dstpath,image)
cv2.imwrite(dstPath,gray)
except:
print ("{} is not converted".format(image))
for fil in glob.glob("*.jpg"):
try:
image = cv2.imread(fil)
gray_image = cv2.cvtColor(os.path.join(path,image), cv2.COLOR_BGR2GRAY) # convert to greyscale
cv2.imwrite(os.path.join(dstpath,fil),gray_image)
except:
print('{} is not converted')
import cv2
import glob, os, errno
# Replace mydir with the directory you want
mydir = r'C:\Users\Quantum\Desktop\testoutput'
#check if directory exist, if not create it
try:
os.makedirs(mydir)
except OSError as e:
if e.errno == errno.EEXIST:
raise
for fil in glob.glob("*.jpg"):
image = cv2.imread(fil)
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # convert to greyscale
cv2.imwrite(os.path.join(mydir,fil),gray_image) # write to location with same name
import os,cv2
path = r'C:\Users\me\Desktop\folder' # Source Folder
dstpath = r'C:\Users\me\Desktop\desfolder' # Destination Folder
try:
makedirs(dstpath)
except:
print ("Directory already exist, images will be written in asme folder")
# Folder won't used
files = os.listdir(path)
for image in files:
img = cv2.imread(os.path.join(path,image))
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.imwrite(os.path.join(dstpath,image),gray)
import cv2
from os import listdir,makedirs
from os.path import isfile,join
path = r'C:\Users\fakabbir.amin\Desktop\pdfop' # Source Folder
dstpath = r'C:\Users\fakabbir.amin\Desktop\testfolder' # Destination Folder
try:
makedirs(dstpath)
except:
print ("Directory already exist, images will be written in asme folder")
# Folder won't used
files = [f for f in listdir(path) if isfile(join(path,f))]
for image in files:
try:
img = cv2.imread(os.path.join(path,image))
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
dstPath = join(dstpath,image)
cv2.imwrite(dstPath,gray)
except:
print ("{} is not converted".format(image))
This code snippet will take all the images from path and write into another folder mentioned in dstpath.