Thank you so much Mr. @albanD!
The code works well in a significantly faster speed!
I have applied it into my training code. But the accuracy of the model seems still as low as before. The reason I think that the operations of replacing pixels by pixels may mess up the gradient of the input.
Suppose that I apply this function to an output of a conv2d() layer, can there be a way for the output to have a decent gradient that can be backwarded to the beginning?