fish-vista / download_and_process_nd_images.py
ksmehrab's picture
PR to add ND processing files and script (#3)
7804064 verified
import pandas as pd
import requests
from PIL import Image
from io import BytesIO
import os
from tqdm import tqdm
import json
import argparse
parser = argparse.ArgumentParser(description='Download, process and save ND images')
parser.add_argument('--save_dir', type=str, help='The directory where processed images will be saved')
args = parser.parse_args()
save_dir = args.save_dir
if not os.path.exists('ND_Processing_Files'):
raise Exception('The ND processing file directory is not found in your current working directory')
if not os.path.exists(save_dir):
os.mkdir(save_dir)
nd_df = pd.read_csv(os.path.join('ND_Processing_Files', 'ND_data.csv'))
with open(os.path.join('ND_Processing_Files', 'nd_filenames_bboxes_map.json'), 'r') as f:
nd_filenames_bboxes_map = json.load(f)
seg_mask_dir = os.path.join('ND_Processing_Files', 'ND_background_masks')
padding = 20
for i, row in tqdm(nd_df.iterrows()):
target_filename = row['filename']
download_url = row['original_url']
local_filename = 'temp.jpg'
response = requests.get(download_url)
# Ensure the request was successful
response.raise_for_status()
# Convert response content to a PIL Image
image = Image.open(BytesIO(response.content))
target_bbox = nd_filenames_bboxes_map[target_filename]
# crop the image
left, upper, right, lower = target_bbox
max_width, max_height = image.size
padded_left = max(left - padding, 0)
padded_upper = max(upper - padding, 0)
padded_right = min(right + padding, max_width)
padded_lower = min(lower + padding, max_height)
# Crop the image using the adjusted, padded bounding box
cropped_image = image.crop((padded_left, padded_upper, padded_right, padded_lower))
assert target_filename[-4] == '.', 'The code assumes we have .<extension> at the end'
target_seg_mask_file = target_filename[:-4]+'.png'
if target_seg_mask_file in os.listdir(seg_mask_dir):
mask_image = Image.open(os.path.join(seg_mask_dir, target_seg_mask_file)).convert('L')
else:
print(f'Segmentation mask not found for target image {target_filename}. Skipping...')
continue
white_image = Image.new("RGB", cropped_image.size, (255, 255, 255))
result_image = Image.composite(cropped_image, white_image, mask_image)
result_image.save(os.path.join(save_dir, target_filename))