tiny-presence-detection / load_and_process_coco.py
slamanigg's picture
Upload load_and_process_coco.py
564fb07 verified
Raw
History Blame Contribute Delete
14 kB
import os
import tensorflow as tf
import tensorflow_datasets as tfds
import matplotlib.pyplot as plt
from datasets import Dataset, Features, Image, Sequence, Value
# --- Configuration ---
TARGET_SIZE = 32 # downsample the images to TARGET_SIZE x TARGET_SIZE
MIN_BOX_AREA_PIXELS = int(0.85*TARGET_SIZE)**2 # minimum area in px, that a depicted person must occupy to be included in the dataset.
CHANNELS = 3 # use 1 for grayscale
OUTLIER_PERCENTAGE = 0.001 # 2% of images will become extreme outliers
def crop_to_bbox_center(image, boxes, labels, target_size=TARGET_SIZE):
"""
Crops an image based on the largest person bounding box.
If no person is present, performs a default central crop.
Args:
image: 3D Tensor (H, W, C)
boxes: 2D Tensor (N, 4) in normalized coordinates [ymin, xmin, ymax, xmax]
labels: 1D Tensor (N,) containing class IDs (0 for person)
target_size: Int, the final resized dimension
"""
image_shape = tf.shape(image)
h = tf.cast(image_shape[0], tf.float32)
w = tf.cast(image_shape[1], tf.float32)
# 1. Mask for 'person' class (label == 0)
person_mask = tf.equal(labels, 0)
has_person = tf.reduce_any(person_mask)
def crop_with_person():
# Filter boxes to only include people
person_boxes = tf.boolean_mask(boxes, person_mask)
# Calculate areas: (ymax - ymin) * (xmax - xmin)
box_heights = person_boxes[:, 2] - person_boxes[:, 0]
box_widths = person_boxes[:, 3] - person_boxes[:, 1]
areas = box_heights * box_widths
# Find the index of the largest person box
largest_idx = tf.argmax(areas)
best_box = person_boxes[largest_idx]
# Convert normalized coordinates to absolute pixels
ymin = best_box[0] * h
xmin = best_box[1] * w
ymax = best_box[2] * h
xmax = best_box[3] * w
# Determine square crop size based on the largest dimension of the box
side = tf.maximum(ymax - ymin, xmax - xmin)
# Ensure side isn't larger than the image canvas itself
side = tf.minimum(side, tf.minimum(h, w))
# Calculate center coordinates of the target box
center_y = (ymin + ymax) / 2.0
center_x = (xmin + xmax) / 2.0
# Calculate top-left corner of the crop square
crop_ymin = center_y - (side / 2.0)
crop_xmin = center_x - (side / 2.0)
# Clamp to ensure the crop window stays completely inside the image boundaries
crop_ymin = tf.clip_by_value(crop_ymin, 0.0, h - side)
crop_xmin = tf.clip_by_value(crop_xmin, 0.0, w - side)
return crop_ymin, crop_xmin, side
def crop_anywhere():
# Fallback if no person: default to a center crop spanning the shortest side
side = tf.minimum(h, w)
crop_ymin = (h - side) / 2.0
crop_xmin = (w - side) / 2.0
return crop_ymin, crop_xmin, side
# Dynamically choose the cropping window coordinates based on condition
crop_ymin, crop_xmin, side = tf.cond(has_person, crop_with_person, crop_anywhere)
# Perform the physical crop
cropped_image = tf.image.crop_to_bounding_box(
image,
tf.cast(crop_ymin, tf.int32),
tf.cast(crop_xmin, tf.int32),
tf.cast(side, tf.int32),
tf.cast(side, tf.int32)
)
# Resize to final target dimensions
final_image = tf.image.resize(cropped_image, [target_size, target_size])
return final_image, boxes
def prepare_data(example):
""" Apply cropping and preserve labels. """
image = example['image']
boxes = example['objects']['bbox']
labels = example['objects']['label']
image, boxes = crop_to_bbox_center(image, boxes, labels)
# Set color space
if CHANNELS == 1:
image = tf.image.rgb_to_grayscale(image)
elif CHANNELS == 3:
pass
else:
raise ValueError(f"Unsupported CHANNELS value: {CHANNELS}. Expected 1 or 3.")
image = tf.cast(image, tf.uint8)
labels = tf.cast(labels, tf.uint8)
return {'image': image, 'bbox': boxes, 'label': labels}
def filter_small_persons(example, target_size=TARGET_SIZE, min_box_area=MIN_BOX_AREA_PIXELS):
"""
Keep image if AT LEAST ONE person is larger than the threshold post-crop.
If the image contains no people at all, keep it as is.
"""
labels = example['objects']['label']
boxes = example['objects']['bbox'] # [ymin, xmin, ymax, xmax] (normalized)
is_person = tf.equal(labels, 0)
person_boxes = tf.boolean_mask(boxes, is_person)
has_persons = tf.greater(tf.shape(person_boxes)[0], 0)
def process_person_images():
image_shape = tf.shape(example['image'])
h = tf.cast(image_shape[0], tf.float32)
w = tf.cast(image_shape[1], tf.float32)
# 1. Calculate individual absolute box areas to find the single largest one
box_heights_normalized = person_boxes[:, 2] - person_boxes[:, 0]
box_widths_normalized = person_boxes[:, 3] - person_boxes[:, 1]
# Absolute dimensions for area calculation
box_heights_orig = box_heights_normalized * h
box_widths_orig = box_widths_normalized * w
areas_orig = box_heights_orig * box_widths_orig
# 2. Replicate the NEW cropping logic: Find the SINGLE largest person box
largest_idx = tf.argmax(areas_orig)
best_box = person_boxes[largest_idx]
# Convert the single largest box to absolute pixels
ymin = best_box[0] * h
xmin = best_box[1] * w
ymax = best_box[2] * h
xmax = best_box[3] * w
# The side length depends ONLY on this largest person box
side = tf.maximum(ymax - ymin, xmax - xmin)
side = tf.minimum(side, tf.minimum(h, w))
# 3. Project ALL person boxes into the final target resolution based on this side length
scale_factor = target_size / side
final_box_heights = box_heights_orig * scale_factor
final_box_widths = box_widths_orig * scale_factor
# Calculate final resolution pixel areas
final_box_areas = final_box_heights * final_box_widths
# Check if any individual person meets or exceeds the threshold
is_big_enough = final_box_areas >= min_box_area
# Keep the image if AT LEAST ONE person is big enough post-crop
return tf.reduce_any(is_big_enough)
# If there are no people, return True to keep the image untouched.
return tf.cond(has_persons, process_person_images, lambda: tf.constant(True))
def visualize_dataset(dataset, num_images=20):
""" Display a portion of random images and person images. """
# Top row: Grab the first 10 processed images sequentially
top_row_ds = dataset.take(num_images)
# Bottom row: Since labels are preserved, we filter for elements containing a person (0)
bottom_row_ds = dataset.filter(lambda x: tf.reduce_any(tf.equal(x['label'], 0))).take(num_images)
fig, axes = plt.subplots(2, num_images, figsize=(18, 5))
# Row 1: Random Samples
for i, example in enumerate(top_row_ds):
img = example['image']
axes[0, i].imshow(img)
axes[0, i].set_title(f"Random {i + 1}", fontsize=9)
axes[0, i].axis('off')
# Row 2: Person Samples
for i, example in enumerate(bottom_row_ds):
img = example['image']
axes[1, i].imshow(img)
axes[1, i].set_title(f"Person {i + 1}", fontsize=9)
axes[1, i].axis('off')
plt.tight_layout()
plt.show()
def save_dataset_to_hf_format(tf_dataset, target_size, export_dir=None):
"""
Converts a processed tf.data.Dataset into a universally accessible
Hugging Face Parquet dataset on disk.
"""
print("Converting TensorFlow dataset to standard arrays...")
images_list = []
bboxes_list = []
labels_list = []
# Stream the elements out of the TF pipeline into memory
for example in tf_dataset:
images_list.append(example['image'].numpy())
bboxes_list.append(example['bbox'].numpy().tolist())
labels_list.append(example['label'].numpy().tolist())
# Define standard HF schema so the Hub can preview the images natively
features = Features({
'image': Image(),
'bbox': Sequence(Sequence(Value('float32'))),
'label': Sequence(Value('int64'))
})
# Build the Hugging Face dataset structure
hf_dataset = Dataset.from_dict({
'image': images_list,
'bbox': bboxes_list,
'label': labels_list
}, features=features)
# Determine the save path
if export_dir is None:
export_dir = os.path.expanduser(f'~/Documents/local/data/tiny_presence_{target_size}_hf')
else:
export_dir = os.path.expanduser(export_dir)
os.makedirs(export_dir, exist_ok=True)
# Save to disk as highly optimized, cross-framework Parquet files
print(f"Saving universally compatible dataset to: {export_dir}")
hf_dataset.save_to_disk(export_dir)
print("Dataset successfully saved!")
return hf_dataset
def visualize_outliers(outlier_samples, max_display=10):
""" Renders the detected outlier samples in a single row layout. """
if not outlier_samples:
print("No outlier samples collected to visualize.")
return
n_display = min(len(outlier_samples), max_display)
fig, axes = plt.subplots(1, n_display, figsize=(18, 3))
# Ensure axes is iterable even if there's only 1 image
if n_display == 1:
axes = [axes]
for i in range(n_display):
img, img_mean = outlier_samples[i]
if CHANNELS == 1:
axes[i].imshow(img.squeeze(), cmap='gray')
else:
axes[i].imshow(img)
axes[i].set_title(f"Mean: {img_mean:.1f}", fontsize=9)
axes[i].axis('off')
plt.suptitle(f"Sample Visualized Outliers (Target Size: {TARGET_SIZE}x{TARGET_SIZE})", fontsize=12, weight='bold')
plt.tight_layout()
plt.show()
def introduce_outliers(example, outlier_prob=OUTLIER_PERCENTAGE):
""" Randomly alters images to be either extremely bright or extremely dark. """
image = example['image']
rand_val = tf.random.uniform([], minval=0.0, maxval=1.0)
should_be_outlier = rand_val < outlier_prob
def make_outlier():
outlier_type = tf.random.uniform([], minval=0, maxval=2, dtype=tf.int32)
image_float = tf.cast(image, tf.float32)
outlier_skew = tf.random.uniform([], minval=200.0, maxval=210.0)
modified_image = tf.cond(
tf.equal(outlier_type, 0),
lambda: image_float + outlier_skew, # Ultra-bright
lambda: image_float - outlier_skew # Ultra-dark
)
modified_image = tf.clip_by_value(modified_image, 0.0, 255.0)
return tf.cast(modified_image, tf.uint8)
final_image = tf.cond(should_be_outlier, make_outlier, lambda: image)
return {
'image': final_image,
'bbox': example['bbox'],
'label': example['label'],
'is_outlier': should_be_outlier
}
# --- DATA PROCESSING PIPELINE ---
# Load data
ds_builder = tfds.builder('coco/2017', data_dir='~/Documents/local/data')
ds_train = ds_builder.as_dataset(split='train')
ds_val = ds_builder.as_dataset(split='validation')
ds_test = ds_builder.as_dataset(split='test')
# Join datasets
full_ds = ds_train.concatenate(ds_val).concatenate(ds_test)
n_images_raw = sum(1 for _ in full_ds)
# Apply filters + cropping
processed_ds = full_ds.filter(lambda x: tf.shape(x['objects']['label'])[0] > 0)
processed_ds = processed_ds.filter(filter_small_persons)
processed_ds = processed_ds.map(prepare_data, num_parallel_calls=tf.data.AUTOTUNE)
# Create outliers
processed_ds = processed_ds.map(introduce_outliers, num_parallel_calls=tf.data.AUTOTUNE)
# Print statistics & collect outlier visualization arrays
n_images_processed = 0
n_outliers = 0
outlier_pixel_sum = 0.0
collected_outliers = [] # Holds tuples of (image_numpy, mean_value)
MAX_SAMPLES_TO_COLLECT = 10
print("Analyzing dataset and collecting metrics...")
for example in processed_ds:
n_images_processed += 1
if example['is_outlier'].numpy():
n_outliers += 1
img_np = example['image'].numpy()
current_mean = img_np.mean()
outlier_pixel_sum += current_mean
# Save up to MAX_SAMPLES_TO_COLLECT items to plot later
if len(collected_outliers) < MAX_SAMPLES_TO_COLLECT:
collected_outliers.append((img_np, current_mean))
avg_outlier_pixel_val = (outlier_pixel_sum / n_outliers) if n_outliers > 0 else 0.0
outlier_ratio = (n_outliers / n_images_processed * 100) if n_images_processed > 0 else 0.0
print(f"\n--- Dataset Statistics ---")
print(f"Total images in raw dataset: {n_images_raw}")
print(f"Images discarded (filtered): {n_images_raw - n_images_processed}")
print(f"Images remaining: {n_images_processed}")
print(f"--------------------------")
print(f"--- Outlier Statistics ---")
print(f"Detected Outliers: {n_outliers} ({outlier_ratio:.2f}% of remaining)")
print(f"Average Outlier Pixel Mean: {avg_outlier_pixel_val:.2f} (Expected near 0 or 255)")
print(f"--------------------------")
# Visualize original/person subsets
visualize_dataset(processed_ds)
# Visualize the captured outlier images
visualize_outliers(collected_outliers, max_display=MAX_SAMPLES_TO_COLLECT)
# Size estimation
total_bytes = TARGET_SIZE * TARGET_SIZE * CHANNELS * tf.uint8.size * n_images_processed
print(f"Total dataset cache size: {total_bytes / (1024 * 1024):.2f} MB")
# Save
processed_ds = processed_ds.apply(tf.data.experimental.assert_cardinality(n_images_processed))
corr_label = "_with_corruptions" if OUTLIER_PERCENTAGE else ""
save_path = os.path.expanduser(f'~/Documents/local/data/tiny_presence_{TARGET_SIZE}_CH_{CHANNELS}_easy{corr_label}')
os.makedirs(save_path, exist_ok=True)
tf.data.Dataset.save(processed_ds, save_path, compression='GZIP')
print(f"Dataset successfully saved to: {save_path}")