I am using a subreddit scraper to download images from wallpaper subreddits. The problem I am having is that some images have a small resolution causing them to look awful when used as wallpapers. I have found that the minimum resolution needed for a good looking wallpaper is 1920x1080. I now need to make a constantly running script that scans the image folder, looks at each images resolution and decides whether to delete it or move on to the next image. I've been tinkering about in Python for an hour or so but feel I am going nowhere fast as I am only a beginner and have not used Python for a few months. Any help on this project would be awesome ;)! Cheers.
UPDATE: I am now stuck on how to get the program to run through a folder and look at each picture. Currently my code is;
import os
from PIL import Image
while True:
for file in os.listdir(r"C:\\Users\\Barney\\Documents\\sam"):
im = Image.open(file)
x, y = im.size
totalsize = x*y
if totalsize < 2073600:
os.remove(file)
But this returns the error;
Traceback (most recent call last):
File "C:\Users\Barney\Desktop\imagefilter.py", line 7, in <module>
im = Image.open(file)
File "C:\Python34\lib\site-packages\PIL\Image.py", line 2251, in open
fp = builtins.open(fp, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'Car - 1971 Ford Mustang Mach 1 351 [2560X1600].jpg'
Looking on the internet I see that there may be a problem from where I am opening the program?? Very confused as the program is looking into this folder and reading the contents as the file it says doesnt exist is in that folder? Any help?
You can use Pillow or PIL:
from PIL import Image
with Image.open(image_file_path) as im:
x, y = im.size
if x < 1920 or y < 1080:
....
UPDATE
os.listdir returns a list of filenames, not a list of filepaths. Unless you run the program in the image directory, it cannot open the file.
Run your program in the image directory, or convert the filenames to filepaths so they can be accessed.
import os
from PIL import Image
img_dir = r"C:\Users\Barney\Documents\sam"
for filename in os.listdir(img_dir):
filepath = os.path.join(img_dir, filename)
with Image.open(filepath) as im:
x, y = im.size
totalsize = x*y
if totalsize < 2073600:
os.remove(filepath)
If you have many subfolders under a main folder you can use the following code:
[for directory_path in glob.glob(r'F:\Data\Main_folder\*'):
print(directory_path)
for filename in os.listdir(directory_path):
filepath = os.path.join(directory_path, filename)
print(filepath)
with Image.open(filepath) as im:
x, y = im.size
totalsize = x*y
if totalsize < 50176:
os.remove(filepath)][1]
Related
I'm trying to modify images in a folder using PIL, but when I run debugging I get a
"Exception has occurred: FileNotFoundError
[Errno 2] No such file or directory: 'page_1.jpg'"
The 'page_1.jpg' is the file I'm interested in. Additionally, I'm using the os library to specify the path. Here's the code, not sure what is going on since it is seeing my file but can't find it.
I have run into this problem while doing the first part of pdf to image conversion and found that if I only include two folders like "/home/folder" it would work.
I am using ubuntu 18.04 and python 3.6.
Thanks for your time.
from pdf2image import convert_from_path
import os
from PIL import Image, ImageFilter
converted = r'/path/to folder'
modified = r'/path/ to folder'
for f in os.listdir(converted):
if f.endswith('.pdf'):
pages = convert_from_path(f, 500)
image_counter = 1
for page in pages:
filename = "Converted/page_" + str(image_counter) + ".jpg"
page.save(filename, 'JPEG')
image_counter = image_counter + 1
for i in os.listdir(modified):
if i.endswith('.jpg'):
filename2 = "path/to folder"
g = Image.open(i)
g.filter(ImageFilter.GaussianBlur()).save(filename2)`enter code here`
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.
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
I am trying to execute this script
from PIL import Image
im = Image.open("image.jpg")
nx, ny = im.size
It is working fine when I run it in python shell
pytesser_v0.0.1]#env python
>>> from PIL import Image
>>> im = Image.open("image.jpg")
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=46x24 at 0x7FA4688F16D0>
but when I put it in a some test.py file and run it like python test.py
I am getting this error
File "test1.py", line 17, in <module>
im = Image.open("image.jpg")
File "/usr/local/python.2.7.11/lib/python2.7/site-packages/PIL/Image.py", line 2309, in open
% (filename if filename else fp))
IOError: cannot identify image file 'image.jpg'
please help me with this issue, Thanks
PS: Earlier I installed PIL from Imaging-1.1.7 setup.py, later I installed Pillow, I think the problem was in the mutual presence of the PIL and Pillow library on the machine.
Seems like PIL library haven't fixed this bug yet.
Here is my solution:
Open image using OpenCV library, then convert it to PIL image
from PIL import Image
import cv2
image_path = 'Folder/My_picture.jpg'
# read image using cv2 as numpy array
cv_img = cv2.imread(image_path)
# convert the color (necessary)
cv_img = cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB)
# read as PIL image in RGB
pil_img = Image.fromarray(cv_img).convert('RGBA')
Then you can operate with it as with a regular PIL image object.
Make sure that "image.jpg" is in the same directory as "test1.py".
If it isn't then you could either move it, or put the correct directory inside of Image.open().
I have the same issue.
This is because the test.py does not have the same pathname. If you are working in the same folder it will work.
However, the solution i found was to put in the full path + file name so that it is unambiguous.
"c:\...fullpath...\image.jpg"
You can do it like this:
from PIL import Image
import os
curDir = os.getcwd()
fileName = "image.jpg"
fn = curDir + "\\" + fileName
print(fn)
image = Image.open(fn)
image.show()
This works. Please let me know if you find better.
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')))