【问题标题】:How to create a 2D numpy array of pixel values?如何创建像素值的二维 numpy 数组?
【发布时间】:2022-01-08 15:14:39
【问题描述】:

我想为 512 x 512 图像创建一个包含所有像素位置的 2d numpy 数组。这意味着会有 5122 或 262,144 个值。如果考虑 x 和 y 零,可能会稍微多一些,但你明白了。

手动操作会像这样pixels = np.array([[0, 1], [0, 2], [0,3], [0,4]]) 一直到最后。但显然我需要自动化它。像素的顺序并不重要。它需要采用这种“格式”,以便我可以通过 0 和 1 索引访问像素 x 和 y 值,即pixels[0][0] 用于第一个像素的 x 值,pixels[0][1] 用于第一个像素的 y 值。

【问题讨论】:

  • 只需使用for-loops 来自动化它。

标签: python arrays numpy


【解决方案1】:

试试这个:

pixels = np.array([[x, y] for y in range(512) for x in range(512)])

请注意,您可以针对不同的 x 或 y 值对其进行修改。

【讨论】:

    【解决方案2】:

    numpy 公开用于通过多维arrays 处理和操作图像,因为它们对于存储非常有用 > 作为像素(rgbrgbagreyscale 等...)

     RGB:

    >>> import numpy as np
    >>> from PIL import Image
    >>> array = np.zeros([100, 200, 3], dtype=np.uint8)
    >>> array[:,:100] = [255, 128, 0] #Orange left side
    >>> array[:,100:] = [0, 0, 255]   #Blue right side
    >>> img = Image.fromarray(array)
    >>> array[:,:100] = [100, 128, 0]
    >>> array[:,100:] = [0, 0, 200]
    >>> img = Image.fromarray(array)
    >>> img.save('img.png')
    

     灰度:

    >>> import numpy as np
    >>> from PIL import Image
    >>> array = np.zeros([100, 200], dtype=np.uint8)
    >>> # Set grey value to black or white depending on x position
    >>> for x in range(200):
    >>>     for y in range(100):
    >>>         if (x % 16) // 8 == (y % 16) // 8:
    >>>             array[y, x] = 0
    >>>         else:
    >>>             array[y, x] = 255
    >>>
    >>> img = Image.fromarray(array)
    >>> img.save('img.png')
    

    【讨论】:

      猜你喜欢
      • 2020-02-21
      • 1970-01-01
      • 2023-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-27
      • 2020-09-10
      相关资源
      最近更新 更多