birgermoell
commited on
Commit
•
a70948b
1
Parent(s):
85b09d0
Create data_loading.py
Browse files- data_loading.py +49 -0
data_loading.py
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import csv
|
3 |
+
import shutil
|
4 |
+
import json
|
5 |
+
from sam_api import segment_image_from_url
|
6 |
+
import requests
|
7 |
+
|
8 |
+
def process_data(data, output_csv, base_image_folder, segmented_image_folder):
|
9 |
+
# Create the folders for base and segmented images if they don't exist
|
10 |
+
os.makedirs(base_image_folder, exist_ok=True)
|
11 |
+
os.makedirs(segmented_image_folder, exist_ok=True)
|
12 |
+
|
13 |
+
# Open the CSV file and write the header
|
14 |
+
with open(output_csv, 'w', newline='') as csvfile:
|
15 |
+
fieldnames = ['base_image', 'segmented_image', 'description']
|
16 |
+
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
|
17 |
+
writer.writeheader()
|
18 |
+
|
19 |
+
# Iterate through the dataset
|
20 |
+
for row in data['rows']:
|
21 |
+
image_url = row['row']['image']['src']
|
22 |
+
report = row['row']['report'].strip("b'")
|
23 |
+
base_image_file = os.path.join(base_image_folder, f"base_image_{row['row_idx']}.jpg")
|
24 |
+
segmented_image_file = os.path.join(segmented_image_folder, f"segmented_image_{row['row_idx']}.png")
|
25 |
+
|
26 |
+
# Download and save the base image
|
27 |
+
response = requests.get(image_url, stream=True)
|
28 |
+
with open(base_image_file, 'wb') as out_file:
|
29 |
+
shutil.copyfileobj(response.raw, out_file)
|
30 |
+
del response
|
31 |
+
|
32 |
+
# Segment the image and save it
|
33 |
+
_ = segment_image_from_url(image_url)
|
34 |
+
shutil.move('segmented_image.png', segmented_image_file)
|
35 |
+
|
36 |
+
# Write the data to the CSV file
|
37 |
+
writer.writerow({'base_image': base_image_file, 'segmented_image': segmented_image_file, 'description': report})
|
38 |
+
|
39 |
+
# Example usage
|
40 |
+
# Load the data from the JSON file
|
41 |
+
with open('data.json', 'r') as json_file:
|
42 |
+
data = json.load(json_file)
|
43 |
+
|
44 |
+
|
45 |
+
output_csv = 'output.csv'
|
46 |
+
base_image_folder = 'base_images'
|
47 |
+
segmented_image_folder = 'segmented_images'
|
48 |
+
|
49 |
+
process_data(data, output_csv, base_image_folder, segmented_image_folder)
|