【问题标题】:Make an array like numpy.array() without numpy在没有 numpy 的情况下创建一个像 numpy.array() 这样的数组
【发布时间】:2019-09-25 10:22:29
【问题描述】:

我有一个图像处理任务,我们被禁止使用 NumPy,所以我们需要从头开始编写代码。我已经完成了逻辑图像转换,但现在我坚持创建一个没有 numpy 的数组。

这是我最后的输出代码:

Output :
new_log =
[[236, 
  232, 
  226, 
  .
  .
  .
 198,
 204]]

我需要将它转换为一个数组,这样我才能像这样(使用 Numpy)编写图像

new_log =
array([[236, 232, 226, ..., 208, 209, 212],
       [202, 197, 187, ..., 198, 200, 203],
       [192, 188, 180, ..., 205, 206, 207],
       ...,
       [233, 226, 227, ..., 172, 189, 199],
       [235, 233, 228, ..., 175, 182, 192],
       [235, 232, 228, ..., 195, 198, 204]], dtype=uint8)
cv.imwrite('log_transformed.jpg', new_log) 
# new_log must be shaped like the second output

【问题讨论】:

标签: python arrays image list numpy


【解决方案1】:

您可以使用与 NumPy 的 np.reshape() 类似的方式创建一个简单的函数来获取您的列表并重新调整它。但它不会很快,而且它对数据类型一无所知(NumPy 的dtype)所以......我的建议是挑战不喜欢 NumPy 的人。特别是如果您使用的是 OpenCV — it depends on NumPy!

以下是您可以在纯 Python 中执行的操作的示例:

def reshape(l, shape):
    """Reshape a list.

    Example
    -------
    >>> l = [1,2,3,4,5,6,7,8,9]
    >>> reshape(l, shape=(3, -1))
    [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    """
    nrows, ncols = shape
    if ncols == -1:
        ncols = len(l) // nrows
    if nrows == -1:
        nrows = len(l) // ncols
    array = []
    for r in range(nrows):
        row = []
        for c in range(ncols):
            row.append(l[ncols*r + c])
        array.append(row)
    return array

【讨论】:

  • -1 是什么意思?
  • 在 NumPy 的 reshape() 函数中,它是“我不知道”的一种通配符。这就是您所说的,例如,“我知道我想要 3 行,根据数组中的元素数量,您可以计算出我需要多少列”。
猜你喜欢
  • 2019-08-20
  • 1970-01-01
  • 2016-07-12
  • 1970-01-01
  • 2020-04-07
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多