没有尝试阅读 Python 挑战,而只是专注于这个问题..
我更喜欢这样的东西:img.pixels
迭代图像大小以收集wand.color.Color
对象会很慢,因为这会重复使用 MagickWand 的内部像素迭代和像素结构。正如所说的挑战是针对 Python 而不是 C 缓冲区,我建议获取一次像素数据缓冲区。之后,您可以自由地迭代、比较、评估等,而无需 ImageMagick 资源。
对于此示例,我假设图像是下面的 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]