I am very new to OpenCV and I am trying to detect just the penny image, but I am getting a bunch of smaller circles. Can someone tell me what Im doing wrong?
Code from here: https://github.com/opencv/opencv/blob/master/samples/cpp/houghcircles.cpp
Only things I changed were to make min circle radius 400, and max of circle 0. Because I know the image will be 600x480 so the penny circle must be at least 400.
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>
using namespace cv;
using namespace std;
static void help()
{
cout << "\nThis program demonstrates circle finding with the Hough transform.\n"
"Usage:\n"
"./houghcircles <image_name>, Default is ../data/board.jpg\n" << endl;
}
int main(int argc, char** argv)
{
cv::CommandLineParser parser(argc, argv,
"{help h ||}{#image|../data/board.jpg|}"
);
if (parser.has("help"))
{
help();
return 0;
}
//![load]
string filename = parser.get<string>("#image");
Mat img = imread(filename, IMREAD_COLOR);
if(img.empty())
{
help();
cout << "can not open " << filename << endl;
return -1;
}
//![load]
//![convert_to_gray]
Mat gray;
cvtColor(img, gray, COLOR_BGR2GRAY);
//![convert_to_gray]
//![reduce_noise]
medianBlur(gray, gray, 5);
//![reduce_noise]
//![houghcircles]
vector<Vec3f> circles;
HoughCircles(gray, circles, HOUGH_GRADIENT, 1,
gray.rows/16, // change this value to detect circles with different distances to each other
100, 30, 400,0 // change the last two parameters
// (min_radius & max_radius) to detect larger circles
);
//![houghcircles]
//![draw]
for( size_t i = 0; i < circles.size(); i++ )
{
Vec3i c = circles[i];
circle( img, Point(c[0], c[1]), c[2], Scalar(0,0,255), 3, LINE_AA);
circle( img, Point(c[0], c[1]), 2, Scalar(0,255,0), 3, LINE_AA);
}
//![draw]
//![display]
imshow("detected circles", img);
waitKey();
//![display]
return 0;
}
You've got radius and diameter mixed up. Your minimum radius cannot be 400 if your image is only 600x480. Set your min_radius to 200.
HoughCircles(gray, circles, HOUGH_GRADIENT, 1,
max(gray.cols,gray.rows), // to find only the biggest perfect circle
100, 100, 0,0 // leave other params as default
);
Related
I have been trying to develop a program - written with C++ and using OpenCV -which counts the overall value of coins shown in some image.
I should note that I am new to the opencv platform.
In order to achieve this goal, as far as I understand - there has to be a use of the Hough transform to detect the ratio of the coins. I found this code example on the OpenCV site, but I can't put a value for the coins.
Here is what I have done so far.
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>
using namespace std;
using namespace cv;
namespace
{
const std::string windowName = "Coins detection";
const std::string cannyThresholdTrackbarName = "Canny threshold";
const std::string accumulatorThresholdTrackbarName = "Accumulator Threshold";
const int cannyThresholdInitialValue = 41;
const int accumulatorThresholdInitialValue = 87;
const int maxAccumulatorThreshold = 200;
const int maxCannyThreshold = 255;
void HoughDetection(const Mat& src_gray, const Mat& src_display, int cannyThreshold, int accumulatorThreshold)
{
std::vector<Vec3f> circles;
HoughCircles( src_gray, circles, HOUGH_GRADIENT, 1, src_gray.rows/8, cannyThreshold, accumulatorThreshold, 0, 0 );
Mat display = src_display.clone();
for( size_t i = 0; i < circles.size(); i++)
{
Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
int radius = cvRound(circles[i][2]);
circle( display, center, 3, Scalar(0,255,0), -1, 8, 0 );
circle( display, center, radius, Scalar(0,0,255), 3, 8, 0 );
}
imshow( windowName, display);
}
}
int main(int argc, char** argv)
{
Mat src, src_gray;
String imageName("c:\\moedas.jpg");
if (argc > 1)
{
imageName = argv[1];
}
src = imread( imageName, IMREAD_COLOR );
if( src.empty() )
{
std::cerr<<"Invalid input image\n";
return -1;
}
cvtColor( src, src_gray, COLOR_BGR2GRAY );
GaussianBlur( src_gray, src_gray, Size(9, 9), 2, 2 );
int cannyThreshold = cannyThresholdInitialValue;
int accumulatorThreshold = accumulatorThresholdInitialValue;
namedWindow( windowName, WINDOW_AUTOSIZE );
createTrackbar(cannyThresholdTrackbarName, windowName, &cannyThreshold,maxCannyThreshold);
createTrackbar(accumulatorThresholdTrackbarName, windowName, &accumulatorThreshold, maxAccumulatorThreshold);
char key = 0;
while(key != 'q' && key != 'Q')
{
cannyThreshold = std::max(cannyThreshold, 1);
accumulatorThreshold = std::max(accumulatorThreshold, 1);
HoughDetection(src_gray, src, cannyThreshold, accumulatorThreshold);
key = (char)waitKey(10);
}
return 0;
}
The code you have so far only segments circle shapes in an input image. This is just the first step to count the coins. There are many ways to perform that task, ranging from simple contour counting techniques to complicated deep learning, and the explanation of such techniques is too broad and large in scope to put efficiently and concisely in an SO answer. However, here are some coin detectors/counter implementations/tutorials that you can check:
Implementation 1 in Python. This is the best of the list, although the code file is larger than yours, not too hard to port to C++. It has the best detection/counting performance but deals with Neural Networks, specifically, a Multilayer Perceptron.
Implementation 2 in Python. This is a very small code file, nearly as large as yours and has no idiomatic Python code, porting it to C++ is a no brainer, you should start here. This implementation uses mere contour counting with the aid of the Canny edge detector.
Tutorial 1 in C++. A simple tutorial in C++, but only serves introductory purposes, the implementations listed above are the real thing.
My goal is to find the biggest contour of a captured webcam frame, then after it's found, find its size and determine either to be rejected or accepted.
Just to explain the objetive of this project, i am currently working for a Hygiene product's Manufacturer. There we have, in total, 6 workers that are responsible for sorting the defective soap bars out of the production line. So in order to gain this workforce for other activities, i am trying to write an algorithm to "replace" their eyes.
I've tried several methods along the way (findcontours, SimpleBlobDetection, Canny, Object tracking), but the problem that i've been facing is that i can't seem to find a way to effectively find the biggest object in a webcam image, find its size and then determine to either discard or accept it.
Below follows my newest code to find the biggest contour in an webcam stream:
#include <iostream>
#include "opencv2/highgui/highgui.hpp"
#include "opencv/cv.h"
#include "opencv2\imgproc\imgproc.hpp"
using namespace cv;
using namespace std;
int main(int argc, const char** argv)
{
Mat src;
Mat imgGrayScale;
Mat imgCanny;
Mat imgBlurred;
/// Load source image
VideoCapture capWebcam(0);
if (capWebcam.isOpened() == false)
{
cout << "Não foi possível abrir webcam!" << endl;
return(0);
}
while (capWebcam.isOpened())
{
bool blnframe = capWebcam.read(src);
if (!blnframe || src.empty())
{
cout << "Erro! Frame não lido!\n";
break;
}
int largest_area = 0;
int largest_contour_index = 0;
Rect bounding_rect;
Mat thr(src.rows, src.cols, CV_8UC1);
Mat dst(src.rows, src.cols, CV_8UC1, Scalar::all(0));
cvtColor(src, imgGrayScale, CV_BGR2GRAY); //Convert to gray
GaussianBlur(imgGrayScale, imgBlurred, Size(5, 5), 1.8);
Canny(imgBlurred, imgCanny, 45, 90); //Threshold the gray
vector<vector<Point>> contours; // Vector for storing contour
vector<Vec4i> hierarchy;
findContours(imgCanny, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE); // Find the contours in the image
for (int i = 0; i < contours.size(); i++) // iterate through each contour.
{
double a = contourArea(contours[i], false); // Find the area of contour
if (a > largest_area)
{
largest_area = a;
largest_contour_index = i; //Store the index of largest contour
bounding_rect = boundingRect(contours[i]); // Find the bounding rectangle for biggest contour
}
}
Scalar color(255, 255, 255);
drawContours(dst, contours, largest_contour_index, color, CV_FILLED, 8, hierarchy); // Draw the largest contour using previously stored index.
rectangle(src, bounding_rect, Scalar(0, 255, 0), 1, 8, 0);
imshow("src", src);
imshow("largest Contour", dst);
waitKey(27);
}
return(0);
}
And here are the results windows that the program generates and the image of the object that i want to detect and sort.
Thank you all in advance for any clues on how to achieve my goal.
I'm trying to count object from image. I use logs photo, and I use some steps to get a binary image.
This is my code:
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <features2d.hpp>
using namespace cv;
using namespace std;
int main(int argc, char *argv[])
{
//load image
Mat img = imread("kayu.jpg", CV_LOAD_IMAGE_COLOR);
if(img.empty())
return -1;
//namedWindow( "kayu", CV_WINDOW_AUTOSIZE );
imshow("kayu", img);
//convert to b/w
Mat bw;
cvtColor(img, bw, CV_BGR2GRAY);
imshow("bw1", bw);
threshold(bw, bw, 40, 255, CV_THRESH_BINARY);
imshow("bw", bw);
//distance transform & normalisasi
Mat dist;
distanceTransform(bw, dist, CV_DIST_L2, 3);
normalize(dist, dist, 0, 2., NORM_MINMAX);
imshow("dist", dist);
//threshold to draw line
threshold(dist, dist, .5, 1., CV_THRESH_BINARY);
imshow("dist2", dist);
//dist = bw;
//dilasi
Mat dilation, erotion, element;
int dilation_type = MORPH_ELLIPSE;
int dilation_size = 17;
element = getStructuringElement(dilation_type, Size(2*dilation_size + 1, 2*dilation_size+1), Point(dilation_size, dilation_size ));
erode(dist, erotion, element);
int erotionCount = 0;
for(int i=0; i<erotionCount; i++){
erode(erotion, erotion, element);
}
imshow("erotion", erotion);
dilate(erotion, dilation, element);
imshow("dilation", dilation);
waitKey(0);
return 0;
}
As you can see, I use Erosion and Dilation to get better circular object of log. My problem is, I'm stuck at counting the object. I tried SimpleBlobDetector but I got nothing, because when I try to convert the result of "dilation" step to CV_8U, the white object disappear. I got error too when I use findContours(). It say something about channel of image. I can't show the error here, because that's too many step and I already delete it from my code.
Btw, at the end, i got 1 channel of image.
Can i just use it to counting, or am i have to convert it and what is the best method to do it?
Two simple steps:
Find contours for the binarized image.
Get the count of the contours.
Code:
int count_trees(const cv::Mat& bin_image){
cv::Mat img;
if(bin_image.channels()>1){
cv::cvtColor(bin_image,img,cv::COLOR_BGR2GRAY);
}
else{
img=bin_image.clone();;
}
if(img.type()!=CV_8UC1){
img*=255.f; //This could be stupid, but I do not have an environment to try it
img.convertTo(img,CV_8UC1);
}
std::vector<std::vector<cv::Point>> contours
std::vector<Vec4i> hierarchy;
cv::findContours( img, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
return contours.size();
}
I have the same problem, here's an idea I'm about to implement.
1) Represent your image as an array of integers; 0 = black, 1 = white.
2) set N = 2;
3) Scan your image, pixel-by-pixel. Whenever you find a white pixel, activate a flood-fill algorithm, starting at the pixel just found; paint the region with the value of N++;
4) Iterate 3 until you reach the last pixel. (N-2) is the number of regions found.
This method depends on the shape of the objects; mine are more chaotic than yours (wish me luck..). I'll make use of a recursive flood-fill recipe found somewhere (maybe Rosetta Code).
This solution also makes it easy to compute the size of each region.
try to apply that on the your deleted img
// count
for (int i = 0; i< contours.size(); i = hierarchy[i][0]) // iteration sur chaque contour .
{
Rect r = boundingRect(contours[i]);
if (hierarchy[i][2]<0) {
rectangle(canny_output, Point(r.x, r.y), Point(r.x + r.width, r.y + r.height), Scalar(20, 50, 255), 3, 8, 0);
count++;
}
}
cout << "Numeber of contour = " << count << endl;
imshow("src", src);
imshow("contour", dst);
waitKey(0);
Hello everyone I have been having this issue with my opencv 3.1 program that I am programming in visual studio 2015 C++. It can use the camera just fine and display images just fine, but I try out a face detect example from the documentation my computer freezes up. Here is the code:
Here are the Two Functions where it gets hung up on: but mainly stops around the faceDetect function, I will do a break point to know specifically where.
void CoreVision::init()
{
face_cascade_name = "C:\\PAD\\opencv\\haarcascades\\haarcascade_frontalface_alt.xml";
eyes_cascade_name = "C:\\PAD\\opencv\\haarcascades\\haarcascade_eye_tree_eyeglasses.xml";
if (!face_cascade.load(face_cascade_name)) { printf("--(!)Error loading face cascade\n"); };
if (!eyes_cascade.load(eyes_cascade_name)) { printf("--(!)Error loading eyes cascade\n"); };
std::cout << "face_dir: " << face_cascade_name << std::endl;
std::cout << "eye_dir: " << eyes_cascade_name << std::endl;
}
cv::Mat CoreVision::detectFace(cv::Mat main)
{
cv::Mat nuller;
try
{
faces.clear();
cv::Mat frame_gray;
cv::cvtColor(main, frame_gray, cv::COLOR_BGR2GRAY);
cv::equalizeHist(frame_gray, frame_gray);
face_cascade.detectMultiScale(frame_gray, faces, 1.1, 2, 0 | cv::CASCADE_SCALE_IMAGE, cv::Size(30, 30));
for (size_t i = 0; i < faces.size(); i++)
{
cv::Point center(faces[i].x + faces[i].width / 2, faces[i].y + faces[i].height / 2);
cv::ellipse(main, center, cv::Size(faces[i].width / 2, faces[i].height / 2), 0, 0, 360, cv::Scalar(255, 0, 255), 4, 8, 0);
cv::Mat faceROI = frame_gray(faces[i]);
std::vector<cv::Rect> eyes;
eyes_cascade.detectMultiScale(faceROI, eyes, 1.1, 2, 0 | cv::CASCADE_SCALE_IMAGE, cv::Size(30, 30));
for (size_t j = 0; j < eyes.size(); j++)
{
cv::Point eye_center(faces[i].x + eyes[j].x + eyes[j].width / 2, faces[i].y + eyes[j].y + eyes[j].height / 2);
int radius = cvRound((eyes[j].width = eyes[j].height) * 0.25);
cv::circle(main, eye_center, radius, cv::Scalar(255, 0, 0), 4, 8, 0);
}
}
return main;
}
catch (...)
{
std::cout << "Exception: have issue with processing face detection.";
return nuller;
}
Here is the main function:
int main()
{
CoreVision _core;
_core.init();
while (true)
{
cv::Mat img = _core.captureImage(-1);
img = _core.detectFace(img);
_core.displayImage(img, "parker");
}
}
And finally the .h file for the two functions:
#include <iostream>
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <opencv2\opencv.hpp>
#include <opencv2\world.hpp>
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
class CoreVision
{
public:
CoreVision();
~CoreVision();
cv::Mat loadImage(const char* image_name, int type);
void saveImage(cv::Mat img, const char* filename);
cv::Mat captureImage(int cam);
cv::Mat detectFace(cv::Mat main);
int convertImage(cv::Mat img, int type);
void displayImage(cv::Mat, const char* window_name);
void init(void);
char cCurrentPath[FILENAME_MAX];
cv::String face_cascade_name;
cv::String eyes_cascade_name;
cv::CascadeClassifier face_cascade;
cv::CascadeClassifier eyes_cascade;
std::vector<cv::Rect> faces;
};
Thank you in advance for your help, I am not for sure if it is a driver issues, but I have tried it on multiple computers and the same freezing happens.
you don't seem to be storing the faces vector. You have it in public
std::vector faces; but where are you using it? eyes and faces are 2 different sets of data. Your also mixing two styles of code c style and c++ style opencv. You should stick with c++ since your using the latest opencv version.
faces.clear(); // under here
std::vector<Rect>faces; // see if this helps
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void saveImage(cv::Mat img, const char* filename); //should be
void imwrite(img, const char* filename);// etc.
cv::Mat img = _core.captureImage(-1);
img = _core.detectFace(img);
_core.displayImage(img, "parker"); // should be
_core.displayImage(Mat frame);
this proably isn't going to work asuming core.captureImage(-1);
is your camera. also what does int convertImage(cv::Mat img, int type); do? are you sure it takes an int value?
c++ convention is
Videocapture cap(0);
Mat frame:
cap >> frame;
namedWindow("video");
imshow(video, frame); //etc
I had exactly the same issue. I figured out that the line containing eyes_cascade.detectMultiScale was the one causing my driver to crash. I have the Intel HD graphics 4400.
The code started working perfectly after I completely uninstalled the Intel HD graphics drivers.
I am having a fairly annoying issue using OpenCV's HoughCircle method to detect circles in an image. I copied the code found in the official documentation and thus far I have been unable to detect anything. The circles vector has a size of 0 after calling the function, therefore there were no circles detected.
I have tried it with multiple images, such as .ppm images, .jpg and none of which end up with circles being detected. I really have no idea what could be going wrong.
If anyone has any idea of what I should try I'd be extremely thankful.
using namespace cv;
Mat src = imread("Images/balls.jpg");
if(! src.data )
{
std::cout << "Could not open or find the image" << std::endl ;
return -1;
}
Mat src_gray2;
cvtColor(src, src_gray2, CV_BGR2GRAY );
GaussianBlur( src_gray2, src_gray2, cv::Size(9, 9), 2, 2 );
vector<Vec3f> circles;
HoughCircles(src_gray2, circles, CV_HOUGH_GRADIENT, 1, src_gray2.rows/8, 200, 100, 0, 0 );
std::cout << circles.size();
This works for me. I adjusted the arguments to the HoughCircles function. See below. Also, I used this book to help me out: OpenCV 2
#include <cstdio>
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/features2d/features2d.hpp>
int main(int argc, char** argv) {
using namespace cv;
cv::Mat src=cv::imread("JGRiM.jpg");
if (!src.data) {
std::cout << "ERROR:\topening image" <<std::endl;
return -1;
}
cv::namedWindow("image",CV_WINDOW_AUTOSIZE);
cv::imshow("image",src);
Mat src_gray2;
cvtColor(src, src_gray2, CV_BGR2GRAY );
GaussianBlur( src_gray2, src_gray2, cv::Size(9, 9), 2, 2 );
vector<Vec3f> circles;
HoughCircles(src_gray2, circles, CV_HOUGH_GRADIENT,
2, // accumulator resolution (size of the image / 2)
5, // minimum distance between two circles
100, // Canny high threshold
100, // minimum number of votes
0, 1000); // min and max radius
std::cout << circles.size() <<std::endl;
std::cout << "end of test" << std::endl;
std::vector<cv::Vec3f>::
const_iterator itc= circles.begin();
while (itc!=circles.end()) {
cv::circle(src_gray2,
cv::Point((*itc)[0], (*itc)[1]), // circle centre
(*itc)[2], // circle radius
cv::Scalar(255), // color
2); // thickness
++itc;
}
cv::namedWindow("image",CV_WINDOW_AUTOSIZE);
cv::imshow("image",src_gray2);
cv::waitKey(0);
return 0;
}
You need to change param2 to a lower value to find more circles. For example in the image posted above in the comments to the question with param2 = 20 I found a circle around the tennis ball.
HoughCircles(src_gray2, circles, CV_HOUGH_GRADIENT, 1, src_gray2.rows/8, 200, 20, 0, 0 );