Skip to content

Image.filter gives wrong result when using asymmetric kernels #3134

Description

@Perfec-specops

Problem

When filtering an array like [[0,0,0],[0,1,0],[0,0,0]](the central element is 1 and the others are 0) with a kernel like [1, 2, 3, 4, 5, 6, 7, 8, 9], a correlation will generate [[9,8,7],[6,5,4],[3,2,1]] and a convolution will generate [[1, 2, 3], [4, 5, 6], [7, 8, 9]], if we don't consider the border.

However, Pillow generates neither of them.

This behavior won't affect results of symmetric kernels we use all the time, so only in some rare cases it will cause wrong result.

from PIL import Image, ImageFilter
import numpy as np

kernel=[1, 2, 3, 4, 5, 6, 7, 8, 9]
image=np.array([
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.]], 'uint8')

img=Image.fromarray(image,'L')
img=img.filter(ImageFilter.Kernel((3,3),kernel,1))

print(np.array(img))

# result:
#[[0 0 0 0 0 0 0]
# [0 0 0 0 0 0 0]
# [0 0 3 2 1 0 0]
# [0 0 6 5 4 0 0]
# [0 0 9 8 7 0 0]
# [0 0 0 0 0 0 0]
# [0 0 0 0 0 0 0]]

# expect:
# the correlation
#[[ 0.  0.  0.  0.  0.  0.  0.]
# [ 0.  0.  0.  0.  0.  0.  0.]
# [ 0.  0.  9.  8.  7.  0.  0.]
# [ 0.  0.  6.  5.  4.  0.  0.]
# [ 0.  0.  3.  2.  1.  0.  0.]
# [ 0.  0.  0.  0.  0.  0.  0.]
# [ 0.  0.  0.  0.  0.  0.  0.]]
# or the convolution
#[[ 0.  0.  0.  0.  0.  0.  0.]
# [ 0.  0.  0.  0.  0.  0.  0.]
# [ 0.  0.  1.  2.  3.  0.  0.]
# [ 0.  0.  4.  5.  6.  0.  0.]
# [ 0.  0.  7.  8.  9.  0.  0.]
# [ 0.  0.  0.  0.  0.  0.  0.]
# [ 0.  0.  0.  0.  0.  0.  0.]]

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions