I'm working on an image to text OCR system and I kept receiving an error on the console stating
Traceback (most recent call last):
File "crack_test.py", line 48, in <module>
temp.append(buildvector(Image.open("./iconset/%s/%s"%(letter,img))))
File "/Users/seng_kin/anaconda/lib/python2.7/site-packages/PIL/Image.py", line 2290, in open
% (filename if filename else fp))
IOError: cannot identify image file './characterset/a/.DS_Store'
I have a folder in a ../OCR/characterset/ directory which has 26 subfolders representing 26 characters whereby each subfolder contains a .PNG of a character.
The score_test.py is stored in ../OCR/
score_test.py Code:
from PIL import Image
import os, sys
import math
****def functions****
iconset = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r',
's','t','u','v','w','x','y','z']
imageset = []
for letter in iconset:
for img in os.listdir('./characterset/%s/'%(letter)):
temp = []
if img != "Thumbs.db": #windows check...
temp.append(buildvector(Image.open("./characterset/%s/%s"%(letter, img))))
imageset.append({letter:temp})
I saw other solutions on the website but all is related to the absence of from PIL import Image. Am I missing something?
.DS_Store is a "hidden" file in directories on Mac OS X.
In your if img != "Thumbs.db" check, you should add:
if not img.startswith('.') and img != 'Thumbs.db':
this way you filter out all "hidden" files.
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 have a file of images and I want the folder to have a random file selected and that image to be displayed. This is the code I have so far:
dir = path.dirname(__file__)
examQ_dir = path.join(dir, 'Exam Questions')
question = choice(path.join(examQ_dir))
image_surface = pg.display.set_mode((850, 500))
image = pg.image.load(question)
And the error I get is as follows:
Traceback (most recent call last):
File "D:/A level Comp Sci/Platformer Game in Development Stages/Question.py", line 13, in <module>
image = pg.image.load(question)
pygame.error: Couldn't open E
And everytime I run it, the last letter of the error is slightly different sometimes it will say
pygame.error: Couldn't open i
And other times there's nothing there at all. I think there's something wrong with my logic of setting this up but I can't work out what. I'm using the PyCharm IDE.
You have to use os.listdir to get entries in the directory. Use os.isfile to evaluate if an entry is a file:
import os
import random
dir = os.path.dirname(__file__)
examQ_dir = os.path.join(dir, 'Exam Questions')
allpaths = [os.path.join(examQ_dir, entry) for entry in os.listdir(examQ_dir)]
filepaths = [p for p in allpaths if os.isfile(p)]
question = random.choice(filepaths)
Note, when you do question = choice(path.join(examQ_dir)), then the argument to choice is a string (the file path). You actually select a random letter form the file path.
I am trying to open the image from this directory but am not been able to.
It gives me the following error:
WindowsError: [Error 123] The filename, directory name, or volume
label syntax is incorrect.
This is my code:
import os, random
random.choice(os.listdir("C:\\Users\rkp10\AppData\Local\Google\Chrome\User Data\Default\Extensions\laookkfknpbbblfpciffpaejjkokdgca\0.91.6_0\backgrounds"+'png'))
In here , in the folder backgrounds there are many images.I want a random Image to open.But while running the program , I am getting WindowsError.
What am I doing wrong?
Edit 1
I tried this:
random.choice(os.listdir(r"C:\Users\rkp10\AppData\Local\Google\Chrome\User Data\Default\Extensions\laookkfknpbbblfpciffpaejjkokdgca\0.91.6_0\backgrounds"+'png'))
But am getting the error:
WindowsError: [Error 123] The filename, directory name, or volume
label syntax is incorrect:
'C:\Users\rkp10\AppData\Local\Google\Chrome\User
Data\Default\Extensions\laookkfknpbbblfpciffpaejjkokdgca\0.91.6_0\backgrounds\*.png/.'
Edit 2
I tried this:
import os, random
a=random.choice(os.listdir(r"C:\Users\rkp10\AppData\Local\Google\Chrome\User Data\Default\Extensions\laookkfknpbbblfpciffpaejjkokdgca\0.91.6_0\backgrounds"))
os.open(a)
Now I dont get error but it does not open the image either.
Edit 3
I have also tried:
import random,os
folder= "C:\\Users\rkp10\AppData\Local\Google\Chrome\User Data\Default\Extensions\laookkfknpbbblfpciffpaejjkokdgca\0.91.6_0\backgrounds"
a=random.choice(os.listdir(folder))
print(a)
from PIL import Image
file = folder+'\\'+a
Image.open(file).show()
#os.open(a, os.O_RDWR)
from PIL import Image
file = folder+'\\'+a
Image.open(file).show()
But got the following error once again:
Traceback (most recent call last): File "G:\Grade 12
Project\auto.py", line 4, in
a=random.choice(os.listdir(folder)) WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:
'C:\Users\rkp10\AppData\Local\Google\Chrome\User
Data\Default\Extensions\laookkfknpbbblfpciffpaejjkokdgca'
Here(the yellow highlighted part) is the directory where my images are stored.
Use the PIL instead.
import os, random
folder=r"D:\Study\SO"
a=random.choice(os.listdir(folder))
print(a)
#os.open(a, os.O_RDWR)
from PIL import Image
file = folder+'\\'+a
Image.open(file).show()
source:
Open and display .png file in python using PIL
The problem with this is that a doesn't have absolute path to that chosen random files.
In Edit 1, the "png" gets concatenated but there is no folder named "backgroundspng"
In Edit 2, you haven't given the flags for os.open() which can be found here.
In Edit 3, please make sure that you are using the r before string.
In you case, use this :
folder = r"C:\\Users\rkp10\AppData\Local\Google\Chrome\User Data\Default\Extensions\laookkfknpbbblfpciffpaejjkokdgca\0.91.6_0\backgrounds"
You need to use a raw string by prepending the string with r:
random.choice(os.listdir(r"C:\Users\rkp10\AppData\Local\Google\Chrome\User Data\Default\Extensions\laookkfknpbbblfpciffpaejjkokdgca\0.91.6_0\backgrounds"+'png'))
Else, you would need to escape each backslash by another backslash.
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]
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)))