I was wondering what is the bast way to use glob.glob in python to manipulate every nth image, lets say I have a folder of ten images and I want to invert every second image.
from PIL import Image, ImageOps
import glob
def main():
for name in glob.glob('*.png'):
im = Image.open(name)
im_invert = ImageOps.invert(im)
im_invert.save('New' + name, quality=100)
main()
It highly depends on how your files are sorted (or how you would like to see your files sorted).
Plus, glob.glob provides a list of unsorted file names (see glob).
Related
I'm trying to create a small tool where I select all the files (textures) in my scene and apply a specific filter to them.
I get the list of '.fileTextureName' attributes that exist on my scene and I get every .exr and .tif that I have. But I am trying to remove the .exr from my list and only apply the filter only to the .tif.
I haven't find a way to make a list of the attributes or to select just the type of file I want.
Here is just the begining of the script:
import maya.cmds as cmds
allFileNodes = cmds.ls(type="file")
def attrList():
for eachFile in allFileNodes:
currentFile = cmds.getAttr(eachFile + '.fileTextureName')
print currentFile
attrList()
Any help is appreciated!!
If you're simply wanting to filter what to operate on based on its file extension then you can use .endswith to only include tif extensions:
import maya.cmds as cmds
all_file_nodes = cmds.ls(type="file")
for each_file in all_file_nodes:
image_path = cmds.getAttr(each_file + ".fileTextureName") # Get the image's path the file is referencing.
if image_path.lower().endswith(".jpg"): # Only continue if the image ends with `tif`, we include `.lower()` in case the extension is upper case.
print image_path # Only tifs beyond this point, do what you want.
In short, I have written a code that opens up a file and does a number of modifications on it. However, I don't want to keep going through my script and renaming all the files when I want to open up a new file.
I'm thinking of setting a variable early on that defines the filename, i.e.
A=filename('png1.png')
B=filename('png2.png')
However, I don't quite know how to implement this. This is my current code:
import os
from os import path
import numpy as np
from PIL import Image
from wordcloud import WordCloud, STOPWORDS
#d=path.dirname(_file_) if "_file_" in locals() else os.getcwd()
os.chdir('C:/Users/Sams PC/Desktop/Word_Cloud_Scripts/Dmitrys Papers/Word_Cloud_Dmitry')
Document=open('Dmitry_all_lower.txt', 'r', encoding='utf-8')
text=Document.read()
heart_mask=np.array(Image.open("**png1.png**"))
print (heart_mask)
split= str('**png1.png**').rsplit('.')
extension=split[len(split)-1]
if extension == "png":
image = Image.open("**png1.png**")
image.convert("RGBA") # Convert this to RGBA if possible
canvas = Image.new('RGBA', image.size, (255,255,255,255)) # Empty canvas colour (r,g,b,a)
canvas.paste(image, mask=image) # Paste the image onto the canvas, using it's alpha channel as mask
#canvas.thumbnail([width, height], Image.ANTIALIAS)
canvas.save('**png2.png**')
from wand.image import Image
with Image(filename='**png2.png**') as img:
img.format='jpeg'
img.save(filename='**png1.jpg**')
from PIL import Image
heart_mask=np.array(Image.open("**png1.jpg**"))
else:
print ('')
print (heart_mask)
stopwords=set(STOPWORDS)
stopwords.update(["will", "us","protein","residue", "interaction","residues","using","proteins","thus","fig"])
wc= WordCloud(stopwords=stopwords, background_color="white",max_words=1000, mask=heart_mask, contour_width=3, contour_color='black')
print ('Generating Word Cloud')
wc.generate(text)
wc.to_file("Dmitry3.png")
import matplotlib.pyplot as plt
plt.figure()
plt.imshow(wc,interpolation="bilinear")
plt.axis("off")
print ('Generation Done')
plt.show()
I've put the entire thing just to see what's going on, but I've bolded (put stars next to), the files I'm trying to modify in my idea. As you can see, I have multiple calls to my file 'png1.png', and I also have calls to save a modified version of that file to 'png2.png' and later a jpeg version of it 'png1.jpg'. I don't want to have to go through my script each time and change each one individually. I was hoping to define them earlier such as A=png1, B=png2, C=jpg1 so that I can replace the calls in my loops with simply A B and C, and if I do choose a new image to upload, I simply change 1 or 2 lines rather than 5 or 6. I.E.
heart_mask=np.array(Image.open("A"))
split= str('A').rsplit('.')
image = Image.open("A")
canvas.save('B')
... so on and so forth
To make your task easier, perhaps you should establish a naming standard defining which files are to be modified, and which ones are already processed. Also, the images you are to process should have a dedicated directory for the purpose.
From what I understand in your code, PNG files are the ones getting processed, while the JPEG files are already done. You can use os.listdir() to traverse a list of files which have a .png extension, something similar to the one below:
for file in os.listdir( "/dedicated_image_dir" ):
if file.endswith(".png"):
# Process your PNG images here
That way, you wouldn't even need to change your code just to accommodate new PNG images with different filenames.
sorry for my trivial question, but I'm new to Python.
I'm trying to convert a series of JPEG images to BMP format and resize it.
I managed to get the procedure for a single image, but now I can not automate the process so that the conversion happens in sequence.
this is my script
from PIL import Image
img = Image.open("C:/Users/***/Documents/images/1.jpg")
new_img = img.resize((320,240))
new_img.save("C:/Users/***/Documents/immages_bmp/1.bmp")
The images are progressively renamed from 1 to 10000.
Does anyone know how to help me implement a for loop to automate the process?
Thank you so much for your help
Something like:
from PIL import Image
from glob import glob
import os
myDir = '/Users/me/pictures'
pic_list = glob(myDir + os.sep + '*' + '.jpg')
for pic in pic_list:
#resize, use a string replace to name new bmps
img = Image.open(pic)
new_img = img.resize((320,240))
newName = pic.replace(".jpg",".bmp")
new_img.save(newName)
Should catch all the images regardless as to their naming convention, and will allow you to edit the list of names before you resize them (or not).
How can I achieve this with Wand library for python:
convert *.png stack_of_multiple_pngs.tiff
?
In particular, how can I read every png image, pack them into a sequence and then save the image as tiff stack:
with Image(filename='*.tiff') as img:
img.save(filename='stack_of_multiple_pngs.tiff')
I understand how to do it for gifs though, i.e. as described in docs. But what about building a sequence as a list and appending every new image I read as a SingleImage()?
Having trouble figuring it out right now.
See also
With wand you would use Image.sequence, not a wildcard filename *.
from wand.image import Image
from glob import glob
# Get list of all images filenames to include
image_names = glob('*.tiff')
# Create new Image, and extend sequence
with Image() as img:
img.sequence.extend( [ Image(filename=f) for f in image_names ] )
img.save(filename='stack_of_multiple_pngs.tiff')
The sequence_test.py file under the test directory will have better examples of working with the image sequence.
i'm trying to use Wand to create a multi-size ico, but i don't find anything talking about that, only normal conversion, to ico... i've found "Sequences":
https://wand.readthedocs.org/en/latest/roadmap.html
and sequences look like what i need, but i only see samples trying to read the multiple images, but not how to create, am i missing something? or is not possible?
or is it possible to do using PIL/PILLOW?
You can append() a single image to Image.sequence list. For example:
from wand.color import Color
from wand.image import Image
with Image(width=32, height=32, background=Color('red')) as ico:
with Image(width=16, height=16, background=Color('green')) as s16:
ico.sequence.append(s16)
ico.save(filename='multisized.ico')
Result (multisized.ico):
I had a similar problem, but with creating a multi-page PDF from multiple JPEG files. In Imagemagick i used command -adjoin. In Wand i did the following:
from glob import glob
from wand.image import Image
files = glob('*.jpg')
with Image() as orig: # create empty Image object
for f in files:
page = Image(filename=f)
orig.sequence.append(page)
orig.save(filename='result.pdf')