NeuroCognition-RAPM / scripts /render_raven_images.py
haznitrama's picture
Add RAVEN image rendering script
bd5831c verified
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import os
import json
import glob
def create_visualization(images, target, output_path_full, output_path_problem, output_path_choices):
"""Create visualization and save as separate images"""
# Create full combined figure
fig = plt.figure(figsize=(8, 12), dpi=150)
# Problem Matrix (3x3 grid in the top section, properly centered)
for i in range(9):
row = i // 3
col = i % 3
ax = plt.subplot2grid((8, 5), (row, col + 1), fig=fig, colspan=1, rowspan=1)
if i < 8:
ax.imshow(images[i], cmap='gray')
rect = Rectangle((0, 0), 1, 1, linewidth=2, edgecolor='black', facecolor='none', transform=ax.transAxes)
ax.add_patch(rect)
ax.axis("off")
else:
white_bg = np.ones_like(images[0]) * 255
ax.imshow(white_bg, cmap='gray', vmin=0, vmax=255)
ax.text(0.5, 0.5, "?", fontsize=40, ha='center', va='center', color='black', fontweight='bold', transform=ax.transAxes)
rect = Rectangle((0, 0), 1, 1, linewidth=2, edgecolor='black', facecolor='none', transform=ax.transAxes)
ax.add_patch(rect)
ax.axis("off")
plt.figtext(0.5, 0.93, "Problem Matrix", fontsize=18, ha='center', fontweight='bold')
# Answer Set (2x4 grid in the bottom section)
for i in range(8):
row = i // 4
col = i % 4
ax = plt.subplot2grid((7, 6), (3 + row, col + 1), fig=fig, colspan=1, rowspan=1)
ax.imshow(images[8 + i], cmap='gray')
rect = Rectangle((0, 0), 1, 1, linewidth=2, edgecolor='black', facecolor='none', transform=ax.transAxes)
ax.add_patch(rect)
ax.set_title(str(i + 1), fontsize=16)
ax.axis("off")
if i == target:
ax.set_xlabel("Correct", color="red", fontsize=12)
plt.figtext(0.5, 0.565, "Answer Choices", fontsize=18, ha='center', fontweight='bold')
plt.subplots_adjust(left=0.05, right=0.95, top=0.92, bottom=0.05, wspace=0.05, hspace=0.15)
plt.savefig(output_path_full, dpi=300, bbox_inches='tight')
plt.close(fig)
# Create problem matrix only
fig, axes = plt.subplots(3, 3, figsize=(6, 6), dpi=150)
for i in range(9):
ax = axes[i // 3, i % 3]
if i < 8:
ax.imshow(images[i], cmap='gray')
rect = Rectangle((0, 0), 1, 1, linewidth=2, edgecolor='black', facecolor='none', transform=ax.transAxes)
ax.add_patch(rect)
ax.axis("off")
else:
white_bg = np.ones_like(images[0]) * 255
ax.imshow(white_bg, cmap='gray', vmin=0, vmax=255)
ax.text(0.5, 0.5, "?", fontsize=40, ha='center', va='center', color='black', fontweight='bold', transform=ax.transAxes)
rect = Rectangle((0, 0), 1, 1, linewidth=2, edgecolor='black', facecolor='none', transform=ax.transAxes)
ax.add_patch(rect)
ax.axis("off")
plt.suptitle("Problem Matrix", fontsize=18, fontweight='bold')
plt.tight_layout()
plt.savefig(output_path_problem, dpi=300, bbox_inches='tight')
plt.close(fig)
# Create answer choices only
fig, axes = plt.subplots(2, 4, figsize=(8, 4), dpi=150)
for i in range(8):
ax = axes[i // 4, i % 4]
ax.imshow(images[8 + i], cmap='gray')
rect = Rectangle((0, 0), 1, 1, linewidth=2, edgecolor='black', facecolor='none', transform=ax.transAxes)
ax.add_patch(rect)
ax.set_title(str(i + 1), fontsize=16)
ax.axis("off")
if i == target:
ax.set_xlabel("Correct", color="red", fontsize=12)
plt.suptitle("Answer Choices", fontsize=18, fontweight='bold')
plt.tight_layout()
plt.savefig(output_path_choices, dpi=300, bbox_inches='tight')
plt.close(fig)
# Create output directory
output_dir = "./../RAPM"
images_dir = os.path.join(output_dir, "images")
os.makedirs(images_dir, exist_ok=True)
# Initialize data list
evaluation_data = []
# Process all subdirectories in RAVEN-10000
raven_dir = "./../RAVEN-10000"
for dataset_type in os.listdir(raven_dir):
dataset_path = os.path.join(raven_dir, dataset_type)
if not os.path.isdir(dataset_path):
continue
print(f"Processing dataset: {dataset_type}")
# Find all test .npz files
test_files = glob.glob(os.path.join(dataset_path, "*test*.npz"))
for npz_file in test_files:
filename = os.path.basename(npz_file)
file_id = filename.replace('.npz', '')
print(f" Processing: {filename}")
# Load data
data = np.load(npz_file)
images = data['image']
target = data['target']
# Create output filenames
full_image_name = f"{file_id}_{dataset_type}_full.png"
problem_image_name = f"{file_id}_{dataset_type}_problem.png"
choices_image_name = f"{file_id}_{dataset_type}_choices.png"
# Create full paths
full_image_path = os.path.join(images_dir, full_image_name)
problem_image_path = os.path.join(images_dir, problem_image_name)
choices_image_path = os.path.join(images_dir, choices_image_name)
# Generate visualizations
create_visualization(images, target, full_image_path, problem_image_path, choices_image_path)
# Create data entry
data_entry = {
"id": f"{file_id}_{dataset_type}",
"dataset_type": dataset_type,
"problem_matrix_image": f"images/{problem_image_name}",
"answer_choices_image": f"images/{choices_image_name}",
"full_image": f"images/{full_image_name}",
"correct_answer": int(target)
}
evaluation_data.append(data_entry)
# Save JSON file
json_output_path = os.path.join(output_dir, "raven_evaluation_data.json")
with open(json_output_path, 'w') as f:
json.dump({"questions": evaluation_data}, f, indent=2)
print(f"\nProcessing complete!")
print(f"Total questions processed: {len(evaluation_data)}")
print(f"JSON file saved to: {json_output_path}")
print(f"Images saved to: {images_dir}")