Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 13951

The Python script for image cropping based on annotation files fails to accurately capture the defined bounding boxes

$
0
0

I have annotated images and aim to load and crop them based on the boundary box information provided in a text file. Despite my code implementation, I'm encountering inaccuracies in identifying the image boundaries. Assistance in resolving this issue would be appreciated.My code is:

import osimport cv2def crop_image_with_annotation(image_path, annotation_path, output_folder):    # Read image    img = cv2.imread(image_path)    # Read bounding box coordinates from annotation file    with open(annotation_path, 'r') as f:        line = f.readline().strip()        print("Annotation line:", line)  # Debugging line        print("Image saved:",)        # Split the line into values        values = line.split()        # Check if the line contains the class label        if len(values) == 5:            class_label, x_min, y_min, width, height = map(float, values)        elif len(values) == 4:            x_min, y_min, width, height = map(float, values)        else:            print("Invalid annotation format")            return    # Convert normalized coordinates to pixel coordinates    img_height, img_width = img.shape[:2]    x1 = int(x_min * img_width)    y1 = int(y_min * img_height)    x2 = int((x_min + width) * img_width)    y2 = int((y_min + height) * img_height)    # Crop image based on bounding box coordinates    cropped_img = img[y1:y2, x1:x2]    # Save cropped image to output folder    filename = os.path.basename(image_path)    output_path = os.path.join(output_folder, filename)    cv2.imwrite(output_path, cropped_img)# Define input and output foldersinput_folder = r"C:\Users\na\Desktop\crop"output_folder = r"C:\Users\na\Desktop\crop\new"# Create the output folder if it doesn't existos.makedirs(output_folder, exist_ok=True)# Iterate over files in the input folderfor filename in os.listdir(input_folder):    if filename.endswith(".jpg") or filename.endswith(".jpeg"):  # Check if the file is an image        # Construct paths for image and annotation file        image_path = os.path.join(input_folder, filename)        annotation_path = os.path.join(input_folder, os.path.splitext(filename)[0] +".txt")        # Check if the annotation file exists        if not os.path.exists(annotation_path):            print(f"Annotation file not found for image {filename}. Skipping...")            continue        # Crop image based on annotation        crop_image_with_annotation(image_path, annotation_path, output_folder)

Viewing all articles
Browse latest Browse all 13951

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>