0

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))

2 Answers2

0

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
John Anderson
  • 35,991
  • 4
  • 13
  • 36
  • 1
    `ret[i][j] = 1` --> `ret[i,j] = 1` ... https://docs.scipy.org/doc/numpy/user/basics.indexing.html#single-element-indexing – wwii Nov 22 '18 at 02:12
-1

You need to fix the calculation for a couple reasons:

It is very difficult to get an arbitrary calculation to match a floating point value

Almost all of your calculation result in a value that is larger than 0 (some even exceed 100), so most of it will be equal to false

The value of i and j is not balanced (as you started from 0 and end at 19)

You need to select an arbitrary value as the condition (by looking at each of the calculation result, or by trial-and-error) and make the condition to be less than that (to fill the circle up).

import numpy as np
from math import fabs

img = np.zeros((20,20))

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

print(gen_circle(img))
Andreas
  • 2,455
  • 10
  • 21
  • 24