简体   繁体   中英

Aligning Python lists to simulate a 1D kernel convolution

I have two Python lists, one conceptually representing a 1D kernel, and the other list is a sequence of values to be convoluted:

listA = [1, 2, 3, 4, 5, 6]

# Visualize it as if it was a Pandas dataframe:
+-----------------------+
| a | b | c | i | j | k |
+-----------------------+
| 1 | 2 | 3 | 4 | 5 | 6 |
+-----------------------+

kernel = [2, 4, 2]

What I want to do is to multiply my kernel by the corresponding 3 values on listA , with the center of the kernel being aligned with a given value. Example:

# Kernel centered at listA.b
+-----------------------+
| a | b | c | i | j | k |
+-----------------------+
| 1 | 2 | 3 | 4 | 5 | 6 |
+-----------------------+
+-----------+
| 2 | 4 | 2 |
+-----------+

# Kernel centered at listA.c
+-----------------------+
| a | b | c | i | j | k |
+-----------------------+
| 1 | 2 | 3 | 4 | 5 | 6 |
+-----------------------+
    +-----------+
    | 2 | 4 | 2 |
    +-----------+

# Kernel centered at listA.k
#  -> note that the kernel is too big, so some of the values
#     run off listA. This is the expected behavior
+-----------------------+
| a | b | c | i | j | k |
+-----------------------+
| 1 | 2 | 3 | 4 | 5 | 6 |
+-----------------------+
                +-------+
                | 2 | 4 |
                +-------+

How can I perform this alignment?

Please see if this helps,

# unpadded list
listA = [1, 2, 3, 4, 5, 6]

# 1x3 kernel
kernelA = [2, 4, 2]

# 1x5 kernel
kernelB = [1, 1, 1, 1, 1]


#kernel = kernelA
kernel = kernelB
loopVal = len(kernel) >> 1
#print(loopVal)


"""
# padded list on both sides
listB = listA.copy()
for i in range(0, loopVal):
    listB.insert(0, 0)
    listB.append(0)
print(listB)
print()
"""

# Full padded list on one side
listB = listA.copy()
for i in range(0, len(kernel) - 1):
    listB.append(0)
print(listB)
print()



## Does not use padded list
#sample = listA

## uses padded list
sample = listB


output = []
for i in range(loopVal, len(sample) - loopVal):
    tmp = 0
    for j in range(0, len(kernel)):
        print(sample[i - loopVal + j], kernel[j])
        tmp += sample[i - loopVal + j] * kernel[j]
    output.append(tmp)
    print(tmp)

print()
print("1D convolution output:")
print(output)

Output:

[1, 2, 3, 4, 5, 6, 0, 0, 0, 0]

1 1
2 1
3 1
4 1
5 1
15
2 1
3 1
4 1
5 1
6 1
20
3 1
4 1
5 1
6 1
0 1
18
4 1
5 1
6 1
0 1
0 1
15
5 1
6 1
0 1
0 1
0 1
11
6 1
0 1
0 1
0 1
0 1
6

1D convolution output:
[15, 20, 18, 15, 11, 6]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM