Search code examples
python-3.xpython-imaging-library

Python3 PIL Error creating an image: cannot identify image file


code

from io import StringIO
import subprocess
import os
import time
from datetime import datetime
from PIL import Image
import subprocess


def captureTestImage(settings, width, height):
    command = "libcamera-still --width {} --height {} --autofocus-on-capture 1 -q 75 --tuning-file /usr/share/libcamera/ipa/rpi/vc4/imx708_wide.json -o DAY-AF1-q75--tuningfile-imx708_wide-06-21-2024-16-15-20.jpg".format(width, height)
    subprocess.run(command[0],shell=True,executable="/usr/bin/bash")
    imageData = StringIO()
    imageData.write(subprocess.check_output(command, shell=True))
    imageData.seek(0)
    im = Image.open(imageData)
    buffer = im.load()
    imageData.close()
    return im, buffer

actual error receiving:

Still capture image received

    im = Image.open(imageData)
  File "/home/user/.local/lib/python3.9/site-packages/PIL/Image.py", line 3339, in open
    raise UnidentifiedImageError(msg)
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f9df4db80>

What is going wrong here?

This is creating an actual image file, but the script is returning this error- why? How can I fix? Thank you


Solution

  • I don't understand why you are making it so complicated. I think the code below should be sufficient for what you are trying to do - if not, please say what functionality it is missing so I can better assist:

    #!/usr/bin/env python3
    
    import subprocess as sp
    
    # Define parameters for libcamera command
    width, height = 640, 480
    filename = 'image.jpg'
    
    # Flesh out libcamera command
    cmd = [
       '/usr/bin/libcamera-still',
       '--width', f'{width}',
       '--height', f'{height}',
       '--autofocus-on-capture', '1',
       '-q', '75',
       '--tuning-file', '/usr/share/libcamera/ipa/rpi/vc4/imx708_wide.json',
       '-o', filename
       ] 
    
    # Run libcamera command to create image.jpg
    sp.run(cmd)
    
    # Open image.jpg with Pillow
    im = Image.open(filename)