1

我正在使用Wand Python Library,并尝试解决Python Challenge,而我当前的问题要求我获取所有偶数/奇数像素。

显然,这是一项非常简单的任务。但是,我发现 Wand 库在加载像素/复制像素方面非常慢(也许是因为我还将 fill_color 更改为每个像素的颜色?),我想知道我是否可以一次将它们全部加载。

我目前加载所有像素的解决方案是这样的:

from wand.image import Image
img = Image(filename="5808.jpg")
pixels = []
for x in range(img.width+1):
    for y in range(img.height+1):
        pixels.append(img[x, y])

print(pixels)

我更喜欢这样的东西:

from wand.image import Image
img = Image(filename="5808.jpg")
print(img.pixels)

有没有类似的东西?提前致谢。

4

1 回答 1

7

没有尝试阅读 Python 挑战,而只是专注于这个问题..

我更喜欢这样的东西:img.pixels

迭代图像大小以收集wand.color.Color对象会很慢,因为这会重复使用 MagickWand 的内部像素迭代和像素结构。正如所说的挑战是针对 Python 而不是 C 缓冲区,我建议获取一次像素数据缓冲区。之后,您可以自由地迭代、比较、评估等,而无需 ImageMagick 资源。

对于此示例,我假设图像是下面的 2x2 PNG (为可见性而缩放。)

示例 2x2 PNG

from wand.image import Image

# Prototype local variables
pixels = []
width, height = 0, 0
blob = None

# Load image
with Image(filename='2x2.png') as image:
    # Enforce pixels quantum between 0 & 255
    image.depth = 8
    # Save width & height for later use
    width, height = image.width, image.height
    # Copy raw image data into blob string
    blob = image.make_blob(format='RGB')

# Iterate over blob and collect pixels
for cursor in range(0, width * height * 3, 3):
    # Save tuple of color values
    pixels.append((blob[cursor],      # Red
                   blob[cursor + 1],  # Green
                   blob[cursor + 2])) # Blue
print(pixels)
#=> [(255, 0, 0), (0, 0, 255), (0, 128, 0), (255, 255, 255)]

这个例子很快,但请记住 Python 很好地处理对象。让我们扩展Image对象,并创建方法来满足img.pixels.

# Lets create a generic pixel class for easy color management
class MyPixel(object):
    red = 0
    green = 0
    blue = 0
    def __init__(self, red=0, green=0, blue=0):
        self.red = red
        self.green = green
        self.blue = blue
    def __repr__(self):
        return u'#{0.red:02X}{0.green:02X}{0.blue:02X}'.format(self)

# Extend wand.image.Image and add a new `img.pixels` pseudo-attribute
class MyImage(Image):
    # Repeat above example
    @property
    def pixels(self):
        pixels = []
        self.depth = 8
        blob = self.make_blob(format='RGB')
        for cursor in range(0, self.width * self.height * 3, 3):
            pixel = MyPixel(red=blob[cursor],
                            green=blob[cursor + 1],
                            blue=blob[cursor + 2])
            pixels.append(pixel)
        return pixels

# Call your custom class; which, collects your custom pixels
with MyImage(filename=filename) as img:
    print(img.pixels)
#=> [#FF0000, #0000FF, #008000, #FFFFFF]
于 2015-05-11T14:12:50.767 回答