In a 2D square grid (matrix) full of zeros
, I need to create a submatrix full of ones
, with the shape of this submatrix being as close as possible to a circle. I know a circle cannot be precisely represented when you work with cells or pixels, therefore I aim at a discretized circle.
The best thing I could come up with was this code, which produces square submatrices (the blue square in the image below):
from __future__ import division
import numpy
import matplotlib.pyplot as plt
import matplotlib.colors as mc
import random
import os
import math
n=101 #Grid size
empty_lattice=numpy.zeros((n,n)) #The empty 2D grid
x=int(numpy.random.uniform(0,n-1)) #X coord. top left corner
y=int(numpy.random.uniform(0,n-1)) #Y coord. top left corner
side=int(numpy.random.uniform(15,n)) #Side of the square approximating the circle
max_y=n-y #Checks the distance between the y of the submatrix origin and the matrix vertical boundary
max_x=n-x #Checks the distance between the x of the submatrix origin and the matrix horizontal boundary
max_width=0 #Initializes a maximum width for the loading submatrix
if max_y<max_x: #This assigns the minimum value between max_y and max_x to max_width, so that the submatrix is always a square
max_width=max_y
else:
max_width=max_x
if side>max_width:
for i in range(0,max_width):
for j in range(0, max_width):
empty_lattice[x+i][y+j]=1
else:
for i in range(0, side):
for j in range(0, side):
empty_lattice[x+i][y+j]=1
Now, visually this translates into the following image, but as you know there is a noticeable difference between the blue square and the inscribed circle in terms of area:
My question: how could I amend my code in order to be able to "smooth" the corners of my squares so that something which resembles a circle appears?
EDIT
The circles should be drawn even if they do not entirely reside within the grid boundaries (look at the image).