将运算应用于矩阵时结果不正确

问题描述 投票:0回答:1

我正在尝试通过将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))) ```
python numpy
1个回答
0
投票
您的代码应如下所示:

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)))
© www.soinside.com 2019 - 2024. All rights reserved.