Python script to crop Picture

Hi everyone,

My name is Kris, and this is my first post in the community. :blush: Earlier this year, I switched from ioBroker to Home Assistant and have been gradually migrating all my automations over. I’m running Home Assistant OS as a virtual machine on my NAS and have been very impressed with its capabilities so far.

However, I’ve hit a bit of a roadblock with one of my automations: in the past, whenever someone rang the doorbell, my camera would take a photo, crop it, and send it to my phone via Telegram. I achieved this in ioBroker using a JavaScript.

Now, I want to replicate this functionality in Home Assistant. Unfortunately, I haven’t found a way to crop an image using the built-in tools. I tried implementing it using a Python script, but I keep running into errors when executing the script. I’ve also tried various tools like “Python Scripts Pro,” but none of them have worked for me so far.

pyScript:

from PIL import Image

def main():
    try:
        # Bilddatei laden
        input_file = "tuer.jpg"
        output_file = "Result.jpg"

        # Bild öffnen
        image = Image.open(input_file)

        # Bildgröße auslesen
        width, height = image.size

        # Beschnitt-Bereich definieren (Beispiel: zentrierter Ausschnitt)
        left = width * 0.1  # 10% vom linken Rand
        top = height * 0.1  # 10% vom oberen Rand
        right = width * 0.9  # 90% vom linken Rand
        bottom = height * 0.9  # 90% vom oberen Rand

        cropped_image = image.crop((left, top, right, bottom))

        # Ergebnis speichern
        cropped_image.save(output_file)

        print(f"Bild wurde erfolgreich beschnitten und als '{output_file}' gespeichert.")

    except FileNotFoundError:
        print(f"Die Datei '{input_file}' wurde nicht gefunden. Stellen Sie sicher, dass sie im gleichen Verzeichnis wie dieses Skript liegt.")
    except Exception as e:
        print(f"Ein Fehler ist aufgetreten: {e}")

if __name__ == "__main__":
    main()

Error Message:

So, here are my questions for you:

  1. Can you help me fix my Python script so that it works and achieves the desired result?
  2. Are there any other Home Assistant solutions or tools that can crop an image and send it via Telegram?

Oh, and here’s an additional detail: when I use the Advanced SSH feature in the WebTerminal add-on and run the PyScript from the console, it works perfectly. Just thought I’d mention that as it might help pinpoint the issue.

I’d appreciate any advice or tips on how to get this automation up and running!

Thanks in advance for your help!

Best regards,
Kris

You can’t use import with the python scripts integration. Try pyscript or AppDaemon.

The other option would be to use the shell_command to run your python file and run it from an automation.

Hi everyone,

Thanks to those who responded to my initial post! One suggestion was to try the PyScript add-on. I went ahead and updated my configuration.yaml accordingly and moved all my Python scripts into the appropriate folder. However, I wasn’t able to execute the scripts afterward.

As a workaround, I followed another guide and added shell_command entries to my configuration. Unfortunately, this approach didn’t help me either—I’m still unable to get the automation to work as intended.

I’d really appreciate further advice on what I might be missing or doing wrong. If anyone has experience using PyScript or shell_command for automations like this, I’d love to hear your insights.
image

Thanks again!

Best regards,
Kris

I have not tested this, and may not have this exactly correct, but something like the following:
Note: I show passing in a variable of the location of the file to be converted, but this is not necessary

configuration.yaml

shell_command: 
  #Shell commands as services.
  convert_image: /config/shell_commands/convert_image.sh {{ image }}

Directory

/config/shell_commands$ ls
convert_image.sh 

The convert_image file itself

#!/bin/sh
# pass in as arg the full path name of the file to convert.
CONFIG_PATH=/config
SHELL_PATH=$CONFIG_PATH/shell_commands
/usr/bin/env python3 $SHELL_PATH/bild.py $1

You can test this in UI->DevTools->Action

action: shell_command.convert_image
  - data:
      image: /config/www/images/my_images/my_image.jpg
1 Like