我正在尝试通过将numpy matrix
转换为图像来制作圆形图像,但是当输入为50
或更高时,图像上会出现奇怪的缺失线。我怎样才能解决这个问题?
输入确定矩阵的大小,50
的输入构成50 by 50
矩阵。我是一个初学者程序员,这是我第一次问堆栈溢出问题,所以请不要苛刻:)这是我的代码。
from PIL import Image
import itertools
np.set_printoptions(threshold=np.inf)
inp = int(input("Input size of matrix"))
dt = np.dtype(np.int8)
M = np.zeros((inp, inp), dtype=dt)
A = (list(itertools.product(range(0, inp), repeat=2)))
count1 = 0
for n in A:
x = (int(n[0]) / (inp - 1)) * 2
y = (int(n[1]) / (inp - 1)) * 2
if (x ** 2) + (y ** 2) - (2 * x) - (2 * y) <= -1:
M[int(x * (inp - 1)/2), int(y * (inp - 1)/2)] = 1
count1 += 1
print(M)
im = Image.fromarray(M * 255)
im.show()
print("Approximation of pi: " + str(4 * (count1 / inp ** 2))) ```
from PIL import Image
import itertools
np.set_printoptions(threshold=np.inf)
inp = int(input("Input size of matrix"))
dt = np.dtype(np.int8)
M = np.zeros((inp, inp), dtype=dt)
A = (list(itertools.product(range(0, inp), repeat=2)))
count1 = 0
for n in A:
x = (int(n[0]) / (inp - 1)) * 2
y = (int(n[1]) / (inp - 1)) * 2
if (x ** 2) + (y ** 2) - (2 * x) - (2 * y) <= -1:
M[round(x * (inp - 1)/2), round(y * (inp - 1)/2)] = 1
count1 += 1
print(M)
im = Image.fromarray(M * 255)
im.show()
print("Approximation of pi: " + str(4 * (count1 / inp ** 2)))
我认为这是另一个具有预期输出的解决方案,这是一个简单的解决方案,无需将float转换为整数(对于索引):
import itertools
import numpy as np
np.set_printoptions(threshold=np.inf)
inp = int(input("Input size of matrix"))
dt = np.dtype(np.int8)
M = np.zeros((inp, inp), dtype=dt)
A = (list(itertools.product(range(0, inp), repeat=2)))
# assign the center
cx,cy=int(inp/2), int(inp/2)
# assign the radius
rad=int(inp/2)
count1 = 0
for n in A:
# calculate distance of a point from the center
dist = np.sqrt((n[0]-cx)**2+(n[1]-cy)**2)
# Assign 1 where dist < rad.
if dist < rad:
M[n[0], n[1]] = 1
count1 += 1
print(M)
im = Image.fromarray(M * 255)
im.show()
print("Approximation of pi: " + str(4 * (count1 / inp ** 2)))