How to add blob like loss constraints that are differentiable in pytorch

Related to this question:

I would also like to know more information regarding this question. It seems to have no answer.
I will like to know if there is a way to add loss constraint based blob/shape characteristics while respecting the loss differentiability. Here are some example of desired constraint :

  1. penalize if number of blobs exceeds
  2. penalize so that a specific class segmentation is included into another one. I thought maybe by multiplication with the thresholded segmentation map it will force inclusion not really a loss constraint however.
  3. penalize if the blob is not convex.

Thanks for your help.