'Differentiate between appending objects with similar color

I am trying to detect each ball, count how many there are, and get their location. I am currently using Canny Edge Detection for that which works pretty well if the balls don't touch each other:

Canny Detection with balls not touching each other

The problem I have is that if the balls are touching, it is not possible to differentiate between them anymore and they are treated as one object:

Canny Detection with balls touching each other

I tried to use HoughCircles, but found that this only works well with actual circles, not distorted ones.

So how would I go about finding a solution? Is there any algorithm that fits better for this problem, or can I somehow work out the individual circles in each contour?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source