2015-05-08 95 views
1

我正在使用Wand Python Library,並試圖解決Python Challenge,而我當前的問題是要求我獲取所有偶數/奇數像素。獲取圖像的所有像素[Wand]

這顯然是一個非常簡單的任務。然而,我發現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) 

有什麼類似嗎?提前致謝。

回答

3

沒有試圖讀取Python的挑戰,只是專注於問題..

我喜歡的東西是這樣的:img.pixels

遍歷圖像尺寸收集wand.color.Color對象會很慢,因爲這會調用MagickWand的內部像素迭代&像素結構的重複使用。由於所說的挑戰是針對Python,而不是C緩衝區,所以我建議一次獲得像素數據的緩衝區。之後,您可以自由地迭代,比較,評估,不需要ImageMagick資源等。

在這個例子中,我假設圖像是一個2x2的PNG低於(縮放能見度。)

Example 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] 
+0

感謝您的幫助。如果我發現自己使用魔杖,我會使用這個,但我設法讓**枕頭**工作。 (我使用魔杖的唯一原因是枕頭不可用。) – SoftWalnut