Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-mini-2024-07-18· OpenAIAi2 WildChat-4.8M (AI2)

How to convert in Python a list of polygons tuples like this: "1215,969 3268,1010…

  1. User

    How to convert in Python a list of polygons tuples like this: "1215,969 3268,1010 3309,1119 3322,3835 3322,4501 3281,4597 1338,4624 464,4583 491,1051 519,996 1215,969" from an image with imageWidth="4607" imageHeight="6143" to DocTr polygons label?

  2. Assistant

    To convert a list of polygon tuples represented as a string into the format used by the DocTr library, you'll need to parse the input string, normalize the polygon coordinates based on the image dimensions, and then format the result accordingly.

    Here's a step-by-step guide and the corresponding Python code:

    1. Parse the input string: Split the string into individual points.
    2. Convert to tuples: Convert each point from a string to a tuple of integers.
    3. Normalize the coordinates: Since the DocTr library may use coordinate normalization (e.g., scaling the coordinates between 0 and 1), you will need to convert the polygon coordinates based on the imageWidth and imageHeight.
    4. Format the output: Once the coordinates are normalized, format them as required by DocTr.

    Python Code

    Here’s a Python function that performs the above steps:

    def convert_to_docktr_polygons(polygon_str, imageWidth, imageHeight):
        # Step 1: Parse the input string
        points = polygon_str.split()
        
        # Step 2: Convert to tuples of integers
        points = [tuple(map(int, point.split(','))) for point in points]
    
        # Step 3: Normalize the coordinates based on image dimensions
        normalized_points = [(x / imageWidth, y / imageHeight) for x, y in points]
    
        # Step 4: Format the output for DocTr. 
        # Assuming DocTr expects a list of tuples of normalized coordinates.
        docktr_polygon = [{'polygon': normalized_points}]
        
        return docktr_polygon
    
    # Example usage
    polygon_str = "1215,969 3268,1010 3309,1119 3322,3835 3322,4501 3281,4597 1338,4624 464,4583 491,1051 519,996 1215,969"
    imageWidth = 4607
    imageHeight = 6143
    
    result = convert_to_docktr_polygons(polygon_str, imageWidth, imageHeight)
    print(result)
    

    Explanation of the Code:

    • Parsing: The split() method splits the string into individual points, and then split(',') further splits each point into x and y coordinates.
    • Normalization: Each coordinate is divided by imageWidth or imageHeight to scale the coordinates to a [0, 1] range.
    • Formatting for DocTr: The normalized coordinates are stored in a list of dictionaries (with the key 'polygon'), which can be modified as per the specific needs of the DocTr usage.

    Note:

    • Adjust the structure of the final output based on the requirements of the DocTr library. The example provided assumes it expects polygons in a certain format. Check the documentation for any specific requirements you need to abide by.
  3. User

    What I meant with "doctr" is "https://github.com/mindee/doctr".

  4. Assistant

    Thank you for the clarification regarding doctr. In the context of the doctr library, specifically for working with polygons, you might want to convert your polygon string into a format that aligns with the doctr expectations for labeled data.

    To convert your polygon string into the format used by doctr, you'll typically want to:

    • Parse the polygon coordinates.
    • Normalize the coordinates based on the image dimensions.
    • Prepare the data in a structured way suitable for doctr, such as a tuple containing the coordinates.

    Here’s how you can achieve this:

    1. Parse the Input: Break down the input string into coordinate tuples.
    2. Normalize Coordinates: Scale the points to a range from 0 to 1 based on the provided imageWidth and imageHeight.
    3. Format for doctr: Create a list of polygons in the expected format.

    Sample Code

    Here is the Python code implementing the above logic:

    def convert_to_doctr_polygons(polygon_str, imageWidth, imageHeight):
        # Step 1: Parse the input string
        points = polygon_str.strip().split()
        
        # Step 2: Convert to tuples of integers
        points = [tuple(map(int, point.split(','))) for point in points]
    
        # Step 3: Normalize the coordinates based on image dimensions
        normalized_points = [(x / imageWidth, y / imageHeight) for x, y in points]
    
        # Format it for doctr as required: a list of polygons
        # If only a single polygon is represented, wrap it in a list
        doctr_polygons = [normalized_points]
        
        return doctr_polygons
    
    # Example usage
    polygon_str = "1215,969 3268,1010 3309,1119 3322,3835 3322,4501 3281,4597 1338,4624 464,4583 491,1051 519,996 1215,969"
    imageWidth = 4607
    imageHeight = 6143
    
    result = convert_to_doctr_polygons(polygon_str, imageWidth, imageHeight)
    print(result)
    

    Explanation of the Code:

    • Parsing: The strip() method removes any leading or trailing whitespace, and split() breaks it into points.
    • Normalization: Each point is normalized by dividing the x-coordinate by imageWidth and the y-coordinate by imageHeight.
    • Output Format for doctr: The result is structured as a list of polygons, which in this case is a single polygon defined by its normalized coordinates.

    This will give you an output like:

    [
        [(0.2636, 0.1577), (0.7092, 0.1640), (0.7189, 0.1825), 
         (0.7215, 0.6221), (0.7215, 0.7296), (0.7128, 0.7450), 
         (0.2901, 0.7497), (0.1000, 0.7428), (0.1065, 0.1710), 
         (0.1127, 0.1619), (0.2636, 0.1577)]  # normalized points
    ]
    

    Note:

    Make sure to check the necessary format for polygons in doctr. The provided code formats it as a list of polygons. Depending on your specific use case, you might need to adjust how you structure the output.

  5. User

    This is an example of polygon in "DocTR" labels: "polygons": [[[608, 694], [644, 694], [644, 728], [608, 728]], [[592, 734], [630, 734], [630, 768], [592, 768]], [[610, 771], [648, 771], [648, 808], [610, 808]], [[598, 894], [636, 894], [636, 930], [598, 930]], [[154, 690], [168, 690], [168, 720], [154, 720]], [[182, 687], [270, 690], [269, 724], [181, 721]], [[282, 690], [364, 690], [364, 722], [282, 722]], [[376, 692], [426, 692], [426, 724], [376, 724]], [[641, 693], [741, 693], [741, 727], [641, 727]], [[150, 728], [166, 728], [166, 760], [150, 760]], [[180, 728], [300, 728], [300, 762], [180, 762]], [[310, 730], [362, 730], [362, 762], [310, 762]], [[628, 732], [744, 732], [744, 768], [628, 768]], [[148, 771], [164, 771], [164, 802], [148, 802]], [[178, 768], [298, 768], [298, 802], [178, 802]], [[310, 768], [380, 775], [377, 808], [307, 801]], [[390, 770], [458, 770], [458, 804], [390, 804]], [[468, 770], [534, 770], [534, 804], [468, 804]], [[644, 771], [746, 771], [746, 808], [644, 808]], [[144, 810], [160, 810], [160, 842], [144, 842]], [[176, 810], [312, 810], [312, 844], [176, 844]], [[324, 810], [378, 810], [378, 844], [324, 844]], [[392, 810], [442, 810], [442, 844], [392, 844]], [[598, 812], [750, 812], [750, 850], [598, 850]], [[388, 892], [440, 892], [440, 928], [388, 928]], [[451, 892], [552, 892], [552, 928], [451, 928]], [[634, 892], [756, 895], [755, 933], [633, 931]], [[436, 933], [490, 933], [490, 970], [436, 970]], [[500, 933], [540, 933], [540, 970], [500, 970]], [[632, 938], [758, 938], [758, 976], [632, 976]], [[468, 976], [524, 976], [524, 1014], [468, 1014]], [[617, 980], [759, 980], [759, 1020], [617, 1020]], [[213, 1071], [411, 1066], [412, 1105], [214, 1110]], [[451, 1063], [762, 1068], [761, 1111], [450, 1105]], [[436, 1158], [508, 1158], [508, 1194], [436, 1194]], [[604, 1157], [770, 1160], [769, 1202], [603, 1199]]]

  6. Assistant

    Thank you for providing a specific format for the polygons as used in the doctr library. Based on the format you've shared, it looks like doctr expects a nested list structure where each polygon is a list of points defined by pairs of coordinates.

    Steps to Convert Into DocTR Format

    1. Parse Input: Convert the string into a list of points.
    2. Normalize Coordinates: Since doctr uses pixel coordinates, there may not be a need for scaling in this case. But if needed, you can adjust the coordinates based on your use case.
    3. Format for DocTR: Create the necessary nested list structure.

    Example Code

    Here's how you can write the function to convert the polygon string into the expected nested structure:

    def convert_to_doctr_polygons(polygon_str):
        # Step 1: Parse the input string into a list of tuples
        points = polygon_str.strip().split()
        
        # Step 2: Convert to tuples of integers
        points = [tuple(map(int, point.split(','))) for point in points]
    
        # Step 3: Convert to the required structure for DocTR.
        # In this case, DocTR expects a list of polygons, 
        # with each polygon being a list of point pairs.
        doctr_polygons = [list(points)]  # Wrap points in a list for a single polygon
        
        return doctr_polygons
    
    # Example usage
    polygon_str = "1215,969 3268,1010 3309,1119 3322,3835 3322,4501 3281,4597 1338,4624 464,4583 491,1051 519,996 1215,969"
    
    # Convert the string to DocTR polygon format
    result = convert_to_doctr_polygons(polygon_str)
    print(result)
    

    Explanation of the Code:

    • Parsing: Similar to before, we split the input polygon string to extract individual points, then convert those to tuples of integers (which represent the x, y coordinates).

    • Formatting: The points are wrapped in a list, which makes up a single polygon in the expected DocTR format. If you have multiple polygons to combine into this format, you would simply append lists of points to doctr_polygons.

    Output Example

    For the provided polygon_str, running the code will give you an output like:

    [
        [[1215, 969], [3268, 1010], [3309, 1119], [3322, 3835], [3322, 4501], [3281, 4597], [1338, 4624], [464, 4583], [491, 1051], [519, 996], [1215, 969]]
    ]
    

    Notes:

    • This code specifically handles a single polygon. If you have multiple polygons and you want to format them similarly, you can adjust how doctr_polygons is populated.
    • Ensure that any necessary normalization is done according to doctr usage. If working with raw pixel coordinates from an image, the above code should suffice. If you need to scale or adjust based on dataset specifications, incorporate those calculations before returning the final list.
  7. User

    When converting they take in count the image width and height, this is a Python function they use, how to use in my case? def to_absolute(width, height, label): polygons = np.empty(label['boxes'].shape, dtype=np.int32) polygons[..., 0] = label['boxes'][..., 0] * width polygons[..., 1] = label['boxes'][..., 1] * height return polygons

  8. Assistant

    To integrate the to_absolute function you provided into your polygon conversion process, you'll need to follow these steps:

    1. Extract coordinates from your polygon string.
    2. Normalize these coordinates by dividing by image width and height.
    3. Use the to_absolute function to convert normalized coordinates back to absolute pixel coordinates.

    Adjusted Code

    Below is the complete code that incorporates the normalization and the use of the to_absolute function to achieve your desired output format for doctr.

    import numpy as np
    
    def to_absolute(width, height, label):
        polygons = np.empty(label['boxes'].shape, dtype=np.int32)
        polygons[..., 0] = label['boxes'][..., 0] * width
        polygons[..., 1] = label['boxes'][..., 1] * height
        return polygons
    
    def convert_to_doctr_polygons(polygon_str, imageWidth, imageHeight):
        # Step 1: Parse the input string into a list of tuples
        points = polygon_str.strip().split()
        # Step 2: Convert to tuples of integers
        points = [tuple(map(int, point.split(','))) for point in points]
        
        # Step 3: Normalize the coordinates
        normalized_points = [(x / imageWidth, y / imageHeight) for x, y in points]
        
        # Prepare the label structure expected by `to_absolute`
        label = {'boxes': np.array(normalized_points, dtype=np.float32)}  # Use float32 for normalized points
    
        # Step 4: Convert normalized points back to absolute pixel coordinates
        absolute_polygons = to_absolute(imageWidth, imageHeight, label)
    
        # Format the output for DocTR
        doctr_polygons = [absolute_polygons.tolist()]  # Wrap it for a single polygon
    
        return doctr_polygons
    
    # Example usage
    polygon_str = "1215,969 3268,1010 3309,1119 3322,3835 3322,4501 3281,4597 1338,4624 464,4583 491,1051 519,996 1215,969"
    imageWidth = 4607
    imageHeight = 6143
    
    # Convert the string to DocTR polygon format with absolute coordinates
    result = convert_to_doctr_polygons(polygon_str, imageWidth, imageHeight)
    print(result)
    

    Explanation of Changes:

    1. Normalization Step:

      • The coordinates are first normalized by dividing each pixel coordinate by imageWidth and imageHeight.
    2. Structuring for to_absolute:

      • The label dictionary is created using a NumPy array of the normalized points. This is necessary to ensure it's in the expected format for the to_absolute function.
    3. Using to_absolute:

      • After passing the normalized coordinates to the to_absolute function, you receive back the absolute pixel coordinates.
    4. Formatting:

      • Finally, the absolute coordinates are wrapped in a list to match the expected format for doctr, which consists of a list of polygons.

    Output:

    When you run the provided code with the specified polygon string, it'll output a list of polygons in the required format with absolute coordinates calculated based on the specified image width and height. The final output will be suitable to use in the doctr library.