Partage
  • Partager sur Facebook
  • Partager sur Twitter

Script Python3 - os.chdir - exiftool

Utilisation avec variables

    21 février 2024 à 17:25:23

    Bonjour,

    Je suis un jeune écolier de 66 ans qui débute en Python.

    Je rencontre 2 points dur :

       - os.chdir(variable)

    import os
    import shutil
    from os import listdir
    import os.path
    from pathlib import Path
    import errno
    
    Dossier_RAW = input("Input Dossier RAW : ")
    print("Dossier RAW = ", Dossier_RAW)                    # Dossier RAW =  '/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test batch hdrmerge/10_RAW'
    Dossier_panorama = str(Path(Dossier_RAW).parents[0])
    print("Dossier du panorama : ", Dossier_panorama)       # Dossier du panorama :  '/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge
    path = (Dossier_panorama + "'")
    print("Path = ", path)                                  # Path =  '/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge'
    
    #test = os.path.expanduser(Path(Dossier_RAW).parents[0])
    #test = os.path.expanduser(Dossier_RAW)
    
    
    
    
    #os.chdir(test)                 # FileNotFoundError: [Errno 2] No such file or directory: "'/home/vieux_loup/Images/.Vorkflow/Test_batch_hdrmerge/10_RAW' "
    os.chdir(path)                  # FileNotFoundError: [Errno 2] No such file or directory: "'/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge'"
    
    #os.chdir('/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge')              # chdir =  /home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge           Ok
    #os.chdir('/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge/10_RAW')     # chdir =  /home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge/10_RAW     Ok
    
    print("chdir = ", os.getcwd())
    vieux_loup@Zalman:~$ python3 /home/vieux_loup/Bureau/OpenClassRoom/FOCR_1.py  
    Input Dossier RAW : '/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge/10_RAW' 
    Dossier RAW =  '/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge/10_RAW' 
    Dossier du panorama :  '/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge
    Path =  '/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge'
    Traceback (most recent call last):
      File "/home/vieux_loup/Bureau/OpenClassRoom/FOCR_1.py", line 22, in <module>
        os.chdir(path)                  # FileNotFoundError: [Errno 2] No such file or directory: "'/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge'"
    FileNotFoundError: [Errno 2] No such file or directory: "'/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge'"
    vieux_loup@Zalman:~$ 

    - Passer des variables à exiftool

    import os
    
    path = '/home/vieux_loup/Images/.Vorkflow/Travaux photos/Megeve 2023/Test batch hdrmerge/10 RAW/'
    #path = '/home/vieux_loup/Images/.Vorkflow/Travaux photos/Megeve_2023/Test_batch_hdrmerge/10_RAW/'
    
    #RAW = input("Dossier RAW : ")
    #path = RAW
    
    RAW = os.path.dirname(path)
    print("\n" + "Dossier: " + RAW + "\n")
    from os import listdir
    from os.path import isfile, join
    RAWS = sorted([f for f in listdir(RAW) if isfile(join(RAW, f))])
    print(RAWS)
    
    
    import sys
    import pyexiv2
    
    Item = RAWS[0:9]
    print("\n")
    print(Item)
    print("\n")
    
    
    def ExposureTime(a):
        md = pyexiv2.ImageMetadata(RAW + '/' + a)
        md.read()
        aperture = float(md['Exif.Photo.ExposureTime'].value)
        exposuretime = ("{}".format(aperture))
        return(exposuretime)
    
    ExTi_t = set(map(ExposureTime, Item))       # https://apprendrepython.com/appliquer-une-fonction-aux-elements-dune-liste-avec-map-en-python/
    print(ExTi_t)
    
    
    def ExposureTimeFloat(b):
        return(float(b))
    
    ExTi_n = sorted((list(map(ExposureTimeFloat, ExTi_t))), reverse = True)
    print(ExTi_n)
    
    
    def Vitesse(v):
        return("1/" + str(round(1/v)))
    
    Vitesses = list(map(Vitesse, ExTi_n))
    
    #print("\n" +  "Bracketting : " + str(len(Vitesses)) + " expositions")
    print("\n" + "Photos : " + str(len(RAWS)) + "          Bracketting : " + str(len(Vitesses)) + " expositions" + "          Piles : " + str((len(RAWS))//(len(Vitesses))))
    print("Vitesses : " + str(Vitesses))
    #print("Photos : " + str(len(RAWS)) + "      Piles : " + str((len(RAWS))//(len(Vitesses))))
    #print("\n")
    
    if len(RAWS) % len(Vitesses) > 0:
        input("Erreur - 1 pile incomplète - Entrée pour quitter")
        exit()
    
    
    #file = RAWS[0]
    Photos_1 = RAWS[0]
    md = pyexiv2.ImageMetadata(RAW + '/' + Photos_1)
    md.read()
    
    aperture = str(md['Exif.Photo.DateTimeOriginal'].value)
    Date = ("{}".format(aperture))#
    #print("Prise de vue le : " + Date + "\n")
    #print("Prise de vue le : " + Date)
    #print(type(Date))
    #print("\n")
    
    
    from datetime import datetime, timedelta
    
    Date_a = datetime.strptime(Date, "%Y-%m-%d %H:%M:%S")
    #print("Date photo 1 = " + str(Date_a))
    
    #print(type(Date_a))
    #print("\n")
    
    Date_pile_1 = Date_a.replace(minute=0, second=0)
    print("Date prise de vue : " + str(Date_a) + "      Time pile 1 : " + str(Date_pile_1))
    #print(type(Date_pile_1))
    print("\n")
    
    
    from PIL import Image
    import exifread
    import datetime
    import exiftool         # pip install git+https://github.com/smarnach/pyexiftool.git#egg=pyexiftool   https://exiftool.org/forum/index.php?topic=10962.0
    import errno
    #from exiftool import ExifToolHelper
    
    os.chdir(RAW)
    directory = os.getcwd()
    print("Directory : ", directory)
    
    def Datetime(raw):                              # https://pythonhint.com/post/1167377288211670/how-to-change-image-captured-date-in-python
    
        print("i = " + i)               # i = DSC_7367.NEF
        print("Index = " + str(RAWS.index(i)))
        Index = RAWS.index(i)
        AddSec = Index//len(Vitesses)*10
        print("AddSec = " + str(AddSec))
        new_date = Date_pile_1 + datetime.timedelta(seconds=AddSec)
        print(new_date)
        #print("\n")
    
        files = (RAW + '/' + raw)
        # files = os.path.join(RAW, raw)     # A tester
        print(raw)              # DSC_7367.NEF
        print(type(raw))
        print(files)
        print(type(files))
        file = bytes(files, 'utf-8')
        print(file)
        print(type(file))
    
        #exif = ("b\"-DateTimeOriginal=" + str(new_date) + "\", b\"" + str(raw) + "\"")
        #exif = ("b'-DateTimeOriginal=" + str(new_date) + "', b'" + str(raw) + "'")
        exif = ("-DateTimeOriginal=" + str(new_date) + str(raw))
        #exif = bytes(exi, 'utf-8')
        print("Exif = ", exif)              # Exif =  -DateTimeOriginal=2023-06-19 15:02:10', DSC_7368.NEF'
        print(type(exif))
        print()
    
    
    #with exiftool.ExifTool() as et:
        #et.execute(b"-DateTimeOriginal=2022:01:01 01:00:00", b"DSC_7367.NEF")   # OK
        #et.execute(b'-DateTimeOriginal=2022:01:01 01:00:00', b'DSC_7367.NEF')   # OK
    
        #et.execute(b'(-DateTimeOriginal=2022:01:01 01:00:00, DSC_7367.NEF)')        # Pas d'erreur mais ne fonctionne pas
        #et.execute(exif)        # NameError: name 'exif' is not defined. Did you mean: 'exit'?
        #et.execute('exif')      # line 135, in <module> et.execute('exif')
                                # self._process.stdin.write(b"\n".join(params + (b"-execute\n",)))
                                # TypeError: sequence item 0: expected a bytes-like object, str found
        #b'et.execute(exif)'         # pas d'erreur, mais ne marche pas
        #et.execute(b'-DateTimeOriginal=2022:01:01 01:00:00', "$(i)")    # TypeError: sequence item 1: expected a bytes-like object, str found
        #et.execute(b'-DateTimeOriginal=2022:01:01 01:00:00', b'"$(i)"')     # Pas d'erreur mais ne fonctionne pas
        #et.execute(b'-DateTimeOriginal=2022:01:01 01:00:00', b'"$i"')         # Pas d'erreur mais ne fonctionne pas
        #et.execute('$exif')     # TypeError: sequence item 1: expected a bytes-like object, str found
    
    
    
    #   https://stackoverflow.com/questions/50938662/writing-exif-data-to-the-exif-header-using-pyexiftool
    #   https://sylikc.github.io/pyexiftool/examples.html
    #   https://www.codeease.net/programming/python/cd-in-python
    #   https://photo.stackexchange.com/questions/92390/how-to-use-user-provided-variables-with-exiftool
    #   https://stackoverflow.com/questions/6812031/how-to-make-unicode-string-with-python3
    
    
    for i in RAWS:
        x = Datetime(i)
    
    # lancer programme externe :  'os.system("...")'
    # Programme externe = hdrmerge -v --batch -a -g 5 -b 32 --no-crop *.NEF
    
    
    #---------------------------------------------------------------------------------------------------------------------------------
    # Python NameError : le nom n'est pas défini
    # La solution à ce problème consiste à appeler vos classes et fonctions après les avoir définies. Python n'a aucun moyen de transmettre des classes ou des méthodes, la seule option est donc de placer les invocations de fonctions à # la fin du programme plutôt qu'au début. L'autre option consiste à placer vos méthodes dans des bibliothèques importées en haut de votre fichier, qui sont toujours appelées en premier.
    
    # https://bobbyhadz.com/blog/python-nameerror-name-is-not-defined
    
    

    Resultat :

    vieux_loup@Zalman:~$ python3 /home/vieux_loup/Bureau/OpenClassRoom/HDRmergeCLI.py 
    
    Dossier: /home/vieux_loup/Images/.Vorkflow/Travaux photos/Megeve 2023/Test batch hdrmerge/10 RAW
    
    ['DSC_7327.NEF', 'DSC_7328.NEF', 'DSC_7329.NEF', 'DSC_7330.NEF', 'DSC_7331.NEF', 'DSC_7332.NEF', 'DSC_7333.NEF', 'DSC_7334.NEF', 'DSC_7335.NEF', 'DSC_7336.NEF', 'DSC_7337.NEF', 'DSC_7338.NEF', 'DSC_7339.NEF', 'DSC_7340.NEF', 'DSC_7341.NEF', 'DSC_7342.NEF', 'DSC_7343.NEF', 'DSC_7344.NEF', 'DSC_7345.NEF', 'DSC_7346.NEF', 'DSC_7347.NEF', 'DSC_7348.NEF', 'DSC_7349.NEF', 'DSC_7350.NEF', 'DSC_7351.NEF', 'DSC_7352.NEF', 'DSC_7353.NEF', 'DSC_7354.NEF', 'DSC_7355.NEF', 'DSC_7356.NEF', 'DSC_7357.NEF', 'DSC_7358.NEF', 'DSC_7359.NEF', 'DSC_7360.NEF', 'DSC_7361.NEF', 'DSC_7362.NEF', 'DSC_7363.NEF', 'DSC_7364.NEF', 'DSC_7365.NEF', 'DSC_7366.NEF', 'DSC_7367.NEF', 'DSC_7368.NEF']
    
    
    ['DSC_7327.NEF', 'DSC_7328.NEF', 'DSC_7329.NEF', 'DSC_7330.NEF', 'DSC_7331.NEF', 'DSC_7332.NEF', 'DSC_7333.NEF', 'DSC_7334.NEF', 'DSC_7335.NEF']
    
    
    {'0.005', '0.002', '0.003125'}
    [0.005, 0.003125, 0.002]
    
    Photos : 42          Bracketting : 3 expositions          Piles : 14
    Vitesses : ['1/200', '1/320', '1/500']
    Date prise de vue : 2023-06-19 15:54:33      Time pile 1 : 2023-06-19 15:00:00
    
    
    Traceback (most recent call last):
      File "/home/vieux_loup/Bureau/OpenClassRoom/HDRmergeCLI.py", line 92, in <module>
        from exiftool import ExifToolHelper
    ImportError: cannot import name 'ExifToolHelper' from 'exiftool' (/home/vieux_loup/.local/lib/python3.10/site-packages/exiftool.py)
    vieux_loup@Zalman:~$ python3 /home/vieux_loup/Bureau/OpenClassRoom/HDRmergeCLI.py 
    
    Dossier: /home/vieux_loup/Images/.Vorkflow/Travaux photos/Megeve 2023/Test batch hdrmerge/10 RAW
    
    ['DSC_7327.NEF', 'DSC_7328.NEF', 'DSC_7329.NEF', 'DSC_7330.NEF', 'DSC_7331.NEF', 'DSC_7332.NEF', 'DSC_7333.NEF', 'DSC_7334.NEF', 'DSC_7335.NEF', 'DSC_7336.NEF', 'DSC_7337.NEF', 'DSC_7338.NEF', 'DSC_7339.NEF', 'DSC_7340.NEF', 'DSC_7341.NEF', 'DSC_7342.NEF', 'DSC_7343.NEF', 'DSC_7344.NEF', 'DSC_7345.NEF', 'DSC_7346.NEF', 'DSC_7347.NEF', 'DSC_7348.NEF', 'DSC_7349.NEF', 'DSC_7350.NEF', 'DSC_7351.NEF', 'DSC_7352.NEF', 'DSC_7353.NEF', 'DSC_7354.NEF', 'DSC_7355.NEF', 'DSC_7356.NEF', 'DSC_7357.NEF', 'DSC_7358.NEF', 'DSC_7359.NEF', 'DSC_7360.NEF', 'DSC_7361.NEF', 'DSC_7362.NEF', 'DSC_7363.NEF', 'DSC_7364.NEF', 'DSC_7365.NEF', 'DSC_7366.NEF', 'DSC_7367.NEF', 'DSC_7368.NEF']
    
    
    ['DSC_7327.NEF', 'DSC_7328.NEF', 'DSC_7329.NEF', 'DSC_7330.NEF', 'DSC_7331.NEF', 'DSC_7332.NEF', 'DSC_7333.NEF', 'DSC_7334.NEF', 'DSC_7335.NEF']
    
    
    {'0.002', '0.003125', '0.005'}
    [0.005, 0.003125, 0.002]
    
    Photos : 42          Bracketting : 3 expositions          Piles : 14
    Vitesses : ['1/200', '1/320', '1/500']
    Date prise de vue : 2023-06-19 15:54:33      Time pile 1 : 2023-06-19 15:00:00
    
    
    Traceback (most recent call last):
      File "/home/vieux_loup/Bureau/OpenClassRoom/HDRmergeCLI.py", line 92, in <module>
        from exiftool import ExifToolHelper
    ImportError: cannot import name 'ExifToolHelper' from 'exiftool' (/home/vieux_loup/.local/lib/python3.10/site-packages/exiftool.py)
    vieux_loup@Zalman:~$ python3 /home/vieux_loup/Bureau/OpenClassRoom/HDRmergeCLI.py 
    
    Dossier: /home/vieux_loup/Images/.Vorkflow/Travaux photos/Megeve 2023/Test batch hdrmerge/10 RAW
    
    ['DSC_7327.NEF', 'DSC_7328.NEF', 'DSC_7329.NEF', 'DSC_7330.NEF', 'DSC_7331.NEF', 'DSC_7332.NEF', 'DSC_7333.NEF', 'DSC_7334.NEF', 'DSC_7335.NEF', 'DSC_7336.NEF', 'DSC_7337.NEF', 'DSC_7338.NEF', 'DSC_7339.NEF', 'DSC_7340.NEF', 'DSC_7341.NEF', 'DSC_7342.NEF', 'DSC_7343.NEF', 'DSC_7344.NEF', 'DSC_7345.NEF', 'DSC_7346.NEF', 'DSC_7347.NEF', 'DSC_7348.NEF', 'DSC_7349.NEF', 'DSC_7350.NEF', 'DSC_7351.NEF', 'DSC_7352.NEF', 'DSC_7353.NEF', 'DSC_7354.NEF', 'DSC_7355.NEF', 'DSC_7356.NEF', 'DSC_7357.NEF', 'DSC_7358.NEF', 'DSC_7359.NEF', 'DSC_7360.NEF', 'DSC_7361.NEF', 'DSC_7362.NEF', 'DSC_7363.NEF', 'DSC_7364.NEF', 'DSC_7365.NEF', 'DSC_7366.NEF', 'DSC_7367.NEF', 'DSC_7368.NEF']
    
    
    ['DSC_7327.NEF', 'DSC_7328.NEF', 'DSC_7329.NEF', 'DSC_7330.NEF', 'DSC_7331.NEF', 'DSC_7332.NEF', 'DSC_7333.NEF', 'DSC_7334.NEF', 'DSC_7335.NEF']
    
    
    {'0.003125', '0.002', '0.005'}
    [0.005, 0.003125, 0.002]
    
    Photos : 42          Bracketting : 3 expositions          Piles : 14
    Vitesses : ['1/200', '1/320', '1/500']
    Date prise de vue : 2023-06-19 15:54:33      Time pile 1 : 2023-06-19 15:00:00
    
    
    Directory :  /home/vieux_loup/Images/.Vorkflow/Travaux photos/Megeve 2023/Test batch hdrmerge/10 RAW
    i = DSC_7327.NEF
    Index = 0
    AddSec = 0
    2023-06-19 15:00:00
    DSC_7327.NEF
    <class 'str'>
    /home/vieux_loup/Images/.Vorkflow/Travaux photos/Megeve 2023/Test batch hdrmerge/10 RAW/DSC_7327.NEF
    <class 'str'>
    b'/home/vieux_loup/Images/.Vorkflow/Travaux photos/Megeve 2023/Test batch hdrmerge/10 RAW/DSC_7327.NEF'
    <class 'bytes'>
    Exif =  -DateTimeOriginal=2023-06-19 15:00:00DSC_7327.NEF
    <class 'str'>
    
    i = DSC_7328.NEF
    Index = 1
    AddSec = 0
    2023-06-19 15:00:00
    DSC_7328.NEF
    <class 'str'>
    /home/vieux_loup/Images/.Vorkflow/Travaux photos/Megeve 2023/Test batch hdrmerge/10 RAW/DSC_7328.NEF
    <class 'str'>
    b'/home/vieux_loup/Images/.Vorkflow/Travaux photos/Megeve 2023/Test batch hdrmerge/10 RAW/DSC_7328.NEF'
    <class 'bytes'>
    Exif =  -DateTimeOriginal=2023-06-19 15:00:00DSC_7328.NEF
    <class 'str'>
    
    i = DSC_7329.NEF
    Index = 2
    AddSec = 0
    2023-06-19 15:00:00
    DSC_7329.NEF
    <class 'str'>
    /home/vieux_loup/Images/.Vorkflow/Travaux photos/Megeve 2023/Test batch hdrmerge/10 RAW/DSC_7329.NEF
    <class 'str'>
    b'/home/vieux_loup/Images/.Vorkflow/Travaux photos/Megeve 2023/Test batch hdrmerge/10 RAW/DSC_7329.NEF'
    <class 'bytes'>
    Exif =  -DateTimeOriginal=2023-06-19 15:00:00DSC_7329.NEF
    <class 'str'>
    
    i = DSC_7330.NEF
    Index = 3
    AddSec = 10
    2023-06-19 15:00:10
    DSC_7330.NEF
    <class 'str'>
    /home/vieux_loup/Images/.Vorkflow/Travaux photos/Megeve 2023/Test batch hdrmerge/10 RAW/DSC_7330.NEF
    <class 'str'>
    b'/home/vieux_loup/Images/.Vorkflow/Travaux photos/Megeve 2023/Test batch hdrmerge/10 RAW/DSC_7330.NEF'
    <class 'bytes'>
    Exif =  -DateTimeOriginal=2023-06-19 15:00:10DSC_7330.NEF
    <class 'str'>
    # Etc ...
    vieux_loup@Zalman:~$ 
    

    ________________________________________________________________________________________

    with exiftool.ExifTool() as et:
        et.execute('$exif')     # TypeError: sequence item 1: expected a bytes-like object, str found
    

    Résultat :

    Voir ligne 141

    Comment remplacer DateTime & Nom fichier par des variables ?

    Comment déclarer les variables ?

    vieux_loup@Zalman:~$ python3 /home/vieux_loup/Bureau/OpenClassRoom/HDRmergeCLI_2.py 
    
    Dossier: /home/vieux_loup/Images/.Vorkflow/Travaux photos/Megeve 2023/Test batch hdrmerge/10 RAW
    
    ['DSC_7327.NEF', 'DSC_7328.NEF', 'DSC_7329.NEF', 'DSC_7330.NEF', 'DSC_7331.NEF', 'DSC_7332.NEF', 'DSC_7333.NEF', 'DSC_7334.NEF', 'DSC_7335.NEF', 'DSC_7336.NEF', 'DSC_7337.NEF', 'DSC_7338.NEF', 'DSC_7339.NEF', 'DSC_7340.NEF', 'DSC_7341.NEF', 'DSC_7342.NEF', 'DSC_7343.NEF', 'DSC_7344.NEF', 'DSC_7345.NEF', 'DSC_7346.NEF', 'DSC_7347.NEF', 'DSC_7348.NEF', 'DSC_7349.NEF', 'DSC_7350.NEF', 'DSC_7351.NEF', 'DSC_7352.NEF', 'DSC_7353.NEF', 'DSC_7354.NEF', 'DSC_7355.NEF', 'DSC_7356.NEF', 'DSC_7357.NEF', 'DSC_7358.NEF', 'DSC_7359.NEF', 'DSC_7360.NEF', 'DSC_7361.NEF', 'DSC_7362.NEF', 'DSC_7363.NEF', 'DSC_7364.NEF', 'DSC_7365.NEF', 'DSC_7366.NEF', 'DSC_7367.NEF', 'DSC_7368.NEF']
    
    
    ['DSC_7327.NEF', 'DSC_7328.NEF', 'DSC_7329.NEF', 'DSC_7330.NEF', 'DSC_7331.NEF', 'DSC_7332.NEF', 'DSC_7333.NEF', 'DSC_7334.NEF', 'DSC_7335.NEF']
    
    
    {'0.003125', '0.005', '0.002'}
    [0.005, 0.003125, 0.002]
    
    Photos : 42          Bracketting : 3 expositions          Piles : 14
    Vitesses : ['1/200', '1/320', '1/500']
    Date prise de vue : 2023-06-19 15:54:33      Time pile 1 : 2023-06-19 15:00:00
    
    
    Directory :  /home/vieux_loup/Images/.Vorkflow/Travaux photos/Megeve 2023/Test batch hdrmerge/10 RAW
    Traceback (most recent call last):
      File "/home/vieux_loup/Bureau/OpenClassRoom/HDRmergeCLI_2.py", line 141, in <module>
        et.execute('$exif')     # TypeError: sequence item 1: expected a bytes-like object, str found
      File "/home/vieux_loup/.local/lib/python3.10/site-packages/exiftool.py", line 221, in execute
        self._process.stdin.write(b"\n".join(params + (b"-execute\n",)))
    TypeError: sequence item 0: expected a bytes-like object, str found
    vieux_loup@Zalman:~$ 
    

    Infos système :

    vieux_loup@Zalman:~$ python3 /home/vieux_loup/Bureau/infos.py 
    système -> Linux
    jeu d'instructions -> 64bit
    distribution -> #104-Ubuntu SMP Tue Jan 9 15:25:40 UTC 2024
    version python -> 3.10.12
    vieux_loup@Zalman:~$ 

    Une âme charitable peut-elle me mettre sur la voie ?

    Merci d'avance

    Cordialement

    • Partager sur Facebook
    • Partager sur Twitter
      22 février 2024 à 6:39:00

      Salut, 

      Quand tu postes un code, épure-le, fais en sorte qu'il soit minimaliste et qu'il reproduise les erreurs (là, c'est un peu le boxon). :) 

      Pour ce qui est de ton premier souci, tu te mélanges un peu les pinceaux.

      Un exemple :

      import os
      from pathlib import Path
      
      file_path = "/home/diablo76/Images/Chat.hdr"
      print("Chemin du fichier image : ", file_path)
      
      file_dir = os.path.dirname(file_path)
      print("Répertoire du fichier image : ", file_dir)
      
      file_name = os.path.basename(file_path)
      print("Nom du fichier image :" , file_name)
      
      os.chdir(file_dir)
      print("chdir = ", os.getcwd())
      
      # Avec pathlib
      
      posix_path = Path(file_path)
      print("Répertoire du fichier image : ", posix_path.parent)
      print("Nom du fichier image :" , posix_path.name)
      
      os.chdir(posix_path.parent)
      print("chdir = ", os.getcwd())

      os.chdir() prend en argument un répertoire.

      Pour le deuxième problème ce n'est pas mieux :

      $exif

      est l'appel de la variable exif definie dans un script bash (shell, terminal, cmd), rien à voir avec Python.

      • Reproduis un exemple simpe à partir d'un seul fichier raw
      • Affiche la structure du dictionnaire retourné par :
      import exiftool
      
      file_path = "Chemin et nom de l'image"
      
      with exiftool.ExifToolHelper() as et:
          metadata = et.get_metadata(file_path)
          print(metadata)




      • Partager sur Facebook
      • Partager sur Twitter
        22 février 2024 à 13:33:22

        Bonjour Garkam,

        Merci pour le coup de pouce

        Script passé avec           with exiftool.ExifTool() as et:

        vieux_loup@Zalman:~$ python3 /home/vieux_loup/Bureau/Garkam.py
        Traceback (most recent call last):
          File "/home/vieux_loup/Bureau/Garkam.py", line 5, in <module>
            with exiftool.ExifToolHelper() as et:
        AttributeError: module 'exiftool' has no attribute 'ExifToolHelper'

        vieux_loup@Zalman:~$ python3 /home/vieux_loup/Bureau/Garkam.py
        {'SourceFile': '/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge/10_RAW/DSC_7327.NEF', 'ExifTool:ExifToolVersion': 12.4, 'File:FileName': 'DSC_7327.NEF', 'File:Directory': '/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge/10_RAW', 'File:FileSize': 30012246, 'File:FileModifyDate': '2023:06:19 17:54:34+02:00', 'File:FileAccessDate': '2024:02:22 13:00:03+01:00', 'File:FileInodeChangeDate': '2024:02:20 14:06:12+01:00', 'File:FilePermissions': 100755, 'File:FileType': 'NEF', 'File:FileTypeExtension': 'NEF', 'File:MIMEType': 'image/x-nikon-nef', 'File:ExifByteOrder': 'II', 'EXIF:Make': 'NIKON CORPORATION', 'EXIF:Model': 'NIKON D5500', 'EXIF:Orientation': 1, 'EXIF:Software': 'Ver.1.02', 'EXIF:ModifyDate': '2023:06:19 15:54:33', 'EXIF:Artist': '', 'EXIF:JpgFromRawStart': 1108480, 'EXIF:JpgFromRawLength': 3115056, 'EXIF:YCbCrPositioning': 2, 'EXIF:ImageWidth': 6016, 'EXIF:ImageHeight': 4016, 'EXIF:BitsPerSample': 14, 'EXIF:Compression': 34713, 'EXIF:PhotometricInterpretation': 32803, 'EXIF:StripOffsets': 4224000, 'EXIF:SamplesPerPixel': 1, 'EXIF:RowsPerStrip': 4016, 'EXIF:StripByteCounts': 25788246, 'EXIF:XResolution': 300, 'EXIF:YResolution': 300, 'EXIF:PlanarConfiguration': 1, 'EXIF:ResolutionUnit': 2, 'EXIF:CFARepeatPatternDim': '2 2', 'EXIF:CFAPattern2': '0 1 1 2', 'EXIF:SubfileType': 1, 'EXIF:OtherImageStart': 238080, 'EXIF:OtherImageLength': 870173, 'EXIF:ReferenceBlackWhite': '0 255 0 255 0 255', 'EXIF:Copyright': '', 'EXIF:ExposureTime': 0.003125, 'EXIF:FNumber': 8, 'EXIF:ExposureProgram': 1, 'EXIF:ISO': 100, 'EXIF:SensitivityType': 2, 'EXIF:CreateDate': '2023:06:19 15:54:33', 'EXIF:ExposureCompensation': 0, 'EXIF:MaxApertureValue': 1.74110112659225, 'EXIF:MeteringMode': 5, 'EXIF:LightSource': 9, 'EXIF:Flash': 16, 'EXIF:FocalLength': 35, 'EXIF:UserComment': '', 'EXIF:SubSecTime': 23, 'EXIF:SubSecTimeOriginal': 23, 'EXIF:SubSecTimeDigitized': 23, 'EXIF:SensingMethod': 2, 'EXIF:FileSource': 3, 'EXIF:SceneType': 1, 'EXIF:CFAPattern': '2 2 0 1 1 2', 'EXIF:CustomRendered': 0, 'EXIF:ExposureMode': 1, 'EXIF:WhiteBalance': 1, 'EXIF:DigitalZoomRatio': 1, 'EXIF:FocalLengthIn35mmFormat': 52, 'EXIF:SceneCaptureType': 0, 'EXIF:GainControl': 0, 'EXIF:Contrast': 0, 'EXIF:Saturation': 0, 'EXIF:Sharpness': 0, 'EXIF:SubjectDistanceRange': 0, 'EXIF:GPSVersionID': '2 3 0 0', 'EXIF:DateTimeOriginal': '2023:06:19 15:54:33', 'EXIF:TIFF-EPStandardID': '1 0 0 0', 'EXIF:JpgFromRaw': '(Binary data 3115056 bytes, use -b option to extract)', 'EXIF:OtherImage': '(Binary data 870173 bytes, use -b option to extract)', 'EXIF:ThumbnailTIFF': '(Binary data 57816 bytes, use -b option to extract)', 'XMP:CreatorTool': 'NIKON D5500 Ver.1.02    ', 'XMP:CreateDate': '2023:06:19 15:54:33.23', 'XMP:Rating': 0, 'MakerNotes:MakerNoteVersion': '0211', 'MakerNotes:Quality': 'RAW    ', 'MakerNotes:WhiteBalance': 'SUNNY       ', 'MakerNotes:FocusMode': 'AF-A  ', 'MakerNotes:FlashSetting': '            ', 'MakerNotes:FlashType': '                   ', 'MakerNotes:WhiteBalanceFineTune': '0 0', 'MakerNotes:WB_RBLevels': '2.05078125 1.40234375 1 1', 'MakerNotes:ProgramShift': 0, 'MakerNotes:ExposureDifference': 0, 'MakerNotes:Compression': 6, 'MakerNotes:XResolution': 300, 'MakerNotes:YResolution': 300, 'MakerNotes:ResolutionUnit': 2, 'MakerNotes:PreviewImageStart': 39540, 'MakerNotes:PreviewImageLength': 140000, 'MakerNotes:YCbCrPositioning': 2, 'MakerNotes:FlashExposureComp': 0, 'MakerNotes:ExternalFlashExposureComp': 0, 'MakerNotes:FlashExposureBracketValue': 0, 'MakerNotes:ExposureBracketValue': 0, 'MakerNotes:CropHiSpeed': '12 6016 4016 6016 4016 0 0', 'MakerNotes:ExposureTuning': 0, 'MakerNotes:SerialNumber': 2202064, 'MakerNotes:ColorSpace': 1, 'MakerNotes:VRInfoVersion': '0100', 'MakerNotes:VibrationReduction': 2, 'MakerNotes:VRMode': 0, 'MakerNotes:ActiveD-Lighting': 0, 'MakerNotes:PictureControlVersion': '0200', 'MakerNotes:PictureControlName': 'STANDARD', 'MakerNotes:PictureControlBase': 'STANDARD', 'MakerNotes:PictureControlAdjust': 0, 'MakerNotes:PictureControlQuickAdjust': 0, 'MakerNotes:Sharpness': 12, 'MakerNotes:Clarity': 4, 'MakerNotes:Contrast': 0, 'MakerNotes:Brightness': 0, 'MakerNotes:Saturation': 0, 'MakerNotes:Hue': 0, 'MakerNotes:FilterEffect': 255, 'MakerNotes:ToningEffect': 255, 'MakerNotes:ToningSaturation': 127, 'MakerNotes:TimeZone': 60, 'MakerNotes:DaylightSavings': 1, 'MakerNotes:DateDisplayFormat': 2, 'MakerNotes:ISO': 100, 'MakerNotes:ISOExpansion': 0, 'MakerNotes:ISO2': 100, 'MakerNotes:ISOExpansion2': 0, 'MakerNotes:VignetteControl': 3, 'MakerNotes:AutoDistortionControl': 1, 'MakerNotes:BlackLevel': '600 600 600 600', 'MakerNotes:ImageSizeRAW': 1, 'MakerNotes:LensType': 6, 'MakerNotes:Lens': '35 35 1.8 1.8', 'MakerNotes:FlashMode': 0, 'MakerNotes:ShootingMode': 49, 'MakerNotes:ContrastCurve': '(Binary data 578 bytes, use -b option to extract)', 'MakerNotes:ShotInfoVersion': '0235', 'MakerNotes:FirmwareVersion': 1.02, 'MakerNotes:NEFCompression': 4, 'MakerNotes:NoiseReduction': 'OFF ', 'MakerNotes:NEFLinearizationTable': '(Binary data 624 bytes, use -b option to extract)', 'MakerNotes:ColorBalanceVersion': '0224', 'MakerNotes:LensDataVersion': '0204', 'MakerNotes:ExitPupilPosition': 128, 'MakerNotes:AFAperture': 1.78179743628068, 'MakerNotes:FocusPosition': 4, 'MakerNotes:FocusDistance': 5.01187233627272, 'MakerNotes:FocalLength': 35.6359487256136, 'MakerNotes:LensIDNumber': 159, 'MakerNotes:LensFStops': 7.33333333333333, 'MakerNotes:MinFocalLength': 35.6359487256136, 'MakerNotes:MaxFocalLength': 35.6359487256136, 'MakerNotes:MaxApertureAtMinFocal': 1.78179743628068, 'MakerNotes:MaxApertureAtMaxFocal': 1.78179743628068, 'MakerNotes:MCUVersion': 161, 'MakerNotes:EffectiveMaxAperture': 1.78179743628068, 'MakerNotes:RawImageCenter': '0 0', 'MakerNotes:DateStampMode': 0, 'MakerNotes:RetouchHistory': 0, 'MakerNotes:ShutterCount': 8751, 'MakerNotes:FlashInfoVersion': '0107', 'MakerNotes:FlashSource': 0, 'MakerNotes:ExternalFlashFirmware': '0 0', 'MakerNotes:ExternalFlashZoomOverride': 0, 'MakerNotes:ExternalFlashStatus': 0, 'MakerNotes:ExternalFlashReadyState': 0, 'MakerNotes:FlashCompensation': 0, 'MakerNotes:FlashGNDistance': 0, 'MakerNotes:FlashGroupAControlMode': 0, 'MakerNotes:FlashGroupBControlMode': 0, 'MakerNotes:FlashGroupCControlMode': 0, 'MakerNotes:FlashGroupACompensation': 0, 'MakerNotes:FlashGroupBCompensation': 0, 'MakerNotes:FlashGroupCCompensation': 0, 'MakerNotes:VariProgram': '               ', 'MakerNotes:MultiExposureVersion': '0100', 'MakerNotes:MultiExposureMode': 0, 'MakerNotes:MultiExposureShots': 0, 'MakerNotes:MultiExposureAutoGain': 0, 'MakerNotes:HighISONoiseReduction': 4, 'MakerNotes:PowerUpTime': '0000:00:00 00:00:00', 'MakerNotes:AFInfo2Version': '0100', 'MakerNotes:ContrastDetectAF': 0, 'MakerNotes:AFAreaMode': 1, 'MakerNotes:PhaseDetectAF': 3, 'MakerNotes:PrimaryAFPoint': 1, 'MakerNotes:AFPointsUsed': '01 00 00 00 00', 'MakerNotes:ContrastDetectAFInFocus': 0, 'MakerNotes:FileInfoVersion': '0100', 'MakerNotes:MemoryCardNumber': 0, 'MakerNotes:DirectoryNumber': 223, 'MakerNotes:FileNumber': 7327, 'MakerNotes:RetouchInfoVersion': '0200', 'MakerNotes:RetouchNEFProcessing': -1, 'MakerNotes:SilentPhotography': 0, 'MakerNotes:PreviewImage': '(Binary data 140000 bytes, use -b option to extract)', 'Composite:Aperture': 8, 'Composite:BlueBalance': 1.40234375, 'Composite:CFAPattern': '2 2 0 1 1 2', 'Composite:ImageSize': '6016 4016', 'Composite:Megapixels': 24.160256, 'Composite:RedBalance': 2.05078125, 'Composite:ScaleFactor35efl': 1.48571428571429, 'Composite:ShutterSpeed': 0.003125, 'Composite:SubSecCreateDate': '2023:06:19 15:54:33.23', 'Composite:SubSecDateTimeOriginal': '2023:06:19 15:54:33.23', 'Composite:SubSecModifyDate': '2023:06:19 15:54:33.23', 'Composite:AutoFocus': 1, 'Composite:LensID': '9F 58 44 44 14 14 A1 06', 'Composite:LensSpec': '35 35 1.8 1.8 6', 'Composite:CircleOfConfusion': 0.0202234446540448, 'Composite:DOF': '3.02411371004219 14.6247865059519', 'Composite:FOV': '37.93946508638 3.44552700203495', 'Composite:FocalLength35efl': 52.0000000000001, 'Composite:HyperfocalDistance': 7.57165767847438, 'Composite:LightValue': 14.3219280948874}
        vieux_loup@Zalman:~$

        • Partager sur Facebook
        • Partager sur Twitter
          22 février 2024 à 13:34:51

          Dans ton 1er code os.chdir ne peut accéder qu'à un chemin existant (message de l'erreur), il ne créé pas les éventuels dossiers manquants du chemin; et je remarque que dans certains cas, il y a des espaces entre les mots et dans d'autres cas, des soulignés ("Test batch hdrmerge" "Test_batch _hdrmerge" sont 2 choses différentes)

          Dans l'autre cas, le message est aussi parlant :"expected a bytes-like object, str found" => la fonction attend un tableau de bytes or tu lui fournit une chaine de caractères. il faut décomposer ta chaine en tableau de bytes.
          Cependant si on regarde la doc (https://sylikc.github.io/pyexiftool/reference/1-exiftool.html#exiftool.ExifTool.execute), la fonction accepte aussi des chaines si on a défini la propriété encoding (exiftool.ExifTool.encoding quelques lignes au dessus). Sans l'avoir définit, on devrait pouvoir utiliser la fonction str.encode("xxx") des chaines ( "exemple".encode("UTF8") => retourne la chaine sous forme de tableau de bytes avec encodage UTF8.

          Le message d'erreur d'import est bizarre, essai de réinstaller exiftool selon la doc https://sylikc.github.io/pyexiftool/installation.html (tu dois avoir une vieille version)

          • Partager sur Facebook
          • Partager sur Twitter
            22 février 2024 à 15:14:26

            import os
            from pathlib import Path
            
            posix_path = Path('/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge/10_RAW')
            
            os.chdir(posix_path.parent)             # chdir =  /home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge
            
            print("chdir = ", os.getcwd())

            OK - 10_RAW étant le dossier contenant les RAW

            import os
            from pathlib import Path
            
            #Dossier_RAW = input("Input Dossier RAW : ")
            #print("Dossier RAW = ", Dossier_RAW)                    # Dossier RAW =  '/home/vieux_loup/Images/.Vorkflow/Travaux photos/Megeve_2023/Test batch hdrmerge/10_RAW'
            
            #file_dir = Dossier_RAW
            #print("A : " ,file_dir)                                 # A :  '/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge/10_RAW'
            
            posix_path = Path(input("Input Dossier RAW : "))
            print("B : " ,posix_path)                               # B :  '/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge/10_RAW'
            
            print("C : " ,posix_path.name)                          # C :  10_RAW'
            
            print("D : " ,posix_path.parent)                        # D :  '/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge
            
            os.chdir(posix_path.parent)
            # os.chdir('/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge')  # chdir =  /home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge
            
            
            print("chdir = ", os.getcwd())

            Résultat :  posix_path.parent renvoi le chemin sans ' à la fin

            vieux_loup@Zalman:~$ python3 /home/vieux_loup/Bureau/python_3.py 
            Input Dossier RAW : '/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge/10_RAW' 
            B :  '/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge/10_RAW' 
            C :  10_RAW' 
            D :  '/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge
            Traceback (most recent call last):
              File "/home/vieux_loup/Bureau/python_3.py", line 17, in <module>
                os.chdir(posix_path.parent)
            FileNotFoundError: [Errno 2] No such file or directory: "'/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge"
            vieux_loup@Zalman:~$ 
            




            • Partager sur Facebook
            • Partager sur Twitter
              22 février 2024 à 15:31:43

              bon bah tu as l'erreur là: le guillemet simple en trop au début du chemin que tu as rentré (en fait, tu n'as pas à mettre de guillemet à la saisie de ton chemin.

              Pour exiftool, je réitère que tu dois avoir une vielle version et donc il faut désinstaller celle que tu as et installé la plus récente cf mon lien dans ma réponse précédente) (ou alors trouver et consulter la doc de ta version d'exiftool => https://smarnach.github.io/pyexiftool/genindex.html )on voit qu'il n'y a pas d'ExifToolHelper dans cette version)

              • Partager sur Facebook
              • Partager sur Twitter
                22 février 2024 à 15:49:20

                Comment ça se fait qu'au premier lancement de :

                vieux_loup@Zalman:~$ python3 /home/vieux_loup/Bureau/Garkam.py

                tu as une erreur et au deuxième lancement le dictionnaire est affiché ???

                Après, les exemples que j'ai donnés, c'était qu'à partir d'un fichier image, on obtienne son répertoire, du coup, je ne suis pas sûr d'avoir tout compris.

                Que veux-tu faire, modifier les méta-données (exif) de toutes les images contenues dans un répertoire ???



                -
                Edité par Garkam 22 février 2024 à 15:56:35

                • Partager sur Facebook
                • Partager sur Twitter
                  22 février 2024 à 17:34:06

                  Suite umfred

                  ExifTool upload, donc ExifToolHelper opérationnel

                  vieux_loup@Zalman:~$ python3 -m pip install -U pyexiftool
                  Defaulting to user installation because normal site-packages is not writeable
                  Requirement already satisfied: pyexiftool in ./.local/lib/python3.10/site-packages (0.1)
                  Collecting pyexiftool
                    Downloading PyExifTool-0.5.6-py3-none-any.whl.metadata (11 kB)
                  Downloading PyExifTool-0.5.6-py3-none-any.whl (51 kB)
                     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 51.2/51.2 kB 200.0 kB/s eta 0:00:00
                  DEPRECATION: flatbuffers 1.12.1-git20200711.33e2d80-dfsg1-0.6 has a non-standard version number. pip 24.1 will enforce this behaviour change. A possible replacement is to upgrade to a newer version of flatbuffers or contact the author to suggest that they release a version with a conforming version number. Discussion can be found at https://github.com/pypa/pip/issues/12063
                  Installing collected packages: pyexiftool
                    Attempting uninstall: pyexiftool
                      Found existing installation: PyExifTool 0.1
                      Uninstalling PyExifTool-0.1:
                        Successfully uninstalled PyExifTool-0.1
                  Successfully installed pyexiftool-0.5.6
                  vieux_loup@Zalman:~$ 


                  Scrip allégé

                  import os
                  
                  #with exiftool.ExifToolHelper() as et:
                      #et.execute(b'-DateTimeOriginal=2022:01:01 01:00:00', b'DSC_7367.NEF')   # OK
                  
                  raw = '/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge/10_RAW/DSC_7327.NEF'
                  file = os.path.basename(raw)
                  print(file)         # DSC_7327.NEF
                  
                  import pyexiv2
                  
                  #md = pyexiv2.ImageMetadata('/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge/10_RAW/DSC_7327.NEF')
                  md = pyexiv2.ImageMetadata(raw)
                  md.read()
                  aperture = str(md['Exif.Photo.DateTimeOriginal'].value)
                  Date = ("{}".format(aperture))#
                  #print(date)               # NameError: name 'date' is not defined. Did you mean: 'Date'?
                  
                  from datetime import datetime, timedelta
                  Date_a = datetime.strptime(Date, "%Y-%m-%d %H:%M:%S")
                  print(Date_a)                   # 2023-06-19 15:54:33
                  DT = Date_a.replace(minute=0, second=0)
                  print(DT)                       # 2023-06-19 15:00:00
                  
                  exif = ("-DateTimeOriginal=" + str(DT) + ", " + str(file))
                  print(exif)                     # -DateTimeOriginal=2023-06-19 15:00:00, DSC_7327.NEF
                  
                  Exif2 = bytes(exif, 'utf-8')
                  print(Exif2)                    # b'-DateTimeOriginal=2023-06-19 15:00:00, DSC_7327.NEF'
                  
                  import exiftool
                  from exiftool import ExifToolHelper
                  
                  with exiftool.ExifToolHelper() as et:
                      et.execute(Exif2)

                  Résultat

                  vieux_loup@Zalman:~$ python3 /home/vieux_loup/Bureau/OpenClassRoom/umfred/umfred.py 
                  DSC_7327.NEF
                  2023-06-19 15:54:33
                  2023-06-19 15:00:00
                  -DateTimeOriginal=2023-06-19 15:00:00, DSC_7327.NEF
                  b'-DateTimeOriginal=2023-06-19 15:00:00, DSC_7327.NEF'
                  Traceback (most recent call last):
                    File "/home/vieux_loup/Bureau/OpenClassRoom/umfred/umfred.py", line 35, in <module>
                      et.execute(Exif2)
                    File "/home/vieux_loup/.local/lib/python3.10/site-packages/exiftool/helper.py", line 135, in execute
                      raise ExifToolExecuteError(self._last_status, self._last_stdout, self._last_stderr, str_bytes_params)
                  exiftool.exceptions.ExifToolExecuteError: execute returned a non-zero exit status: 1
                  vieux_loup@Zalman:~$ 





















                  • Partager sur Facebook
                  • Partager sur Twitter
                    22 février 2024 à 18:37:30

                    A priori le champ Exif DateTimeOriginal du format NEF (Nikon) n'est pas modifiable selon la norme Exif https://exiftool.org/TagNames/Nikon.html d'où certainement l'erreur d'exécution.
                    • Partager sur Facebook
                    • Partager sur Twitter
                      22 février 2024 à 18:38:48

                      Tu te compliques la vie, soit, tu utilises pyexiv2, soit pyexiftool mais pas les deux:

                      Un exemple qui modifie la date d'origine et qui devrait marcher chez toi :

                      import exiftool
                      from datetime import datetime
                      from time import sleep
                      
                      
                      file_path = "/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge/10_RAW/DSC_7327.NEF"
                      
                      with exiftool.ExifToolHelper() as et:
                          metadata = et.get_metadata(file_path)
                          now = datetime.strftime(datetime.now(), "%Y:%m:%d %H:%M:%S")
                          state = et.set_tags(
                              [file_path],
                              tags={"DateTimeOriginal": now},
                              params=["-P", "-overwrite_original"]
                          )
                          
                          print(state)
                          
                          sleep(2)
                          
                          for key, value in metadata.items():
                              print(key, value)



                      Edit:  @umfred, si c'est le cas dommage.... Mais comment on peut verrouiller une donnée exif dans un fichier ??

                      Je viens de faire l'essai avec une image provenant d'un Nikon D 70 et ça fonctionne.

                      -
                      Edité par Garkam 23 février 2024 à 10:10:56

                      • Partager sur Facebook
                      • Partager sur Twitter
                        22 février 2024 à 19:15:22

                        Garkam a écrit:

                        Edit:  @umfred, si c'est le cas dommage.... Mais comment on peut verrouiller une donnée exif dans un fichier ??

                        Je me suis peut-être trop avancé sur ce verrouillage, j'ai vu ensuite que le tag Exif.Photo.DateTimeOriginal était lui modifiable; donc au final c'est peut-être la définition du tag qui est erronée dans le code utilisant exiftool (sans doute le '-' devant le tag).

                        Avec pyexiv2 (https://github.com/LeoHsiao1/pyexiv2/blob/master/docs/Tutorial.md )

                        import pyexiv2
                         
                        with pyexiv2.Image(r'/home/vieux_loup/Images/.Vorkflow/Travaux photos/Test_batch_hdrmerge/10_RAW/DSC_7327.NEF') as img:
                            data = img.read_exif()
                            print("Avant:" + data['Exif.Photo.DateTimeOriginal'])
                            img.modify_exif({'Exif.Photo.DateTimeOriginal': '2024:02:22 18:00:00'})
                            print("Apres:" + img.read_exif()['Exif.Photo.DateTimeOriginal'])



                        -
                        Edité par umfred 22 février 2024 à 19:17:13

                        • Partager sur Facebook
                        • Partager sur Twitter
                          23 février 2024 à 15:28:58

                          Merci pour votre aide.

                          je vais pouvoir reprendre ce script plus proprement.

                          J'ai aussi trouvé ceci :

                          from your_class import ExifTool, fsencode
                          
                          with ExifTool(source) as et:
                              params = map(fsencode, ['-Title="%s"' % title, '%s' % source_file])
                              et.execute(*params)

                          https://stackoverflow.com/questions/27815719/editing-updating-the-data-of-photo-metadata-using-pyexiftool

                          Pas tester

                          • Partager sur Facebook
                          • Partager sur Twitter
                            23 février 2024 à 16:04:34

                            Ce que serait intéressant, c'est de savoir quels sont les tags que tu veux modifier, seulement DateTimeOriginal ?
                            • Partager sur Facebook
                            • Partager sur Twitter
                              23 février 2024 à 18:28:32

                              Seulement DateTimeOriginal

                              et même seulement minute et seconde

                              Soit un panorama déjà conséquent ( 50 prise de vue, chacune avec 3 expositions ), soit 50 piles de 3 images.

                              HDR merge crée une nouvelle pile dès lors que l’écart entre 2 photos dépasse 3 s (par défaut)

                              HDR merge crée une image brut.DNG (32 bits pour travailler en virgule flottante) à plage dynamique étendue, à partir de chaque pile d’images brut.

                              Dans le cas d’un panorama pris à main levée, le regroupement par piles peut être pris en défaut.

                              Objectif du script :

                              - Dénombrer le nombre d’expositions différentes (TAG : ExposureTime)

                              - Corriger minute et seconde de chaque image, pour assurer un regroupement par pile correct.

                              Soit BKT = Nombre d’expositions différentes

                              Soit DT : DateTime 1ére image (ex : 2023-06-19 15:54:33)

                              DTI : Initialisation DT (ex : 2023-06-19 15:30:00)

                              Pour chaque image je rajoute x s à DTI

                              Image 1 : index = 0 Add_Sec = i//BKT*10 = 0 DateTime image 1 : 2023-06-19 15:30:00

                              Image 2 : index = 1 Add_Sec = i//BKT*10 = 0 DateTime image 2 : 2023-06-19 15:30:00

                              Image 4 : index = 3 Add_Sec = i//BKT*10 = 10 DateTime image 4 : 2023-06-19 15:30:10

                              etc …

                              A la fin éditer une liste pour contrôle

                              [[30:00, 30:00, 30:00], [30:10, 30:10, 30:10], [30:20, etc.]]

                              Puis lancer HDR merge CLI : hdrmerge -v --batch -a -g 3 -b 32 --no-crop *.NEF

                              Evidemment, il convient d’utiliser la meilleure méthode tout au long du script.

                              Standard Exif Tags https://exiv2.org/tags.html

                              • Partager sur Facebook
                              • Partager sur Twitter

                              Script Python3 - os.chdir - exiftool

                              × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
                              • Editeur
                              • Markdown