I have the following for loop and want to use numpy vectorizing, boolean, mask arrays etc to improve the execution speed. arr is a numpy array
def translate(arr, x=0):
arr1 = arr.copy()
for i in range(arr1.shape[0]):
for j in range(arr1.shape[1]):
if i + x < arr1.shape[0] and i + x > 0:
arr1[i,j] = arr[i+x,j]
if i + x < 0 or i + x > arr1.shape[0]:
arr1[i,j] = 255
return arr1
Any help or suggestions will be much appreciated.
Edit: instead of 255, when (i+x) <0, it should be arr[i,j]
def translate(arr, x=0):
arr1 = arr.copy()
for i in range(arr1.shape[0]):
for j in range(arr1.shape[1]):
if i + x < arr1.shape[0] and i + x > 0:
arr1[i,j] = arr[i+x,j]
if i + x < 0 or i + x > arr1.shape[0]:
arr1[i,j] = arr[i,j]
return arr1
Since @Paul Panzer solution didn't give out the same output as your function, I revised on his work by trying boolean array. Hopefully its what you want.
Code:
def my_translate(arr, x=0):
arr = arr.copy()
if x == 0:
return arr.copy()
elif x > 0:
replacement1 = np.zeros(arr.shape)
replacement1[:-x] = arr[x:]
else:
replacement1 = np.zeros(arr.shape)
replacement1[-x:] = arr[:x]
replacement2 = np.zeros(arr.shape)+255 # Array filled with 255 for second logic
l = [np.repeat(i,arr.shape[1]) for i in range(arr.shape[0])]
firstlooplogic1 = np.asarray(l)+x < arr.shape[0]
firstlooplogic2 = np.asarray(l)+x > 0
secondlooplogic1 = np.asarray(l)+x > arr.shape[0]
secondlooplogic2 = np.asarray(l)+x < 0
part1logic = np.logical_and(firstlooplogic1,firstlooplogic2)
part2logic = np.logical_or(secondlooplogic1,secondlooplogic2)
part1 = part1logic*replacement1
part2 = part2logic*replacement2
part3 = ((part1 == 0) * (part2 == 0)) * arr
return (part1 + part2 +part3).astype(arr.dtype)
Result:
arr = 3 - np.maximum.outer(*2*(np.abs(np.arange(-3, 4)),))
output1 = my_translate(arr,-2) #output from my function
output2 = translate(arr,-2) #output from your function above
np.array_equal(output1,output2)
>Out[10]: True
Basically, I just break down your nested for-loop into boolean array and do the operation.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments