Reputation: 301
I have the following Canvas
class for drawing color in a given pixel:
class Canvas:
def __init__(self,color,pixel):
self.color = color
self.pixel = pixel
self.im = np.zeros((pixel,pixel,3))
self.im[:,:] = color
def show(self):
plt.imshow(self.im)
plt.axis("off")
This simple class draws a square with color, for example:
purple = np.array([0.5, 0.0, 0.5])
C = Canvas(purple, 2001) # 2001 x 2001 pixels
C.show()
I want to create add_disk()
function with three argument: centroid,radius,color
. So that
C.add_disk((1001, 1001), 500, white)
C.show()
However, I am not sure how to do it using the math formula:
I think I can use np.meshgrid
to color white points, but how do I find those points and display on top of the square?
Upvotes: 2
Views: 2651
Reputation: 5000
So with meshgrid, using the shape of the self.im
, we first find the coordinates of the X
and Y
values in the 2D image. Then, we find all values whose coordinates follows the circle rule ((X - Ox) ** 2 + (Y - Oy)**2 <= R**2
).
import matplotlib.pyplot as plt
import numpy as np
class Canvas:
def __init__(self,color,pixel):
self.color = color
self.pixel = pixel
self.im = np.zeros((pixel,pixel,3))
self.im[:,:] = color
def show(self):
plt.imshow(self.im)
plt.axis("off")
def add_disk(self, centroid,radius,color):
x, y = np.meshgrid(np.arange(self.im.shape[0]), np.arange(self.im.shape[1]))
circle_pixels = (x - centroid[0]) ** 2 + (y - centroid[1]) ** 2 <= radius ** 2
self.im[circle_pixels, ...] = color
purple = np.array([0.5, 0.0, 0.5])
C = Canvas(purple, 2001) # 2001 x 2001 pixels
C.show()
white = np.array([255, 255, 255])
C.add_disk((1001, 1001), 500, white)
C.show()
Upvotes: 2