Download image_expander.py from elieh/ops: direct link, hf CLI and curl.
- Browser
- Download file 9.11 kB
-
https://huggingface.co/spaces/elieh/ops/resolve/main/image_expander.py
- Command line
-
hf download hf://spaces/elieh/ops/image_expander.py
-
curl -L -o image_expander.py https://huggingface.co/spaces/elieh/ops/resolve/main/image_expander.py
9.11 kB
| #!/usr/bin/env python3 | |
| import argparse | |
| import os | |
| import random | |
| import shutil | |
| import cv2 | |
| import numpy as np | |
| import PIL.ImageOps | |
| # pip install git+https://github.com/Lancern/LanguageSAM.git | |
| from lang_sam import LangSAM | |
| from PIL import Image | |
| def get_mask_and_rect(image_pil, text_prompt, model): | |
| """ | |
| Runs LangSAM on the provided PIL image with a text prompt. | |
| Returns: | |
| - mask_255 (H x W) : mask with values 0 or 255 | |
| - corners (4 x 2 float32 array) : bounding box corners of the chosen mask | |
| """ | |
| results = model.predict([image_pil], [text_prompt]) | |
| if not results or not results[0]: | |
| raise ValueError("LangSAM returned an empty or invalid result.") | |
| result_dict = results[0] | |
| if "masks" not in result_dict or "mask_scores" not in result_dict: | |
| raise ValueError("Expected 'masks' and 'mask_scores' in the result dictionary.") | |
| all_masks = result_dict["masks"] | |
| all_scores = result_dict["mask_scores"] | |
| if len(all_masks) == 0: | |
| raise ValueError("No masks found in 'masks' array.") | |
| best_idx = np.argmax(all_scores) | |
| best_mask = all_masks[best_idx] | |
| mask_bin = (best_mask > 0.5).astype(np.uint8) | |
| mask_255 = mask_bin * 255 | |
| x, y, w, h = cv2.boundingRect(mask_255) | |
| corners = np.array( | |
| [[x, y], [x + w, y], [x + w, y + h], [x, y + h]], dtype=np.float32 | |
| ) | |
| return mask_255, corners | |
| def expand_image_with_variation( | |
| image_pil, target_size, position=None, scale=None, mirror=False | |
| ): | |
| """ | |
| Expands an image to the target size with variations in position and scale. | |
| Args: | |
| image_pil: PIL Image of the product | |
| target_size: (width, height) tuple for the output image | |
| position: (x_offset, y_offset) tuple or None for random positioning | |
| scale: Float scale factor or None for random scaling | |
| mirror: Boolean indicating whether to mirror the image horizontally | |
| """ | |
| target_width, target_height = target_size | |
| # Create a new white image of the target size | |
| new_image = Image.new("RGB", (target_width, target_height), (255, 255, 255)) | |
| # Mirror the image if requested | |
| if mirror: | |
| image_pil = PIL.ImageOps.mirror(image_pil) | |
| # Apply scaling | |
| if scale is None: | |
| # Random scale factor between 0.3 (far shot) and 0.9 (close shot) | |
| scale = random.uniform(0.3, 0.9) | |
| new_width = int(image_pil.width * scale) | |
| new_height = int(image_pil.height * scale) | |
| # Ensure the scaled image isn't larger than the target canvas | |
| if new_width > target_width: | |
| new_width = target_width | |
| new_height = int(image_pil.height * (target_width / image_pil.width)) | |
| if new_height > target_height: | |
| new_height = target_height | |
| new_width = int(image_pil.width * (target_height / image_pil.height)) | |
| # Use high quality resizing with LANCZOS resampling | |
| resized_image = image_pil.resize((new_width, new_height), Image.Resampling.LANCZOS) | |
| # Apply random or specified positioning | |
| if position is None: | |
| # Random position that ensures the image is fully within the canvas | |
| max_x = target_width - new_width | |
| max_y = target_height - new_height | |
| paste_x = random.randint(0, max(0, max_x)) | |
| paste_y = random.randint(0, max(0, max_y)) | |
| else: | |
| paste_x, paste_y = position | |
| # Paste the processed image onto the new white canvas | |
| new_image.paste(resized_image, (paste_x, paste_y), resized_image.convert("RGBA")) | |
| return new_image | |
| def crop_to_product(image_pil, model, text_prompt="product"): | |
| """ | |
| Crops the image to just the product using LangSAM. | |
| """ | |
| # Get the mask and bounding box | |
| mask_255, corners = get_mask_and_rect(image_pil, text_prompt, model) | |
| # Convert corners to x, y, w, h format | |
| x, y = int(corners[0][0]), int(corners[0][1]) | |
| w = int(corners[2][0] - corners[0][0]) | |
| h = int(corners[2][1] - corners[0][1]) | |
| # Add a much larger margin (100% of width/height) to ensure we don't cut off any part of the product | |
| margin_x = int(w * 1.0) | |
| margin_y = int(h * 1.0) | |
| # Calculate new coordinates with margins | |
| x1 = max(0, x - margin_x) | |
| y1 = max(0, y - margin_y) | |
| x2 = min(image_pil.width, x + w + margin_x) | |
| y2 = min(image_pil.height, y + h + margin_y) | |
| # Crop the image | |
| cropped_image = image_pil.crop((x1, y1, x2, y2)) | |
| return cropped_image | |
| def main(): | |
| parser = argparse.ArgumentParser( | |
| description="Expand product images to standard sizes with white background and variations in position and scale." | |
| ) | |
| parser.add_argument( | |
| "--input-dir", | |
| required=True, | |
| help="Directory containing input images and caption files.", | |
| ) | |
| parser.add_argument("--output-dir", default="output", help="Output directory.") | |
| parser.add_argument( | |
| "--text-prompt", default="product", help="Text prompt describing the product." | |
| ) | |
| parser.add_argument( | |
| "--variations", | |
| type=int, | |
| default=1, | |
| help="Number of variations to generate per size.", | |
| ) | |
| parser.add_argument( | |
| "--mirror", | |
| action="store_true", | |
| help="Enable mirroring of the product in some variations.", | |
| ) | |
| args = parser.parse_args() | |
| # If the output directory exists, delete it | |
| if os.path.exists(args.output_dir): | |
| shutil.rmtree(args.output_dir) | |
| # Create output directory | |
| os.makedirs(args.output_dir) | |
| # Initialize LangSAM | |
| print("Loading LangSAM model...") | |
| model = LangSAM() | |
| # Define target sizes | |
| target_sizes = [ | |
| (1024, 1024), # Standard square | |
| ] | |
| # Get all image files from the input directory | |
| image_files = [ | |
| f | |
| for f in os.listdir(args.input_dir) | |
| if f.endswith((".png", ".jpg", ".jpeg")) | |
| and os.path.isfile(os.path.join(args.input_dir, f)) | |
| ] | |
| for image_file in image_files: | |
| image_path = os.path.join(args.input_dir, image_file) | |
| base_name = os.path.splitext(image_file)[0] | |
| caption_file = os.path.join(args.input_dir, f"{base_name}.txt") | |
| # Check if corresponding caption file exists | |
| if not os.path.exists(caption_file): | |
| print(f"Warning: No caption file found for {image_file}, skipping.") | |
| continue | |
| # Read the caption | |
| with open(caption_file, "r") as f: | |
| caption = f.read().strip() | |
| # Load image | |
| print(f"Processing {image_file}...") | |
| image_pil = Image.open(image_path).convert("RGB") | |
| # Include original image in the output - save in PNG format for lossless quality | |
| original_image_path = os.path.join(args.output_dir, f"{base_name}_original.png") | |
| image_pil.save(original_image_path, format="PNG", quality=100) | |
| # Include original caption in the output | |
| original_caption_path = os.path.join( | |
| args.output_dir, f"{base_name}_original.txt" | |
| ) | |
| with open(original_caption_path, "w") as f: | |
| f.write(caption) | |
| print(f"Saved original image and caption to {original_image_path}") | |
| # Crop to just the product | |
| print(f"Segmenting product with prompt '{args.text_prompt}'...") | |
| product_image = crop_to_product(image_pil, model, args.text_prompt) | |
| # Create expanded images with variations for each target size | |
| for size in target_sizes: | |
| print(f"Creating {args.variations} variations at {size[0]}x{size[1]}...") | |
| # Generate variations with different positions and scales | |
| for i in range(args.variations): | |
| # Focus on zooming out to show aspect ratio/resolution | |
| # Use a wider range of scales to capture different zoom levels | |
| scale = random.uniform(0.05, 0.5) # Prioritize zoomed out views | |
| variation_type = "zoom_out" | |
| # Randomly mirror some images if enabled | |
| mirror = args.mirror and random.choice([True, False]) | |
| mirror_suffix = "_mirrored" if mirror else "" | |
| expanded_image = expand_image_with_variation( | |
| product_image, size, scale=scale, mirror=mirror | |
| ) | |
| # Create output filename | |
| output_filename = f"{base_name}_{size[0]}x{size[1]}_{variation_type}{mirror_suffix}_{i + 1}" | |
| # Save the expanded image with high quality settings | |
| image_output_path = os.path.join( | |
| args.output_dir, f"{output_filename}.png" | |
| ) | |
| expanded_image.save(image_output_path, format="PNG", quality=100) | |
| # Save the caption to a matching text file | |
| caption_output_path = os.path.join( | |
| args.output_dir, f"{output_filename}.txt" | |
| ) | |
| with open(caption_output_path, "w") as f: | |
| f.write(caption) | |
| print( | |
| f"Saved {variation_type}{' mirrored' if mirror else ''} shot to {image_output_path}" | |
| ) | |
| if __name__ == "__main__": | |
| main() | |