繁体   English   中英

制作一个像 numpy.array() 这样没有 numpy 的数组

[英]Make an array like numpy.array() without numpy

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

所以这是我最后的 output 代码:

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

您可以制作一个简单的 function 来获取您的列表并以与 NumPy 的np.reshape()类似的方式对其进行整形。 但它不会很快,而且它对数据类型(NumPy 的dtype )一无所知,所以......我的建议是挑战不喜欢 NumPy 的人。 特别是如果您使用的是 OpenCV - 它取决于 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM