You can do the same as the example you show here.
In this example, img is a leaf (it was not created in a differentiable manner, it is just a Tensor that you optmize over) so it will also work with pytorch if you do that.