W Allen
W Allen

Reputation: 23

How to extract coins out of an image?

So I want to segment and extract the coins out of the image and use them for other purposes. But I ran into problems extracting those coins out first. The background shouldn't be white all the time.

enter image description here

I've tried thresholding and find the contours, but it returns more contours than expected. What should I do?

cv::Mat coinpic, backgroundpic, diffpic, newpic, threshold;

cv::cvtColor([self cvMatFromUIImage:coins], coinpic, cv::COLOR_BGR2GRAY);

cv::threshold(coinpic, diffpic, 200, 255, cv::THRESH_BINARY_INV+cv::THRESH_OTSU);

vector<vector<cv::Point>> contours;
vector<cv::Vec4i> hierarchy;

cv::findContours(diffpic, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE);

cout << contours.size() << endl;

return [self UIImageFromCVMat:diffpic];

The result I expect is like this following link: https://docs.opencv.org/3.4.3/d3/db4/tutorial_py_watershed.html

Upvotes: 0

Views: 444

Answers (1)

L.C.
L.C.

Reputation: 1145

Coins detection is the typical example where you (most probably) want to use Hough Transform for circles. It implemented in OpenCV and you can find several examples, for example here and here (these are in Python, but you can find many others)

You will probably get more (or not all) contours at the first attempt, to fix this you should play with param1 and param2 (see the opencv documentation)

Upvotes: 1

Related Questions