Фотоорганайзер по содержимому

Фотоорганайзер по содержимому


from imageai.Detection import ObjectDetection

import os

import shutil


INPUT_FOLDER = "photos"

OUTPUT_FOLDER = "sorted_photos"

MODEL_PATH = "yolo.h5"


def setup_detector():

  detector = ObjectDetection()

  detector.setModelTypeAsYOLOv3()

  detector.setModelPath(MODEL_PATH)

  detector.loadModel()

  return detector


def detect_objects(detector, image_path):

  _, predictions = detector.detectObjectsFromImage(

    input_image=image_path,

    output_image_path=os.devnull, # не сохраняем изображение

    minimum_percentage_probability=40,

    extract_detected_objects=False,

    display_object_name=False,

    display_percentage_probability=False,

    display_box=False,

    return_detected_frame=False

  )

  return set([p['name'] for p in predictions])


def classify_category(objects):

  categories = {

    "people": ["person"],

    "animals": ["dog", "cat", "horse", "bird"],

    "documents": ["book", "laptop", "keyboard", "tvmonitor", "cell phone"],

    "food": ["cake", "banana", "apple", "bowl", "sandwich"],

    "nature": ["tree", "plant", "flower"],

  }

  for category, keywords in categories.items():

    if any(obj in keywords for obj in objects):

      return category

  return "other"


def organize_photos():

  detector = setup_detector()


  if not os.path.exists(OUTPUT_FOLDER):

    os.makedirs(OUTPUT_FOLDER)


  for file_name in os.listdir(INPUT_FOLDER):

    if not file_name.lower().endswith(('.jpg', '.jpeg', '.png')):

      continue


    full_path = os.path.join(INPUT_FOLDER, file_name)

    objects = detect_objects(detector, full_path)

    category = classify_category(objects)


    target_folder = os.path.join(OUTPUT_FOLDER, category)

    os.makedirs(target_folder, exist_ok=True)


    shutil.copy(full_path, os.path.join(target_folder, file_name))

    print(f"{file_name} → {category}")


if __name__ == "__main__":

  organize_photos()

Report Page