沒有試圖讀取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]
感謝您的幫助。如果我發現自己使用魔杖,我會使用這個,但我設法讓**枕頭**工作。 (我使用魔杖的唯一原因是枕頭不可用。) – SoftWalnut