i'm trying to make something that returns a random image from a folder to eventually put together an outfit. the path is a specific folder, as each path is a different type of clothing article (i.e. a folder/path for pants would be /Users/xxx/Desktop/outfit_images/5pants)
def article(path):
files = os.listdir(path) # listdir gives you a list with all filenames in the provided path.
randomFile = random.choice(files) # random.choice then selects a random file from your list
image = Image.open(path + '/' + randomFile) # displayed the image
return image
i'm using the code above to have the specified clothing article file as the input, and then select a random image from that file. i however, get errors (.DS_Store selection error) every few attempts becuase of the hidden files on the mac '.', '..', and want to figure out how to avoid selecting these hidden files. i would prefer to use a method other than running the rm from the terminal. any help is greatly appreciated!
You can use glob for this:
import glob
import os
def article(path):
files = glob.glob(os.path.join(path, '*'))
randomFile = random.choice(files)
image = Image.open(path + '/' + randomFile)
return image
Related
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)
So I'm trying to use pillow to apply kernals to .jpg images in python and I'm trying to process an entire image set at once. I have a script here that will iterate through the training set, apply the edge finding filter, and save the result in a different folder. Whenever I try to do that using the .save command it throw an error telling me there is no such file as the one I'm saving it to. The thing is, I'm trying to create that file. It doesn't do this when I've got a definite file name, only when I'm trying to do it iterativly. Can anyone see what the problem here is?
import PIL
import os
from PIL import Image
from PIL import ImageFilter
from PIL.ImageFilter import (FIND_EDGES)
num = 1
path = "/home/<me>/Desktop/<my documents>/<my project>/Training Set Cars/"
dirs = os.listdir(path)
for filename in dirs:
print(filename)
im = Image.open(path + filename)
aString = str(num)
print("/home/<me>/Desktop/<my documents>/<my project>/Training Car Edges/%s.jpg" % aString)
ERROR HERE>>> im.filter(FIND_EDGES).save("/home/<me>/Desktop/<my documents>/<my project>/Training Car Edges/%s.jpg" % aString)
num += 1
Example of PDF: "Smith#00$Consolidated_Performance.pdf"
The goal is to add a bookmark to page 1 of each PDF based on the filename.
(Bookmark name in example would be "Consolidated Performance")
import os
from openpyxl import load_workbook
from PyPDF2 import PdfFileMerger
cdir = "Directory of PDF" # Current directory
pdfcdir = [filename for filename in os.listdir(cdir) if filename.endswith(".pdf")]
def addbookmark(f):
output = PdfFileMerger()
name = os.path.splitext(os.path.basename(f))[0] # Split filename from .pdf extension
dp = name.index("$") + 1 # Find position of $ sign
bookmarkname = name[dp:].replace("_", " ") # replace underscores with spaces
output.addBookmark(bookmarkname, 0, parent=None) # Add bookmark
output.append(open(f, 'rb'))
output.write(open(f, 'wb'))
for f in pdfcdir:
addbookmark(f)
The UDF works fine when applied to individual PDFs, but it won't add the bookmarks when put into the loop at the bottom of the code. Any ideas on how to make the UDF loop through all PDFs within pdfcdir?
I'm pretty sure that the issue you're having has nothing to do with the loop. Rather, you're passing just the filenames and not including the directory path. It's trying to open these files in the script's current working directory (the directory the script is in, by default) rather than in the directory you read the filenames from.
So, join the directory name with each file name when calling your function.
for f in pdfcdir:
addbookmark(os.path.join(cdir, f))
I am generating a gif with images2gif from some .png pictures. I am using the following script:
__author__ = 'Robert'
from images2gif import writeGif
from PIL import Image
import os
file_names = sorted((fn for fn in os.listdir('/home/manager/Desktop/sf_linux_shared/project/prueba') if fn.endswith('.png')))
#['animationframa.png', 'animationframb.png', ...] "
images = [Image.open(fn) for fn in file_names]
size = (150,150)
for im in images:
im.thumbnail(size, Image.ANTIALIAS)
print writeGif.__doc__
filename = "my_gif.GIF"
writeGif(filename, images, duration=0.2)
however I have the following error:
IOError: [Errno 2] No such file or directory: 'cosa.png'
cosa.png is one of the pictures I want to create the gif with. The problem seems to be in:
images = [Image.open(fn) for fn in file_names]
but I cannot detect it
open(filename) looks in the current working directory if filename is not an
absolute path. The current working directory is the directory from which the script is run.
Either use os.chdir to change the working directory, or make all your filenames absolute:
WORKDIR = '/home/manager/Desktop/sf_linux_shared/project/prueba'
file_names = sorted((os.path.join(WORDIR, fn)
for fn in os.listdir(WORKDIR) if fn.endswith('.png')))
Hi all I need to open images from a folder one by one do some processing on images and save them back to other folder. I am doing this using following sample code.
path1 = path of folder of images
path2 = path of folder to save images
listing = os.listdir(path1)
for file in listing:
im = Image.open(path1 + file)
im.resize((50,50)) % need to do some more processing here
im.save(path2 + file, "JPEG")
Is there any best way to do this?
Thanks!
Sounds like you want multithreading. Here's a quick rev that'll do that.
from multiprocessing import Pool
import os
path1 = "some/path"
path2 = "some/other/path"
listing = os.listdir(path1)
p = Pool(5) # process 5 images simultaneously
def process_fpath(path):
im = Image.open(path1 + path)
im.resize((50,50)) # need to do some more processing here
im.save(os.path.join(path2,path), "JPEG")
p.map(process_fpath, listing)
(edit: use multiprocessing instead of Thread, see that doc for more examples and information)
You can use glob to read the images one by one
import glob
from PIL import Image
images=glob.glob("*.jpg")
for image in images:
img = Image.open(image)
img1 = img.resize(50,50)
img1.save("newfolder\\"+image)