Inquiry about image to table by using Python Script node

Hello.

I want to draw several plt charts with python script nodes and make them into table rows.
But I don’t know how I can convert the plt charts to table row images.

Here is how I tried to do it.
But I get a type error.
ValueError: Data type 'binary' in column 'image' is not supported in KNIME Python. Please use a different data type.

And I read the image using python script node to check the type.
"org.knime.core.data.image.png.PNGImageValueFactory"

Is it possible to convert a plt chart to this type?

The reason I am trying this is to output multiple images as a table, because python script node can only output one image.

I’d appreciate it if someone could help me :slight_smile :slight_smile:

Best regards,
hhkim

python_image_test.knwf (77.0 KB)

Hi,

in the past I had the same question. I came a across that saving the images to a local folder in the python script and loading them afterwards was the best way.

What I did:

  • Use “extract context properties” and search for “context.workflow.temp.location”
  • pass this to the python node and use this as the folder to store the files
  • create proper filenames and write images in python node
  • pass image location via pandas dataframe to KNIME
  • use “string to Path” and “Path to URI” to prepare the usage of
  • “Read Images” to read the images you just created into a table
  • delete images from the folder with the last node "Delete Files/Folders (Table)

Here you can find my example

2 Likes

Hi @hhkim,
You can export images in the output table by adding a pillow Image object to the table. Try this:

import knime.scripting.io as knio
import matplotlib.pyplot as plt
from io import BytesIO
from PIL import Image
import pandas as pd

# Example data for plotting
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]

# Create a simple line plot
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title("Example Plot")
ax.set_xlabel("X axis")
ax.set_ylabel("Y axis")

# Save the plot to a BytesIO buffer in PNG format
buf = BytesIO()
plt.savefig(buf, format='png')
plt.close(fig)
buf.seek(0)

# --- IMPORTANT PART: wrap the image as a PIL.Image object ---
img = Image.open(buf)
# ------------------------------------------------------------

# Create a DataFrame with the image in a column
# The column must contain PIL.Image objects for KNIME to recognize them as images
df = pd.DataFrame({"Image (PIL)": [img]})

# Output the table to KNIME
knio.output_tables[0] = knio.Table.from_pandas(df)
4 Likes

Thank you so much for sharing this great method.

I just tried this and it works fine.

Have a good day!

@hhkim another option could be to use SQLite to store images. Does also work with Phyton.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.