i am unable to presrve the perturbations in the yellow watermark: what to do so it…
- User
i am unable to presrve the perturbations in the yellow watermark: what to do so it preserve wheni split adn combine: import cv2 import os import glob import argparse import numpy as np
parser = argparse.ArgumentParser(description="Split or combine character images.") parser.add_argument('--mode', choices=['split', 'combine'], default='split', help='Mode to run: split or combine') parser.add_argument('--split_input', type=str, default='split', help='Input folder for split mode') parser.add_argument('--split_output', type=str, default='combined', help='Output folder for split mode') parser.add_argument('--combine_input', type=str, default='split', help='Input folder for combine mode') parser.add_argument('--combine_output', type=str, default='combined', help='Output folder for combine mode') parser.add_argument('--original_input', type=str, default='test', help='Folder containing original images for combine mode') parser.add_argument('--padding', type=int, default=10, help='Padding to add around each character') parser.add_argument('--char_size', type=int, default=64, help='Uniform size for character images (width and height)') parser.add_argument('--debug', action='store_true', help='Save debug images showing detected character boundaries') args = parser.parse_args()
if args.mode == "split": INPUT_FOLDER = args.split_input OUTPUT_FOLDER = args.split_output PADDING = args.padding CHAR_SIZE = args.char_size os.makedirs(OUTPUT_FOLDER, exist_ok=True)
# Clear metadata file at start of split mode meta_path = os.path.join(OUTPUT_FOLDER, "metadata.txt") if os.path.exists(meta_path): os.remove(meta_path) # Remove existing metadata file # Loop through all PNG files # for filepath in glob.glob(os.path.join(INPUT_FOLDER, "*.jpg")): for filepath in glob.glob(os.path.join(INPUT_FOLDER, "*.png")) + glob.glob(os.path.join(INPUT_FOLDER, "*.jpg")): filename = os.path.basename(filepath) print(f"Processing {filename}...") # Example filename: 0_unobtainable_0.png # Extract label (the word between underscores) parts = filename.split("_") if len(parts) < 2: print(f"Skipping {filename}, filename format not matching") continue label = parts[1] # "unobtainable" # Load image (color and grayscale) img_color = cv2.imread(filepath, cv2.IMREAD_COLOR) if img_color is None: print(f"Failed to load {filename}") continue gray = cv2.cvtColor(img_color, cv2.COLOR_BGR2GRAY) # Find contours on inverted image to get character bounding boxes (original working method) thresh = 255 - gray # bitwise inversion _, thresh_bin = cv2.threshold(thresh, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) contours, _ = cv2.findContours(thresh_bin, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Sort contours left-to-right contours = sorted(contours, key=lambda ctr: cv2.boundingRect(ctr)[0]) # Filter contours with original size requirements valid_contours = [] for ctr in contours: x, y, w, h = cv2.boundingRect(ctr) if w > 2 and h > 2: # Original filter - this was working valid_contours.append(ctr) print(f" -> Found {len(valid_contours)} valid contours for '{label}' (expected {len(label)})") # Just warn about mismatches without changing the detection if len(valid_contours) != len(label): if len(valid_contours) < len(label): print(f" -> WARNING: Missing {len(label) - len(valid_contours)} characters in {filename}") print(f" Some characters may not be detected properly") else: print(f" -> WARNING: Found {len(valid_contours) - len(label)} extra contours") print(f" Extra contours will be ignored") # Prepare metadata list - this will store exact crop regions and original image info metadata = [] # Store original image dimensions for perfect reconstruction h_orig, w_orig = gray.shape[:2] metadata.append(f"ORIGINAL_SIZE {w_orig} {h_orig}") # Save each character (using original working logic) for i, ctr in enumerate(valid_contours): x, y, w, h = cv2.boundingRect(ctr) if i >= len(label): print(f"Skipping extra contour {i} in {filename} (no matching label)") break # Extract exact character region from original color image char_img = img_color[y:y+h, x:x+w].copy() # Store original character dimensions before any processing orig_char_h, orig_char_w = char_img.shape[:2] # Add padding around the character char_img_padded = cv2.copyMakeBorder( char_img, PADDING, PADDING, PADDING, PADDING, cv2.BORDER_CONSTANT, value=(255, 255, 255) ) # Resize to uniform size for model training char_img_uniform = cv2.resize(char_img_padded, (CHAR_SIZE, CHAR_SIZE)) char_label = label[i] print(f" -> Saving char {i} ({char_label}) from {filename} - original: {orig_char_w}x{orig_char_h}, uniform: {CHAR_SIZE}x{CHAR_SIZE}") # Save with new filename: word_charIndex_char.png out_path = os.path.join( OUTPUT_FOLDER, f"{filename[:-4]}_{i}_{char_label}.png" ) cv2.imwrite(out_path, char_img_uniform) # Save metadata: character index, original bounding box (x,y,w,h), padding info, and uniform size metadata.append(f"CHAR {i} {x} {y} {w} {h} {PADDING} {CHAR_SIZE}") # Save debug image only if debug flag is enabled if args.debug: debug_img = gray.copy() if len(debug_img.shape) == 2: # Convert grayscale to color for colored rectangles debug_img = cv2.cvtColor(debug_img, cv2.COLOR_GRAY2BGR) for i, ctr in enumerate(valid_contours): if i < len(label): x, y, w, h = cv2.boundingRect(ctr) # Draw rectangle around detected character cv2.rectangle(debug_img, (x, y), (x+w, y+h), (0, 255, 0), 1) # Put character label cv2.putText(debug_img, label[i], (x, y-2), cv2.FONT_HERSHEY_SIMPLEX, 0.3, (0, 0, 255), 1) # Save debug image debug_path = os.path.join(OUTPUT_FOLDER, f"debug_{filename}") cv2.imwrite(debug_path, debug_img) # Save metadata to a single combined metadata file meta_path = os.path.join(OUTPUT_FOLDER, "metadata.txt") with open(meta_path, "a") as f: # Append mode # Write filename header f.write(f"FILE {filename[:-4]}\n") for line in metadata[1:]: # Skip the first line as it's already written with FILE header f.write(line + "\n") # Add metadata for original size from the first line f.write(metadata[0] + "\n") f.write("END_FILE\n") # Mark end of this file's metadata print("✅ Done! All word images split into uniform-sized characters with padding. Metadata saved to metadata.txt") - Assistant
- User
yes
- Assistant
- User
- Assistant
- User
Usage examples:
Split mode with debug visualization:
python3 script.py --mode split --split_input images --split_output characters --padding 10 --char_size 64 --debug
Split mode without debug:
python3 script.py --mode split --split_input images --split_output characters --padding 10 --char_size 64
Combine mode:
python3 script.py --mode combine --combine_input characters --combine_output reconstructed --original_input images?
- Assistant
- User
but the image naming taking should be same
- Assistant
Got it 👍 you want the naming scheme of the split characters and the recombined images to match the original image names, so that after combining, you can trace them back without confusion. Here’s how we can handle naming properly: 🔹 Split mode
Suppose you have an image: 1000_flute.png
When splitting into characters, the output should be: python-replCopyEdit1000_flute_0.png 1000_flute_1.png 1000_flute_2.png ...
(index appended at the end).
🔹 Combine mode
When combining, it should:
Take all files with prefix 1000_flute_
Order them by index (_0, _1, _2...)
Merge them back
Save as 1000_flute.png in the combine_output folder.
I can modify the script I gave you so that naming stays consistent between split and combine. 👉 Do you also want to keep the same extension (.png / .jpg) as the original input image when combining, or always save combined images as .png?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.