I am trying to follow a machine learning code the code
and am unsure of why I receive a FileNotFoundError: [Errno 2] No such file or directory: 'new_imgs/0.png' when trying to modify the images. When checking my folders I see the lfw.gz file and the directory with all of the images. Would I need to create a new folder in this case and set that path = to file paths to have the images that are being resized saved? This is the portion of the code that causes the error. Any advice would be great!
url = "http://vis-www.cs.umass.edu/lfw/lfw.tgz"
filename = "lfw.tgz"
directory = "imgs"
new_dir = "new_imgs"
import urllib
import tarfile
import os
import tarfile
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.image import imread
from scipy.misc import imresize, imsave
import tensorflow as tf
%matplotlib inline
if not os.path.isdir(directory):
if not os.path.isfile(filename):
urllib.urlretrieve (url, filename)
tar = tarfile.open(filename, "r:gz")
tar.extractall(path=directory)
tar.close()
filepaths = []
for dir_, _, files in os.walk(directory):
for fileName in files:
relDir = os.path.relpath(dir_, directory)
relFile = os.path.join(relDir, fileName)
filepaths.append(directory + "/" + relFile)
for i, fp in enumerate(filepaths):
img = imread(fp) #/ 255.0
img = imresize(img, (40, 40))
imsave(new_dir + "/" + str(i) + ".png", img)
Related
I am going to resize image file which located in Desktop with set of subfolder.
I try following command and it works without rename save new.
from PIL import Image
import os, sys
import glob
root_dir='./././Desktop/python/'
def resize():
for filename in glob.iglob(root_dir + '**/*.jpg', recursive=True):
print(filename)
im = Image.open(filename)
imResize = im.resize((450,600), Image.ANTIALIAS)
imResize.save(filename , 'JPEG', quality=90)
resize()
My question is how can I add the correct command to save the renewe resized image file with append 'f + _thumbnail' + .jpg?
E.g file1 > file1_thumbnail.jpg
I tried add followings to row print(filename) but show error.
f, e = os.path.splitext(path+item)
size = im.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))
new_im.save(f + 'resized.jpg', 'JPEG', quality=90)
May I know how can fix it?
Many Thanks
You can use python slicing of strings for this -
You can modify your code to -
from PIL import Image
import os, sys
import glob
root_dir='./././Desktop/python/'
def resize():
for filename in glob.iglob(root_dir + '**/*.jpg', recursive=True):
print(filename)
im = Image.open(filename)
imResize = im.resize((450,600), Image.ANTIALIAS)
filename = filename[:-4] + " _thumbnail" + filename[-4:]
imResize.save(filename , 'JPEG', quality=90)
resize()
The ".jpg" can be sliced at the end.
I have about 300000 image files in a zip folder. Some of those files have path starting with '__'. PIL function Image.Open() is not able to open these files. Please suggest a way to open them. My code below:
import pandas as pd
import numpy as np
from zipfile import ZipFile
from io import BytesIO
from PIL import Image
from PIL import UnidentifiedImageError
problem_files = []
file_paths = []
img_list = []
img_size = (128,128)
with ZipFile('/XXX/YYY/ZZZ/AI_ML/Project2/words.zip') as myzip:
contents = myzip.namelist()
for i in range(0,len(contents)-1):
text = str(contents[i])
if '.png' in text:
file_paths.append(contents[i])
for path in file_paths:
img = myzip.read(path)
try:
img_data = Image.open(BytesIO(img))
except UnidentifiedImageError:
problem_files.append(path)
img_data = img_data.convert('L')
img_data = img_data.resize(img_size)
image_as_array = np.array(img_data, np.uint8)
image_as_array = np.reshape(image_as_array,(1,-1))
img_list.append(image_as_array)
This puts all the files with path starting with '__' into problem_files list
problem_files[-10:]
['__MACOSX/words/j04/j04-070/._j04-070-08-07.png',
'__MACOSX/words/j04/j04-070/._j04-070-04-07.png',
'__MACOSX/words/j04/j04-070/._j04-070-04-06.png',
'__MACOSX/words/j04/j04-070/._j04-070-08-06.png',
'__MACOSX/words/j04/j04-070/._j04-070-06-03.png',
'__MACOSX/words/j04/j04-070/._j04-070-06-01.png',
'__MACOSX/words/j04/j04-070/._j04-070-08-04.png',
'__MACOSX/words/j04/j04-070/._j04-070-04-04.png',
'__MACOSX/words/j04/j04-070/._j04-070-04-05.png',
'__MACOSX/words/j04/j04-070/._j04-070-08-05.png']
There are about 100000 images in problem_files list
I am trying to read all the jpeg images in my folder. But it throws an error.
import os
import sys
import random
import math
import numpy as np
import cv2
import matplotlib
import matplotlib.pyplot as plt
from shutil import copy
datafolder = r'C:\Users\ABI\Documents\Take Leap\TL\TL\*.jpeg'
categories = ["number","character"]
for category in categories:
path = os.path.join(datafolder, *category)
dirs = os.listdir(path)
for img in dirs:
img_array = cv2.imread(os.path.join(path,img), cv2.IMREAD_GRAYSCALE)
plt.imshow(img_array, cmap = "black")
plt.show()
break
sys.exit()
OSError
Traceback (most recent call last)
<ipython-input-13-c3f3eb12f0fc> in <module>
15 for category in categories:
16 path = os.path.join(datafolder, *category)
---> 17 dirs = os.listdir(path)
18 for img in dirs:
19 img_array = cv2.imread(os.path.join(path,img), cv2.IMREAD_GRAYSCALE)
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\\Users\\ABI\\Documents\\Take Leap\\TL\\TL\\*.jpeg\\n\\u\\m\\b\\e\\r'
With #Rakesh's comment about removing that splat asterisk, your code is still generating a path like C:\Users\ABI\Documents\Take Leap\TL\TL\*.jpeg\number which is wrong.
You might be looking for something like
import glob
data_template = r'C:\Users\ABI\Documents\Take Leap\TL\TL\{category}\*.jpeg'
# ...
for category in categories:
path = data_template.format(category=category)
files = glob.glob(path)
This will generate and use paths like C:\Users\ABI\Documents\Take Leap\TL\TL\number\*.jpeg.
Note the use of glob.glob(), which can handle wildcards unlike os.listdir(), which only accepts a directory.
i'm trying to retrieve images from my local directory using array list but i got all images from list but i don't know how to show images from list one by one.
Please help me if anyone knows.
my.py:
import os, os.path
imgs = []
# print(imgs)
path = "C:/Users/admin/PycharmProjects/my_module/static/files"
valid_images = [".jpg",".gif",".png",".tga"]
print(valid_images)
for f in os.listdir(path):
ext = os.path.splitext(f)[1]
os.listdir(path).append(f)
# Image.show(f)
There are several options depending on your environment and visualization libraries. Check this good answer
You need to do from PIL import Image, then you could do Image.open(path + "/" + f).show(). Try this:
import os, os.path
from PIL import Image
imgs = []
path = "path/to/directory"
valid_images = [".jpg", ".gif", ".png", ".tga"]
print(valid_images)
for f in os.listdir(path):
ext = os.path.splitext(f)[1]
if ext in valid_images:
imgs.append(path + "/" + f)
img = Image.open(path + "/" + f)
img.show()
print(imgs)
I have tried and i got my expected output.
py:
import os
from PIL import Image
img=[]
path="C:/Users/admin/PycharmProjects/my_module/static/files/"
for f in os.listdir(path):
ext = os.path.splitext(f)[1]
os.listdir(path).append(f)
image = Image.open(f)
image.show()
files2 = [f for f in listdir(dstpath) if isfile(join(dstpath,f))]
for image in files2:
img = cv2.imread(os.path.join(dstpath,image))
equ = cv2.equalizeHist(img)
dstPath2 = join(dstpath,image)
cv2.imwrite(dstPath2,equ)
I have a folder consisting of grayscale images in jpg format but when I run my above code for Histogram equalization it gives me the above mentioned error. Pls help
imread load image in color mode by default. Try to use img = cv2.imread(your_image_path,cv2.IMREAD_GRAYSCALE) instead
#author: Quantum
"""
import cv2
import os
from os import listdir,makedirs
from os.path import isfile,join
path = r'' # Source Folder
dstpath = r'' # 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),cv2.IMREAD_GRAYSCALE)
**imgnew=cv2.equalizeHist(img)**
dstPath = join(dstpath,image)
cv2.imwrite(dstPath,imgnew)
except:
print ("{} is not converted".format(image))
All I did was added the histeq function while my files are converted to grayscale