Created
June 17, 2023 02:50
-
-
Save trojblue/7f9b690337228e92a2ab1c47a9b667a1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# use in a ipynb notebook | |
import os | |
from PIL import Image | |
from IPython.core.display import HTML, display as disp | |
import io | |
import base64 | |
# Disable truncating of text | |
pd.set_option('display.max_colwidth', None) | |
def display_images(root_dir, csv_filepath): | |
# Read csv file into a pandas DataFrame | |
df = pd.read_csv(csv_filepath) | |
for _, row in df[:5].iterrows(): | |
filename = row['filename'] | |
if not os.path.isabs(filename): | |
image_filepath = os.path.join(root_dir, filename) | |
else: | |
image_filepath = filename | |
if os.path.exists(image_filepath) and image_filepath.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif')): | |
try: | |
# Open image with PIL | |
pil_im = Image.open(image_filepath) | |
# Convert PIL image to base64-encoded image | |
image_data = io.BytesIO() | |
pil_im.save(image_data, format='PNG') | |
base64_image = base64.b64encode(image_data.getvalue()).decode('utf-8') | |
# Display image and text | |
image_html = f"<img style='width: 400px; margin:0px; float: left; border: 1px solid black;' src='data:image/png;base64,{base64_image}' />" | |
data_html = f"<div style='margin-left: 420px; border: 1px solid black;'>{row.to_frame().to_html()}</div>" | |
final_html = image_html + data_html | |
disp(HTML(final_html)) | |
except Exception as e: | |
print(f"Failed to display image {image_filepath}. Error: {e}") | |
else: | |
print(f"File {image_filepath} does not exist or is not a valid image file") | |
# Usage | |
root_dir = r"D:\Andrew\Downloads\demo" | |
csv_filepath = r"D:\Andrew\Downloads\demo\metrics.csv" | |
display_images(root_dir, csv_filepath) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment