| import os |
| import tensorflow as tf |
| import tensorflow_datasets as tfds |
| import matplotlib.pyplot as plt |
| from datasets import Dataset, Features, Image, Sequence, Value |
|
|
| |
| TARGET_SIZE = 32 |
| MIN_BOX_AREA_PIXELS = int(0.85*TARGET_SIZE)**2 |
| CHANNELS = 3 |
| OUTLIER_PERCENTAGE = 0.001 |
|
|
|
|
| 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) |
|
|
| |
| person_mask = tf.equal(labels, 0) |
| has_person = tf.reduce_any(person_mask) |
|
|
| def crop_with_person(): |
| |
| person_boxes = tf.boolean_mask(boxes, person_mask) |
|
|
| |
| box_heights = person_boxes[:, 2] - person_boxes[:, 0] |
| box_widths = person_boxes[:, 3] - person_boxes[:, 1] |
| areas = box_heights * box_widths |
|
|
| |
| largest_idx = tf.argmax(areas) |
| best_box = person_boxes[largest_idx] |
|
|
| |
| ymin = best_box[0] * h |
| xmin = best_box[1] * w |
| ymax = best_box[2] * h |
| xmax = best_box[3] * w |
|
|
| |
| side = tf.maximum(ymax - ymin, xmax - xmin) |
| |
| side = tf.minimum(side, tf.minimum(h, w)) |
|
|
| |
| center_y = (ymin + ymax) / 2.0 |
| center_x = (xmin + xmax) / 2.0 |
|
|
| |
| crop_ymin = center_y - (side / 2.0) |
| crop_xmin = center_x - (side / 2.0) |
|
|
| |
| 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(): |
| |
| side = tf.minimum(h, w) |
| crop_ymin = (h - side) / 2.0 |
| crop_xmin = (w - side) / 2.0 |
| return crop_ymin, crop_xmin, side |
|
|
| |
| crop_ymin, crop_xmin, side = tf.cond(has_person, crop_with_person, crop_anywhere) |
|
|
| |
| 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) |
| ) |
|
|
| |
| 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) |
|
|
| |
| 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'] |
|
|
| 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) |
|
|
| |
| box_heights_normalized = person_boxes[:, 2] - person_boxes[:, 0] |
| box_widths_normalized = person_boxes[:, 3] - person_boxes[:, 1] |
|
|
| |
| box_heights_orig = box_heights_normalized * h |
| box_widths_orig = box_widths_normalized * w |
| areas_orig = box_heights_orig * box_widths_orig |
|
|
| |
| largest_idx = tf.argmax(areas_orig) |
| best_box = person_boxes[largest_idx] |
|
|
| |
| ymin = best_box[0] * h |
| xmin = best_box[1] * w |
| ymax = best_box[2] * h |
| xmax = best_box[3] * w |
|
|
| |
| side = tf.maximum(ymax - ymin, xmax - xmin) |
| side = tf.minimum(side, tf.minimum(h, w)) |
|
|
| |
| scale_factor = target_size / side |
| final_box_heights = box_heights_orig * scale_factor |
| final_box_widths = box_widths_orig * scale_factor |
|
|
| |
| final_box_areas = final_box_heights * final_box_widths |
|
|
| |
| is_big_enough = final_box_areas >= min_box_area |
|
|
| |
| return tf.reduce_any(is_big_enough) |
|
|
| |
| 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_ds = dataset.take(num_images) |
|
|
| |
| 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)) |
|
|
| |
| 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') |
|
|
| |
| 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 = [] |
|
|
| |
| 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()) |
|
|
| |
| features = Features({ |
| 'image': Image(), |
| 'bbox': Sequence(Sequence(Value('float32'))), |
| 'label': Sequence(Value('int64')) |
| }) |
|
|
| |
| hf_dataset = Dataset.from_dict({ |
| 'image': images_list, |
| 'bbox': bboxes_list, |
| 'label': labels_list |
| }, features=features) |
|
|
| |
| 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) |
|
|
| |
| 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)) |
|
|
| |
| 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, |
| lambda: image_float - outlier_skew |
| ) |
| 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 |
| } |
|
|
|
|
| |
| |
| 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') |
|
|
| |
| full_ds = ds_train.concatenate(ds_val).concatenate(ds_test) |
| n_images_raw = sum(1 for _ in full_ds) |
|
|
| |
| 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) |
|
|
| |
| processed_ds = processed_ds.map(introduce_outliers, num_parallel_calls=tf.data.AUTOTUNE) |
|
|
| |
| n_images_processed = 0 |
| n_outliers = 0 |
| outlier_pixel_sum = 0.0 |
| collected_outliers = [] |
| 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 |
|
|
| |
| 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_dataset(processed_ds) |
|
|
| |
| visualize_outliers(collected_outliers, max_display=MAX_SAMPLES_TO_COLLECT) |
|
|
| |
| 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") |
|
|
| |
| 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}") |
|
|