Tips for creating curved corners on a polygon using given x and y coordinates

Is there a way to draw a polygon from X, Y coordinates with rounded corners using the points I have?

Below is my current code, but I am open to suggestions if there is another library that may work better.

Displayed below is my output image generated by the code:

And here is the function in use:

def create_mask(dirct,filename,alistofpoint,height,width):
    myimg = np.zeros((height,width), dtype = "uint8")
    po = np.array(alistofpoint, np.int32)
    myimg_mod=cv2.fillPoly(myimg, [po],(255,255))
    cv2.imwrite(dirct+"//"+filename, myimg_mod)

Answer №1

To accomplish this task, you can utilize the Pillow library's ImageDraw module. Start by defining the coordinates to create a polygon and then apply a wide line with rounded corners for outlining.

from operator import itemgetter
from pathlib import Path
from PIL import Image, ImageDraw

def generate_custom_mask(directory, filename, point_list, h, w):
    custom_mask = Image.new('L', (w, h), color=0)
    draw_tool = ImageDraw.Draw(custom_mask)
    draw_tool.polygon(point_list, fill=255, outline=255)
    draw_tool.line(point_list, fill=255, width=5, joint='curve')
    custom_mask.save(Path(directory)/filename)
    return custom_mask

padding = 25
point_list = [(114, 197), (96, 77), (110, 42), (138, 56,), (166, 124), (166, 174), (154, 195)]
w = max(point_list, key=itemgetter(0))[0] + padding
h = max(point_list, key=itemgetter(1))[1] + padding

created_mask = generate_custom_mask('\.', 'output_image.png', point_list, h, w)
created_mask.show()

Shown below is an enlarged view of the polygon without an outline on the left, and with the added outline on the right side. The visual impact may be minimal due to the image resolution used in this demonstration.

https://i.stack.imgur.com/y8NIy.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Python Arrays and Links

My CSV file represents a tree diagram structure in the following format: A,B #A is associated with B A,C #A is associated with C B,D #B is associated with D B,E #B is associated with E C,F #C is associated with F C,G #C is associated with G In this ...

Cease the execution of the function as soon as the mouse key is no

I'm currently working on a function that should run when the mouse key is pressed down and be canceled once it's released. I want to achieve this using pynput. Here's the code snippet I've been using, but it seems like it's waiting ...

When attempting to close the current window in Python, Windows Handling automatically shuts down the entire browser

Currently, I am using Windows handling to open the map directions in a new window. After the new window opens, I close it and continue with the remaining work in the code. However, instead of just closing the child window, the whole browser is being closed ...

Steps for updating the ChromeDriver binary file on Ubuntu

I've been using Python / Selenium / Chrome / ChromeDriver for various tasks like testing and scraping. Recently, I've been trying to change the cdc_ string to something else in a file. However, even after replacing it with cat_ in vim, nothing se ...

The outcome produced by the union-find algorithm is not what was anticipated

After studying an example from this source, I implemented a union-find algorithm: import numpy as np class UnionFind(object): def __init__(self, edges): self.edges = edges self.n_edges = np.max(edges) + 1 self.data = list(ra ...

Flask not displaying Bokeh DataTable

I have been working on a Flask web application that displays data in a DataTable and creates interactive reports using Bokeh. However, I am facing an issue with my code to show the Bokeh DataTable. from flask import Flask, render_template, request import ...

Various approaches for standardizing values in image manipulation

My current project involves creating a neural network to identify forest areas in satellite images. As I delved into analyzing the images, I encountered a dilemma regarding how to normalize the pixel values. Initially, I considered dividing each pixel va ...

Insert a new value into a pandas DataFrame with specified index and column names

I am working on populating a pandas Dataframe value by value. My input is a series of dictionaries like this: LIST_OF_DICTS = [ {'name':'carlos','age':34}, {'name':'John', 'country':'USA&apo ...

Choose any brother or sister

Is it limited to using preceding-sibling and following-sibling for specifically selecting siblings? Condensed Markup Example <ui-view> <descendant> <!-- 1 --> <descendant> <!-- 2 --> <descendant> <!-- 3 ...

Gradual transformation of binary information

I am working with a binary file that has a specific format, outlined here for those interested. While I can successfully read and convert the data into the desired format, the challenge lies in processing these files efficiently. The issue is not with read ...

What is the process for deserializing a string that contains a quote within its value?

I am facing a challenge with deserializing the following string: { "bw": 20, "center_freq": 2437, "channel": 6, "essid": "DIRECT-sB47" Philips 6198", "freq": 2437 } The JSON structure is almost correct, but there is an issue with the quote in t ...

Error: `virtualenv` command not found in pyenv

I came across a helpful tutorial for installing torch on Ubuntu 20.04. One step involves setting up pyenv, which is similar to virtualenv for Python, allowing me to manage multiple Python versions. While it may seem unnecessary at first, it's all part ...

Can you explain the significance of the following in a Python Binary String?

Seeking a quick answer to this question that is difficult to find through a simple Google search. If I am presented with the following hexadecimal code: b'\xff\xfe\x03\x00\x07\xff0\x00[\x0f\xefm' Wh ...

Having trouble using Python's Selenium to interact with an input box and send keys

My goal is to automate the login process on a specific website . The script provided successfully navigates to the page where the password needs to be entered. import time from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWa ...

Enhancing the reliability of Absolute XPath for testing purposes

I recently delved into the world of test automation and have been self-teaching myself. While exploring a challenging DOM page on the internet, I managed to locate the elusive blue button using an absolute Xpath. It was the only method that seemed effecti ...

`an issue arises when attempting to run a local command using fabric2`

Take a look at the code below: from fabric2 import Connection cbis = Connection.local() with cbis.cd('/home/bussiere/Workspace/Stack/Event/'): cbis.run('git add .') Unfortunately, I encountered this error: TypeError: local() mi ...

"Enhance the readability of JSON dumps with beautiful formatting

This piece of code allows me to format a dict into JSON in a neat way: import json d = {'a': 'blah', 'b': 'foo', 'c': [1,2,3]} print json.dumps(d, indent = 2, separators=(',', ': ')) R ...

Exploring the Integration of Two Independent Microservices via RESTful API for Data Exchange

Is there a way to establish a connection between two distinct APIs in different programming languages? Specifically, I have an application built in node.js with MongoDB and another one in Python with MySQL. I'm facing the challenge of establishing a 1 ...

What is the best way to find an element in a list using Python?

I have developed a function to delete elements from a text file, but I am facing an issue where even if the element is present in the list, it always shows "Student was not found". Can anyone help me understand why this is happening? Below is the code sni ...

While utilizing the Sequential model, I encountered an error stating "AttributeError: 'Model' object does not possess the attribute 'predict_classes'"

As outlined in this particular question, it has been advised that a sequential model is required to utilize .predict_classes. Despite implementing this model, the following error persists: AttributeError: 'function' object has no attribute ' ...