[英]Python 3 PIL: Converting a Numpy array of 3-tuples to an image in HSV
我正在嘗試編寫代碼來制作 Python 3 中的 Mandelbrot 分形圖像。該代碼在不使用 numpy arrays 的情況下工作,但速度很慢。 為了加快速度,我嘗試使用 numpy 和 numba。
在 PIL 中的 Image.fromarray() 中使用 numpy 數組的 3 元組時,生成的圖像是一系列垂直線,而不是預期的 Mandelbrot 圖像。 經過一些研究,我認為問題出在數據類型上,並且可能與有符號整數和無符號整數有關。 如果我在 numpy 數組中存儲 HSV 值的整數而不是 3 個元組,我可以讓事情正常工作。 不幸的是,這給出了一個黑白圖像,我想要一個彩色圖像。 另一個奇怪的事情是,每次運行代碼時,代碼生成的圖像都會略有變化。 我不確定這是一個相關的還是單獨的問題。 這是代碼,經過調整以刪除 mandelbrot 生成器並簡單地創建一個漸變圖像,它顯示了問題:
from PIL import Image, ImageDraw
from numba import jit
import numpy as np
@jit
def simple_image(width,height):
n3 = np.empty((width, height), dtype=object)
for i in range(width):
for j in range(height):
n3[i, j] = (min(j, 255), 255, 255)
return n3
arr = simple_image(800, 600)
im = Image.new('HSV', (800, 600), (0, 0, 0))
im = Image.fromarray(arr.astype(object), mode='HSV')
im.convert('RGB').save('output.png', 'PNG')
這是生成的圖像。 垂直線
當我對代碼進行一些更改以存儲整數並創建黑白圖像時,它可以工作:
from PIL import Image, ImageDraw
from numba import jit
import numpy as np
@jit
def simple_image(width,height):
n3 = np.empty((width, height))
for i in range(width):
for j in range(height):
n3[i, j] = min(j, 255)
return n3
arr = simple_image(800, 600)
im = Image.new('HSV', (800, 600), (0, 0, 0))
im = Image.fromarray(arr)
im.convert('RGB').save('output.png', 'PNG')
這是由於hpaulj的建議而回答問題的代碼。 numpy數組從3元組的2d數組更改為三維尺寸為3的3d數組。dtype在兩個位置設置為'uint8'。
from PIL import Image, ImageDraw
from numba import jit
import numpy as np
@jit
def white_image(width,height):
n3 = np.empty((width, height, 3), dtype='uint8')
for i in range(width):
for j in range(height):
n3[i, j, 0] = min(j, 255)
n3[i, j, 1] = 255
n3[i, j, 2] = 255
return n3
arr = white_image(800, 600)
im = Image.new('HSV', (800, 600), (0, 0, 0))
im = Image.fromarray(arr.astype('uint8'), mode='HSV')
im.convert('RGB').save('output.png', 'PNG')
這個問題正在解決一個特定於將 numba 與 PIL 一起使用的問題
如果有人從谷歌那里被引導到這篇文章,尋找一種從數組創建 HSV 圖像的簡單方法,這里有一個修改后的解決方案,它刪除了使用 numba 所特別需要的東西:
from PIL import Image, ImageDraw
import numpy as np
def color_image(width,height):
img = np.empty((height, width, 3), dtype='uint8')
for y in range(height):
for x in range(width):
img[y, x, 0] = int(255*x/width)
img[y, x, 1] = int(255*y/height)
img[y, x, 2] = 255
return img
arr = color_image(800, 600)
im = Image.fromarray(arr, mode='HSV')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.