Home > database >  Using Python, access SQL database table field with stored path to get Image
Using Python, access SQL database table field with stored path to get Image

Time:08-01

I have many combinations of the following Python code, the data is stored in a Microsoft local SQL database, which has a table & field with a path & name of a image to load.

Here is the code:

import pyodbc
from PIL import Image

# Trusted Connection to Named Instance
connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=localhost;DATABASE=MorthoAI;Trusted_Connection=yes;')
cursor=connection.cursor()

cursor.execute("SELECT TOP (1) [Id],[MorthoImagePath] ,[MorthoHipFemurSize]  FROM [MorthoAI].[dbo].[MorthoImagePathFemurSize20Rows]")
while 1:
    row = cursor.fetchone()
    if not row:
        break
    print(row.MorthoImagePath)

    filename = row.MorthoImagePath
    print(filename)

    with Image.open(filename) as image:
            width, height = image.size
cursor.close()
connection.close()

Here is the data: 'C:\dir1\DX PELVIS 1 OR 2 VIEWS LOW AP PELVIS PELVIS FROG BILAT 0001.jpg'

Here is the error happening:

C:\ProgramData\Anaconda3\envs\TF29Py39\python.exe C:/github/murphymj5209/MorthoEntTraining/main.py
Traceback (most recent call last):
  File "C:\github\murphymj5209\MorthoEntTraining\main.py", line 18, in <module>
    with Image.open(filename) as image:
  File "C:\ProgramData\Anaconda3\envs\TF29Py39\lib\site-packages\PIL\Image.py", line 3092, in open
    fp = builtins.open(filename, "rb")
OSError: [Errno 22] Invalid argument: "'C:\\dir1\\DX PELVIS 1 OR 2 VIEWS LOW AP PELVIS PELVIS FROG BILAT 0001.jpg'"
'C:\dir1\DX PELVIS 1 OR 2 VIEWS LOW AP PELVIS PELVIS FROG BILAT 0001.jpg'
'C:\dir1\DX PELVIS 1 OR 2 VIEWS LOW AP PELVIS PELVIS FROG BILAT 0001.jpg'

Process finished with exit code 1

Let me know if you have an idea of why this happening. thanks ahead

CodePudding user response:

It looks like the filename is repeated multiple times in the filename variable. The error has the path once quoted and twice without quotes.

CodePudding user response:

As you suggested, I took out the single quotes in my sql table and it worked

  • Related