簡體   English   中英

如何顯示由像素 map 制成的圖像?

[英]How do I show an image made from a pixel map?

好的,所以我嘗試編輯圖像並將編輯結果轉換為像素 map。 效果很好,但我只是不知道如何將像素 map 轉換為實際圖像並顯示它。

這是我的代碼:

from PIL import Image
import numpy as np
img = Image.open('sample.jpg')
pixels = img.load()

for i in range(img.size[0]): # for every pixel:
    for j in range(img.size[1]):
        if pixels[i,j] == (255, 0, 0):
            pixels[i,j] = (0, 0 ,0)

im2 = Image.fromarray(pixels)
im2.show()

此外,我收到此錯誤消息:

Traceback (most recent call last):
  File "C:\Users\Haris.Sabotic\Desktop\Image Color Inverter\code.py", line 15, in <module>
    im2 = Image.fromarray(pixels)
  File "C:\Users\Haris.Sabotic\AppData\Local\Programs\Python\Python37-32\lib\site-packages\PIL\Image.py", line 2508, in fromarray
    arr = obj.__array_interface__
AttributeError: 'PixelAccess' object has no attribute '__array_interface__'

您不必將pixels轉換回圖像,因為pixels會更改原始img中的值 - 所以您必須顯示img.show()

from PIL import Image

img = Image.open('sample.jpg')
pixels = img.load()

width, height = img.size 
for col in range(width):
    for row in range(height):
        if pixels[col,row] == (255, 0, 0):
            pixels[col,row] = (0, 0 ,0)

img.show()

編輯:轉換為 numpy 數組時需要fromarray()

from PIL import Image
import numpy as np

img1 = Image.open('sample.jpg')

pixels = np.array(img1)

pixels[np.all(pixels == (255, 0, 0), axis=-1)] = (0,0,0)

img2 = Image.fromarray(pixels)
img2.show()

順便說一句:如果您必須在數組中獲取像素,請記住該數組使用[row,col]而不是[col,row]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM