【问题标题】:Incorrect results when applying operations to a matrix对矩阵应用运算时结果不正确
【发布时间】:2020-02-08 06:24:43
【问题描述】:

我试图通过将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))) ```

【问题讨论】:

  • 我说奇怪的行只出现在等于或大于 50 的值上,但我意识到问题出现在 input = 48 上,而不是 input = 49 上,所以我不确定是什么发生

标签: python numpy


【解决方案1】:

问题出在这一行:M[int(x * (inp - 1)/2), int(y * (inp - 1)/2)] = 1 实际上,这一行在某些索引中分配了 1 两次,并错过了一些索引,因为您使用的是 int()。使用round() 获取最接近的整数。这会有所帮助。将这一行:M[int(x * (inp - 1)/2), int(y * (inp - 1)/2)] = 1 改为这一行:M[round(x * (inp - 1)/2), round(y * (inp - 1)/2)] = 1

您的代码应如下所示:

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

我认为这是另一个具有预期输出的解决方案,它是一个简单的解决方案,无需将浮点数转换为整数(用于索引):

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

【讨论】:

  • @CarlosViramontes 嗨,我更新了答案。它现在有两种解决方案。我认为更新的答案解决了您的问题。如果你这么认为,那么请接受我的回答。谢谢。
  • 非常感谢,感谢您检查我的代码为什么不起作用。它帮助我解决了另一个我试图用不同的代码解决的问题。
猜你喜欢
  • 1970-01-01
  • 2013-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多