medical-diffusion-sam / data_loading.py
birgermoell's picture
Create data_loading.py
a70948b
raw
history blame
1.91 kB
import os
import csv
import shutil
import json
from sam_api import segment_image_from_url
import requests
def process_data(data, output_csv, base_image_folder, segmented_image_folder):
# Create the folders for base and segmented images if they don't exist
os.makedirs(base_image_folder, exist_ok=True)
os.makedirs(segmented_image_folder, exist_ok=True)
# Open the CSV file and write the header
with open(output_csv, 'w', newline='') as csvfile:
fieldnames = ['base_image', 'segmented_image', 'description']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
# Iterate through the dataset
for row in data['rows']:
image_url = row['row']['image']['src']
report = row['row']['report'].strip("b'")
base_image_file = os.path.join(base_image_folder, f"base_image_{row['row_idx']}.jpg")
segmented_image_file = os.path.join(segmented_image_folder, f"segmented_image_{row['row_idx']}.png")
# Download and save the base image
response = requests.get(image_url, stream=True)
with open(base_image_file, 'wb') as out_file:
shutil.copyfileobj(response.raw, out_file)
del response
# Segment the image and save it
_ = segment_image_from_url(image_url)
shutil.move('segmented_image.png', segmented_image_file)
# Write the data to the CSV file
writer.writerow({'base_image': base_image_file, 'segmented_image': segmented_image_file, 'description': report})
# Example usage
# Load the data from the JSON file
with open('data.json', 'r') as json_file:
data = json.load(json_file)
output_csv = 'output.csv'
base_image_folder = 'base_images'
segmented_image_folder = 'segmented_images'
process_data(data, output_csv, base_image_folder, segmented_image_folder)