【问题标题】:how to change all pixels in a given rectangle如何更改给定矩形中的所有像素
【发布时间】:2014-11-10 22:35:29
【问题描述】:

我需要创建一个函数,该函数接受矩形的尺寸,然后是所需的像素颜色。到目前为止,我的函数如下所示:

def makeRectangle(width, height, desiredPixel):

    # Begin with a rectangle image with all black pixels
    resultImage = EmptyImage(width, height)

    # Creates the total size of the rectangle image
    size = width * height

    # Change the color of all pixels
    for i in range(width):
        resultImage.setPILPixel(i, width, desiredPixel)

    return resultImage

我认为我需要使用嵌套的 for 循环,但我找不到改变所有像素颜色的方法。我现在拥有的函数会生成要更改的中间像素线。

【问题讨论】:

    标签: python pixel


    【解决方案1】:

    PIL有绘制矩形的功能:

    draw = ImageDraw.Draw(resultImage)
    draw.rectangle([0,0,width,height], fill=desiredPixel)
    

    在 Python 中循环很慢,所以最好找到一个优化的函数来做这种事情。

    【讨论】:

      【解决方案2】:

      不清楚您是想弄清楚如何循环,还是只想创建具有特定颜色的新图像。如果是后者,您可以在制作新图像时指定背景颜色,因此根本不需要循环:

      im = Image.new("RGB", (width, height), "white")
      

      或者您可以使用fill 或仅使用十六进制值来指定颜色:

      im = Image.new("RGB", (width,height), "#ddd" )
      

      【讨论】:

        【解决方案3】:

        您需要遍历 x 和 y 维度来更改所有像素:

        for x in range(width):
            for y in range(height):
                resultImage.setPILPixel(x, y, desiredPixel)
        

        应该可以解决问题。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-21
          • 1970-01-01
          • 2019-04-19
          相关资源
          最近更新 更多