Изображение PIL из numpy индексация массива - PullRequest
0 голосов
/ 05 августа 2020

Я конвертирую логический массив numpy (ie, маска) в изображение PIL и вижу очень странное поведение.

# using PIL pixel access - works as expected
img = Image.new('1', (100, 100)) # '1' for 1-bit image mode
img_pixels = img.load()

for x in range(1, 99):
    for y in range(1, 50):
        img_pixels[x,y] = True

img

PIL Pixel Access version

# Numpy array, turning into a PIL image. 
ary = np.zeros((100,100), dtype=np.bool)

for x in range(1, 99):
    for y in range(1, 50):
        ary[x,y] = True
      
Image.fromarray(ary)

numpy version

If I inspect the values of ary it appears the True values are appropriately set.

So why are these images different?

Edit:

If I reverse x and y for the numpy version I get this. It's clear that something else is going on because if it was just rows and columns reversed I should get the same shape but vertically aligned.

ary = np.zeros((100,100), dtype=np.bool)

for x in range(1, 99):
    for y in range(1, 50):
        ary[y,x] = True # note that rows and columns are reversed
      
Image.fromarray(ary)

numpy с использованием столбца, порядка строк

Ответы [ 2 ]

1 голос
/ 05 августа 2020

PIL имеет обратные адреса x и y. Чтобы исправить это, замените x и y в своем коде:

ary = np.zeros((100,100), dtype=np.bool)

for x in range(1, 99):
    for y in range(1, 50):
        ary[y,x] = True
      
Image.fromarray(ary)

введите описание изображения здесь

0 голосов
/ 05 августа 2020

Это оказалось ошибкой в ​​более ранней версии PIL, которая была исправлена ​​по крайней мере в версии 7.0

с

  • PIL: 7.2.0
  • numpy: 1.19.1

поведение соответствует ожидаемому. Спасибо @furas за его помощь в тестировании.

...