Select only .tif files in scene, Maya-Python - python

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.

Related

Manipulate every nth image using glob.glob

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).

can you use pigeon to annotate all images in a folder

I would like to label images within a folder with either yes or no for a machine learning project.
I found this great tool; Pigeon..
https://github.com/agermanidis/pigeon
but the examples provided online requires the user to provide the names of all files within the script. I have not been able to find a way to point the script to a folder instead of including all image names.
Is there a way where you can just provide a link to a folder only.
from pigeon import annotate
from IPython.display import display, Image
annotations = annotate(
['assets/img_example1.jpg', 'assets/img_example2.jpg'],
options=['cat', 'dog', 'horse'],
display_fn=lambda filename: display(Image(filename))
)
One possible solution is to just list all files in the folder you are interested in. In this case you provide just the path to the folder (absolute or relative) and use os.listdir to get all the files in that folder.
I then use os.path.join to get the file paths and pass a list of the file paths to annotate.
from pigeon import annotate
from IPython.display import display, Image
import os
path = "assets"
imgs = os.listdir(path)
imgs = [os.path.join(path, img) for img in imgs]
annotations = annotate(
imgs,
options=['cat', 'dog', 'horse'],
display_fn=lambda filename: display(Image(filename))
)
I made a for-loop that went through a folder and populated a list with the image names. Then just called the list in place of
['assets/img_example1.jpg', 'assets/img_example2.jpg']

OS function in python to read files

I have a folder structure listed like the following
MA/valid/wrist/pa/positive/image2.png
Basically, for each wrist there are multiple pa, and for each pa there is a positive or negative study, and for each study there are up to 3 images in png format.
I have written a code below, but it only goes down to the pa level, it does not load my image files. Any help with loading my image files will be appreciated.
def load(Pic_Dir,Imsize):
data = []
dirs = next(os.walk(Pic_Dir))[1]
for dir_name in dirs:
files = next(os.walk(os.path.join(Pic_Dir, dir_name)))[2]
print("load [", len(files), "] files from [",dir_name,"] " )
for i in range(len(files)):
image_name = files[i]
image_path = os.path.join(Pic_Dir, dir_name, image_name)
label = dir_name
img = cv2.imread(image_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = cv2.resize(img, (Imsize, Imsize))
data.append([np.array(img), label])
return
The function is called with the following line:
data=load("/Users/bond/MA/train/XR_WRIST",244)
I am not sure if I understood your question very well. However, if you need to walk through the directory and process all image file in its sub-directory, I would suggest you write something like this:
def load(root_director,Imsize):
import os
#TODO:You need to figure out how to get a list of this pa.
# Your question is not clear on how to get here
pas =get_list_of_pa()
cases =["positive", "negative"]
for pa in pas:
for case in cases:
in_dir = os.path.join(root_directory, pa, case)
all_images = [f for f in os.listdir(in_dir) if f.endswith('.png')]
for image in all_images:
#Do your processing here
pass
Basically, as you said, if you have many pa (what is pa?) you first need to get a list of all pas and loop through each one to access the list of cases=["positive", "negative]. This is not optimum. There are better ways to go through a directory, e.g., using the path.rglob or os.walk method you used before.
Please note that I am writing this code off the top of my head and did not test it in any way.
As a side note, IMHO, I would refactor your method and call it as follows
def load (director, pa, case):
# Get images for the pa and case
# Process the images
This would potentially reduce its complexity. In fact, to respect the single-responsibility principle (SRP), you probably need to refactor the method much further. For example, you need a method to get all the images of a directory
def get_images (director):
pass
Which returns the list of images (in this case, only .png files). Then, you would need another method that processes the image
def process_image (Imsize):
pass
I hope this helps!

Loop through files in list and move specified one (Python)

I have this code which show me all the .tif files in a folder I give.
timestr = datetime.now().strftime('%Y%m%d-%H%M%S%f')
ex_area_files = []
tif_files = glob.glob('C:\\Users\\Bob\\Desktop\\Folder\\' + str(timestr) + '\\EXTRACTED\\*.tif')
ex_area_files = [tif_files]
print(ex_area_files)
How can I move some specified ones (to another folder) ? I mean, I want to move all the .tif files which result of width*height is less/more than a certain value.
What I tried was to loop through the array and, after set the codition, move the files. All the result was a loop fail which blocked all the system :)
It follows...
image = cv2.imread('image.jpg')
height = np.size(image, 0)
width = np.size(image, 1)
condition = (height*width) > 9600
How can I also set ex_area_files (my .tif array) as directory of files from which cv2 can read ? And, more imporant, how to set a file at once ?
The files which satisfy the condition (images with values of 320*30px) should be moved to another directory. How to do it after the program decided that the file is ok to be moved ?
Thanks
Tip: this is a next step after this other piece of code: Exclude images of certain dimensions from process (OpenCV, Python)
In this case, take a look at ex_area14.png. I want to move a series of files like that (but in .tif format..)
I recommend using shutil for moving files. To move them You can use shutil.copy() - I Personally use shutil.copy2()
so try something like this:
import shutil
import opencv
for files in ex_area_files:
if files (PLACE YOUR CONDITION HERE):
`shutil.copy('PATH_OF_file', 'PATH_OF_WHERE_TO_DROP')
EDIT:
So i personally like os.walk(), here i'm looping through the files, and if files endswith .tif, I will read the file with imread get the height and width, and check if that condition is met. You'll have to provide where you want to copy the files to. (Take note of .replace() - imread for some reason likes the slashes like / instead of \)
import shutil
import opencv
import os
for root, dirs, files in os.walk(r'FOLDER HERE'):
for file in files:
if file.lower().endswith('.tif'):
image = cv2.imread(root.replace('\\', '/') + '/' +file
height = np.size(image, 0)
width = np.size(image, 1)
if height*width > 9600:
shutil.copy(root.replace('\\', '/') + '/' +file, 'PATH_OF_WHERE_TO_DROP')

How to load multiple images from folder. PyQt4

I want to be able to load large number of images one by one from the given folder. And also without knowing the names of the each image (only the name of the folder where all images are located). Currently I can load only one image using it's name (pic.jpg):
pixmap = QtGui.QPixmap("pic.jpg")
item = QtGui.QGraphicsPixmapItem(pixmap)
self.scene.addItem(item)
self.scene.update()
Is there any way to do this? Thanks in advance!
The os module contains filesystem access functions.
import os
dir = "dirname"
for file in os.listdir(dir):
... = QtGui.QPixmap(os.path.join(dir, file))
Note: os.path.join is there so you are platform agnostic.

Categories