i have dataset that has classes 0,1,2 the class 0 is in the class 2, so when i crop the…
- User
i have dataset that has classes 0,1,2 the class 0 is in the class 2, so when i crop the class 2 i want also to save the polygon part of class 0 but i have to adjust for the the crop one "def crop_polygon(image_path, class_id, polygon_coordinates, original_image_path, save_path): with Image.open(original_image_path) as img: img_width, img_height = img.size
code# Convert normalized coordinates to image coordinates xy_coordinates = [(int(polygon_coordinates[i] * img_width), int(polygon_coordinates[i + 1] * img_height)) for i in range(0, len(polygon_coordinates), 2)] # Calculate bounding box bounding_box = [min(coord[0] for coord in xy_coordinates), min(coord[1] for coord in xy_coordinates), max(coord[0] for coord in xy_coordinates), max(coord[1] for coord in xy_coordinates)] # Calculate the size of the cropped area crop_width = bounding_box[2] - bounding_box[0] crop_height = bounding_box[3] - bounding_box[1] # Create a new image with a transparent background and the size of the cropped area new_img = Image.new('RGBA', (crop_width, crop_height), (255, 255, 255, 0)) # Transparent background # Create an alpha mask using the polygon ImageDraw.Draw(new_img).polygon([(coord[0] - bounding_box[0], coord[1] - bounding_box[1]) for coord in xy_coordinates], outline=(0, 0, 0, 255), fill=(255, 255, 255, 255)) # Paste the cropped polygon onto the new image using the alpha mask new_img.paste(img.crop((bounding_box[0], bounding_box[1], bounding_box[2], bounding_box[3])), (0, 0), mask=new_img) # Save the cropped image with a transparent background and bounding box new_img.save(save_path) - Assistant