update my code "import os
from PIL import Image, ImageDraw
from tqdm import tqdm
from concurrent.futures import ProcessPoolExecutor
from shapely.geometry import Polygon
def parse_coordinates(line):
parts = line.strip().split()
class_id = int(parts[0])
coordinates = list(map(float, parts[1:]))
return class_id, coordinates
import os
from PIL import Image, ImageDraw
from shapely.geometry import Polygon
from shapely.ops import unary_union
def crop_polygon(image_path, class_id, polygon_coordinates, original_image_path, save_dir, class_0_polygons):
with Image.open(original_image_path) as img:
img_width, img_height = img.size
xy_coordinates = [(int(polygon_coordinates[i] * img_width), int(polygon_coordinates[i + 1] * img_height))
for i in range(0, len(polygon_coordinates), 2)]
# Convert class 0 polygons to coordinates relative to the image
relative_class_0_polys = []
for poly in class_0_polygons:
relative_poly = [(p[0] * img_width, p[1] * img_height) for p in poly]
relative_class_0_polys.append(Polygon(relative_poly))
# Crop the image to match the bounding box of class 2 polygon
bounding_box = Polygon(xy_coordinates).bounds
cropped_image = img.crop(bounding_box)
# Check which class 0 polygons are within the cropped area
cropped_class_0_polys = [poly for poly in relative_class_0_polys if Polygon(xy_coordinates).contains(poly)]
combined_class0_polygon = unary_union(cropped_class_0_polys)
# Correctly save the cropped image
class_dir = os.path.join(save_dir, f'class_{class_id}')
if not os.path.exists(class_dir):
os.makedirs(class_dir)
crop_save_path = os.path.join(class_dir, os.path.basename(image_path))
cropped_image.save(crop_save_path)
# Save class 0 labels if any
if class_id == 2 and combined_class0_polygon:
labels_save_path = os.path.splitext(crop_save_path)[0] + '_labels.txt'
with open(labels_save_path, 'w') as class0_labels_file:
for coord in combined_class0_polygon.exterior.coords:
# Convert coordinates back to relative values within the cropped image
relative_x = (coord[0] - bounding_box[0]) / (bounding_box[2] - bounding_box[0])
relative_y = (coord[1] - bounding_box[1]) / (bounding_box[3] - bounding_box[1])
class0_labels_file.write(f"0 {relative_x} {relative_y}\n")
print(f'Processed {image_path}')
def process_image(image_name, image_dir, labels_dir, save_dir):
image_path = os.path.join(image_dir, image_name)
polygons = get_polygons_for_image(image_name, labels_dir)
for index, (class_id, polygon_coordinates) in enumerate(polygons):
if class_id == 2: # Only process polygons with class_id == 2
save_path = os.path.join(save_dir, f"class_{class_id}", f"{os.path.splitext(image_name)[0]}_crop{index}.png")
crop_polygon(image_path, class_id, polygon_coordinates, image_path, save_path)
def get_polygons_for_image(image_name, labels_dir):
base_name = os.path.splitext(image_name)[0]
label_file = f"{base_name}.txt" # Replace with your actual label file extension
label_file_path = os.path.join(labels_dir, label_file)
polygons = []
if os.path.exists(label_file_path):
with open(label_file_path, 'r') as f:
for line in f.readlines():
parts = line.strip().split()
if len(parts) >= 6: # Assuming the format has at least 3 pairs of coordinates for a polygon
class_id = int(parts[0])
polygon_coordinates = list(map(float, parts[1:]))
polygons.append((class_id, polygon_coordinates))
return polygons
def main():
image_dir = "/content/nn/train/images"
labels_dir = "/content/nn/train/labels"
save_dir = "/content/cropped_dataset213"
if not os.path.exists(save_dir):
os.makedirs(save_dir)
with ProcessPoolExecutor() as executor:
futures = []
for image_name in tqdm(sorted(os.listdir(image_dir)), desc="Processing Images"):
if image_name.lower().endswith(('.png', '.jpg', '.jpeg')):
future = executor.submit(process_image, image_name, image_dir, labels_dir, save_dir)
futures.append(future)
# Wait for all futures to complete
for future in tqdm(futures, desc="Waiting for Processes"):
future.result()
print('Polygon cropping is completed.')
if name == "main":
main()