python - 用灰色背景填充图像数组

标签 python numpy python-imaging-library

我通过使用 Image.fromarray(np.haystack(<list of image array>).show() 并排显示缩略图来比较缩略图。问题是图像数组的大小不同。我的解决方案是用背景灰色(200、200、200)填充数组,并使所有数组的大小相等200x200。

我的问题 numpy 有更直接的方法吗?

我的解决方案:

def pad_with_gray_backgound(_array, size):
    array_padded = np.ones((size, size, 3), dtype=np.uint8)*200

    for i in range(array_padded.shape[0]):
        for j in range(array_padded.shape[1]):
            try:
                array_padded[i, j] = _array[i, j]
            except IndexError:
                pass

    return array_padded

并调用此函数

import numpy as np
from PIL import Image

image_arrays = []
for pic in pic_selection:
    pic_thumbnail = io.BytesIO(pic.thumbnail.encode('ISO-8859-1'))
    padded_image_array = pad_with_gray_background(
        np.array(Image.open(pic_thumbnail)), 200)

    image_arrays.append(padded_image_array)

Image.fromarray(np.hstack(image_arrays)).show()

注意 pic.thumbnail 是从 exif 中获取的字节对象

最佳答案

Mark Setchell 的回答是使用切片:

array_padded[0:height, 0:width, :] = image_array[:]

只要确保 image_array 的形状不大于 array_padded 即可。

import numpy as np
from PIL import Image

image_arrays = []
for pic in pic_selection:
    pic_thumbnail = io.BytesIO(pic.thumbnail.encode('ISO-8859-1'))
    image_array = np.array(Image.open(pic_thumbnail))

    height, width = (200, 200)
    array_padded = np.ones((height, width, 3), dtype=np.uint8)*200
    height = min(image_array.shape[0], height)
    width = min(image_array.shape[1], width)
    array_padded[0:height, 0:width, :] = image_array[0:height, 0:width, :]
    image_arrays.append(array_padded)

Image.fromarray(np.hstack(image_arrays)).show()

关于python - 用灰色背景填充图像数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58195591/

相关文章:

python - pandas pivot_table 中的意外结果

python - 将 np.where 数组转换为列表

python - PIL打开tif图像只有一个 channel

python - RGB 到 HSV Python,不断改变色调

python - 无论输入如何,神经网络都会产生相同的输出

python - 在 django 网页中显示 ip 摄像头实时反馈

python - 为 dask 数据框列创建 dask 列表

python - QtDesigner 还是手动完成所有 Qt 样板文件?

python - 在 python 列表中抓取唯一的元组,不管顺序如何

python - 如何将分割的图像与重叠合并