Last active
June 30, 2021 04:40
-
-
Save aryamansharda/95c8c6eef374d84a320a2d59cdc1d97d to your computer and use it in GitHub Desktop.
LowPolygonArt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
import numpy as np | |
# https://github.com/jmespadero/pyDelaunay2D | |
from delaunay2D import Delaunay2D | |
from PIL import Image | |
from PIL import ImageDraw | |
# Load an image from file path | |
img = Image.open('Jaipur.jpg').convert('RGBA') | |
# Grab the dimensions | |
width, height = img.size | |
# We'll use either a random number or user specified number of vertices | |
print("Please enter the number of vertices (or enter 0 for a random amount): \n") | |
inputtedVertices = int(input()) | |
verticesCount = inputtedVertices if inputtedVertices != 0 else random.randint(500, 3000) | |
# Create `verticesCount` number of randomly located (x,y) points | |
randomVertices = np.random.random((verticesCount, 2)) | |
# We want to make sure the extremeties of the image are covered so we'll need to include the edges as well | |
edges = np.array([[0,0], [0,1], [1, 0], [1,1]]) | |
points = np.concatenate((randomVertices, edges)) | |
# Feed those newly created vertices into the Delaunay service | |
dt = Delaunay2D() | |
for point in points: | |
dt.addPoint(point) | |
# Create an image we can draw shapes (triangles) on | |
draw = ImageDraw.Draw(img) | |
# Create the vertices / compute the Delaunay transformation | |
delaunayVertices = dt.exportTriangles() | |
for triangleCoordinates in delaunayVertices: | |
# Get the coordinates for all vertices that comprise the triangle | |
x1, x2, x3 = points[triangleCoordinates[0]][0] * width, points[triangleCoordinates[1]][0] * width, points[triangleCoordinates[2]][0] * width | |
y1, y2, y3 = points[triangleCoordinates[0]][1] * height, points[triangleCoordinates[1]][1] * height, points[triangleCoordinates[2]][1] * height | |
# Find the center of the triangle | |
centerX = round((x1 + x2 + x3) / 3, 2) | |
centerY = round((y1 + y2 + y3) / 3, 2) | |
# Grab the RGB color of the pixel at the center of the triangle | |
r,g,b,a = img.getpixel((centerX, centerY)) | |
# Create a polygon and fill with color at that point in the image | |
draw.polygon([ | |
(x1, y1), | |
(x2, y2), | |
(x3, y3) | |
], fill=(r, g, b,random.randint(0, 256))) | |
# Output to image | |
img.save('./Output.png') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment