I want to continusly loop image gallery (folder) until I press a key.
So I have a folder with 3 images 1,2,3. I want to display them in order and then to repeat.
I've used while but I didn't manage to make it work.
import Image
image1 = Image.open('image1.jpg')
image.show()
image2 = Image.open('image2.jpg')
image.show()
image3 = Image.open('image3.jpg')
image.show()
See if this works. I'm sure there is an easier way, but this is what I could think of.
from os import listdir
from os.path import isfile, join, abspath
import time
import subprocess
mypath = abspath(__file__)
files_in_folder = [f for f in listdir() if isfile(join(mypath, f))]
# get images
imgs = []
for f in files_in_folder:
_, file_extension = os.path.splitext(f)
if file_extension = ".jpg"
imgs.append(f)
# run loop until keyboard interrupt
try:
while True:
for img in imgs:
viewer = subprocess.Popen(['some_viewer', img])
viewer.terminate()
time.sleep(3)
viewer.kill()
except KeyboardInterrupt:
pass
Here is how you can use the glob module:
import Image
from glob import glob
path = 'C:\\Users\\User\\Desktop\\Folder'
#images = []
for ing in glob(path+'\\*.jpg'):
image = Image.open('image1.jpg')
#images.append(image)
image.show()
The commented lines of code are for if you want to be able to access the images later in the code.
Related
Basically, I copied and paste a script, and merged it with other script, and now the script doesn't work, it says an error "NoneType object has no attribute save"Screenshot
And here's the script:
` from PIL import Image
import PIL
import os
from glob import glob
imgs = [y for x in os.walk(".") for y in glob(os.path.join(x[0], '*.png'))]
size = 32, 32
lastdir = None
for file in imgs:
img = Image.open(file)
img = img.thumbnail(size, resample=PIL.Image.NEAREST)
file = file.replace('img', 'icon', 1)
dir = os.path.dirname(file)
try:
os.makedirs(dir)
except:
pass
if dir!=lastdir:
print(dir)
lastdir = dir
img.save(file + ".png", "PNG")`
Resize various images on various directories and save them, but the images are not saving.
The thumbnail() method modifies its object rather than returning a new one. So, this line:
img = img.thumbnail(size, resample=PIL.Image.NEAREST)
should be:
img.thumbnail(size, resample=PIL.Image.NEAREST)
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
In my file, I have a large number of images in jpg format and they are named [fruit type].[index].jpg.
Instead of manually making three new sub folders to copy and paste the images into each sub folder, is there some python code that can parse through the name of the images and choose where to redirect the image to based on the fruit type in the name, at the same time create a new sub folder when a new fruit type is parsed?
Before
TrainingSet (file)
apple.100.jpg
apple.101.jpg
apple.102.jpg
apple.103.jpg
peach.100.jpg
peach.101.jpg
peach.102.jpg
orange.100.jpg
orange.101.jpg
After
TrainingSet (file)
apple(file)
apple.100.jpg
apple.101.jpg
apple.102.jpg
apple.103.jpg
peach(file)
peach.100.jpg
peach.101.jpg
peach.102.jpg
orange(file)
orange.100.jpg
orange.101.jpg
Here’s the code to do just that, if you need help merging this into your codebase let me know:
import os, os.path, shutil
folder_path = "test"
images = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]
for image in images:
folder_name = image.split('.')[0]
new_path = os.path.join(folder_path, folder_name)
if not os.path.exists(new_path):
os.makedirs(new_path)
old_image_path = os.path.join(folder_path, image)
new_image_path = os.path.join(new_path, image)
shutil.move(old_image_path, new_image_path)
If they are all formatted similarly to the three fruit example you gave, you can simply do a string.split(".")[0] on each filename you encounter:
import os
for image in images:
fruit = image.split(".")[0]
if not os.path.isdir(fruit):
os.mkdir(fruit)
os.rename(os.path.join(fruit, image))
As an idea, hope it helps
import os
from pathlib import Path
import shutil
folder_path = "images/"
nameList=[]
for image in os.listdir(folder_paths):
folder_name = image.split('.')[0]
nameList.append(folder_name)
for f in os.listdir(folder_paths):
Path(folder_name).mkdir(parents=True, exist_ok=True,mode=0o755)
des = folder_name +"/"+str(f)
old_path = folder_paths+str(f)
for path in nameList:
if f.endswith('.jpg'):
print(f)
if path == folder_name:
shutil.move(old_path, str(des))
Currently I am trying to crop all images inside a folder under the address of: C:\\Users\\xie\\Desktop\\tiff\\Bmp and then resave them into the same folder. Below is the code I am trying to experiment with, both run without error but does nothing. Also note I am using windows as platform.
Code 1:
from PIL import Image
import os.path, sys
path = "C:\\Users\\xie\\Desktop\\tiff\\Bmp"
dirs = os.listdir(path)
def crop():
for item in dirs:
if os.path.isfile(path+item):
im = Image.open(path+item)
f, e = os.path.splitext(path+item)
imCrop = im.crop(30, 10, 1024, 1004)
imCrop.save(f + 'Cropped.bmp', "BMP", quality=100)
crop()
Code 2:
for f in os.listdir("C:\\Users\\xie\\Desktop\\tiff\\Bmp"):
for f in ("C:\\Users\\xie\\Desktop\\tiff\\Bmp"):
if f.endswith('.bmp'):
print (f, end=" ")
i = Image.open(f)
area = (30, 10, 1024, 1004)
cropped_i = i.crop(area)
cropped_i.show()
cropped_i.save('Cropped{}.bmp', "BMP", quality=100, optimize=True)
Thanks, any help or suggestions are greatly appreciated!
Code 1 : Corrected
This is your corrected code, you almost had it right, you have to join the path correctly, in your code you weren't adding a separator / between the path and the filename. by using os.path.join you can combine a directory path and a filename.
Furthermore, crop takes a tuple of 4, not 4 arguments.
from PIL import Image
import os.path, sys
path = "C:\\Users\\xie\\Desktop\\tiff\\Bmp"
dirs = os.listdir(path)
def crop():
for item in dirs:
fullpath = os.path.join(path,item) #corrected
if os.path.isfile(fullpath):
im = Image.open(fullpath)
f, e = os.path.splitext(fullpath)
imCrop = im.crop((30, 10, 1024, 1004)) #corrected
imCrop.save(f + 'Cropped.bmp', "BMP", quality=100)
crop()
This is more or less a rough version of code, I used with opencv, it should work the same for PIL also
import glob
import numpy as np
from PIL import Image
image_list = []
for filename in glob.glob('name_of_folder/*.jpg'):
im=Image.open(filename)
image_list.append(im)
a=0
c=[]
for i in range(0,len(image_list)):
#ur image cropping and other operations in here for each image_list[i]
c.append(image_list[i])
c[i].save()
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