Skip to content

Instantly share code, notes, and snippets.

@yoya
Last active January 30, 2022 14:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yoya/fb5de57bd35b15333e1e919996b095ef to your computer and use it in GitHub Desktop.
Save yoya/fb5de57bd35b15333e1e919996b095ef to your computer and use it in GitHub Desktop.
convolve repeated edge
import math
import numpy as np
def convolveRepeatedEdge(arr, kernel):
arrLen = len(arr)
kernelLen = len(kernel)
kernelLen_harf = math.floor((kernelLen - 1) / 2)
if type(arr) is list:
arr2 = [0] * arrLen
else:
arr2 = np.zeros(arrLen, dtype=arr.dtype)
for i in range(arrLen):
v = 0;
for k in range(kernelLen):
ii = i + k - kernelLen_harf
if ii < 0:
v += kernel[k] * arr[0]
elif ii < arrLen:
v += kernel[k] * arr[ii]
else:
v += kernel[k] * arr[arrLen-1]
arr2[i] = v;
return arr2;
@yoya
Copy link
Author

yoya commented Jan 30, 2022

import matplotlib.pyplot as plt

arr1 = [1, 1, 1, 1, 0, 0, 0, 0]
arr2 = [0, 0, 0, 0, 1, 1, 1, 1]
kernel = np.array([1, 2, 1]) / 4
arr11 = convolveRepeatedEdge(arr1, kernel)
arr22 = convolveRepeatedEdge(arr2, kernel)
plt.plot(arr11)
plt.plot(arr22)
plt.show()

convolveRepeatedEdge.png

@yoya
Copy link
Author

yoya commented Jan 30, 2022

from scipy import ndimage
import numpy as np
import matplotlib.pyplot as plt

arr1 = [1]*4 + [0]*4;
arr2 = [0]*4 + [1]*4;
kernel = np.array([1, 2, 1]) / 4
arr11 = np.zeros(len(arr1))
arr22 = np.zeros(len(arr2))
ndimage.convolve(arr1, kernel, arr11, mode='nearest')
ndimage.convolve(arr2, kernel, arr22, mode='nearest')
plt.plot(arr11)
plt.plot(arr22)
plt.show()

scipi.ndimage.convolve

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment