I don't see how your code even attempt to answer your assignment.
Which of the image processing function would you use to detect objects in an image?
Which other image processing function would you use to know the size of such objects once detected?
Once you know which pixel belong to which object (from the first function) and the size of such object, it's easy to copy them to the correct image.
I'm afraid I won't give you any more hint than that. It's not a particularly difficult task.