|
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): |
|
|
|
os.makedirs(base_image_folder, exist_ok=True) |
|
os.makedirs(segmented_image_folder, exist_ok=True) |
|
|
|
|
|
with open(output_csv, 'w', newline='') as csvfile: |
|
fieldnames = ['base_image', 'segmented_image', 'description'] |
|
writer = csv.DictWriter(csvfile, fieldnames=fieldnames) |
|
writer.writeheader() |
|
|
|
|
|
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") |
|
|
|
|
|
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_image_from_url(image_url) |
|
shutil.move('segmented_image.png', segmented_image_file) |
|
|
|
|
|
writer.writerow({'base_image': base_image_file, 'segmented_image': segmented_image_file, 'description': report}) |
|
|
|
|
|
|
|
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) |