Monday, 9 May 2016

matrix - Python - Circle patter




I would like to create a circle in zeros matrix by changing specific positions from 0 to 1. Unfortunately, something is wrong in my if statement I cannot figure it out. Thanks for helping me!



img = np.zeros((20,20))
def convert2file(image, newfile):
img = Image.new('RGB', (len(image), len(image[0])), "black")
pixels = img.load()

for i in range(len(image)):
for j in range (len(image[i])):
if image[i][j] == 0:
pixels[j,i] = black
else:
pixels[j,i] = white


save2file(img, newfile)
def gen_circle(image):
ret = np.copy(image)
for i in range(len(image)):
for j in range(len(image[i])):
if fabs((j - len(image)/2)**2 + (i - len(image)/2)**2 - len(image)/2**2) == 0.5**2:
ret[i][j] = 1
return ret

draw_pic(gen_circle(img))

Answer



How about this code:



def gen_circle(image):
ret = np.copy(image)
radius = len(image)/2
radius_sq = radius**2
for i in range(len(image)):
for j in range(len(image[i])):
if (i-radius)**2 + (j-radius)**2 <= radius_sq:
ret[i][j] = 1
return ret

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...