2
$\begingroup$

i try to load image by part of name, for example image_dir is a variable folder, in some different folder i have single image with name "Cat smile.png" or "cat go crazy.jpeg" (note uppercase lowercase Cat , cat) i find glob.glob() but not sure if is right way

image_dir = ###string variable
my_image = "Cat" or "cat"or "caT" or "CAT"

###want to find photo with that part of name if exist

image = os.path.join(bpy.path.abspath("//"),image_dir + os.sep + my_image)

edit: i think is not good way because i think best way to make that is use append image from directory with :

image_dir = ###string variable
directory = os.path.join(bpy.path.abspath("//"),image_dir)
images = []
for fn in os.listdir(directory):
    images.append(fn)

now i can find image name from images because is a list... but I'm not able

$\endgroup$
2
$\begingroup$

Regular expression example.

For the most part this is a generic python question, some answers from stack overflow.

python finding substring inside string

Python glob multiple extensions

Python glob multiple filetypes

For blender specifics, the image file extensions that your blender can open are

>>> bpy.path.extensions_image
frozenset({'.dpx', '.pdd', '.jp2', '.hdr', '.j2c', '.rgb', '.tiff', '.sgi', '.tga', '.rgba', '.png', '.cin', '.jpg', '.exr', '.tif', '.dds', '.psd', '.psb', '.bmp', '.jpeg', '.tx'})

Here is a sample method, that searches for image files that have a substring in their name and an extension suitable to blender. A regular expression search is used in both cases. The searches are case insensitive.

The links above show how to do this using other tools such as glob, pathlib and fnmatch

import bpy

def find_files(substring, path='.', extensions=[]):
    from os import listdir
    from re import search, IGNORECASE
    return [f for f in listdir(path) 
            if search(r'%s' % substring, f, IGNORECASE) 
            and any(search(r'%s$' % ext, f, IGNORECASE) 
                    for ext in extensions)]

def image_files(substring, path="."):
    return find_files(substring, path=path, extensions=bpy.path.extensions_image)

def movie_files(substring, path="."):
    return find_files(substring, path=path, extensions=bpy.path.extensions_movie)

def audio_files(substring, path="."):
    return find_files(substring, path=path, extensions=bpy.path.extensions_audio)

# test call, search for "screenshot" in image folder 
# and load images 
from os.path import join
image_path = "/home/batfinger/Pictures"
for fp in image_files("screenshot", path=image_path):
    print(fp)
    bpy.data.images.load(join(image_path, fp))

Notes maybe switch extension search to first. For recursive folder search would use something like os.walk instead of os.listdir

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.