Você está na página 1de 2

// pendeteksi dan penghitung objek

#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/videoio/videoio.hpp>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

using namespace cv;


using namespace std;

// ==========================================Variabel Merah========================
//
Mat src; Mat src_hsv;
int thresh = 100;
int max_thresh = 255;
int h_min = 0, h_max = 220, s_min =37, s_max = 248, v_min = 37, v_max = 255,
conture = 100;
int s = 0;
char str[200];

// ==========================================Hijau======================== //
/*
int h_min2 = 30, h_max2 = 79, s_min2 = 42, s_max2 = 255, v_min2 = 44, v_max2 = 255,
conture2 = 100; */

int main(int argc, char **argv)


{
/* VideoCapture cap;
cap.open(0);
cap.set(CV_CAP_PROP_FRAME_WIDTH, 320);//420);
cap.set(CV_CAP_PROP_FRAME_HEIGHT, 240);//340); */

while (1)
{
src = imread("apelmerah.jpg", CV_LOAD_IMAGE_GRAYSCALE);
// src = imread("apelhijau.jpg", 1);
namedWindow("Trackbar", CV_WINDOW_NORMAL);
createTrackbar("R1_MIN: ", "Trackbar", &h_min, 255);
createTrackbar("R1_MAX: ", "Trackbar", &h_max, 255);
createTrackbar("R2_MIN: ", "Trackbar", &s_min, 255);
createTrackbar("R2_MAX: ", "Trackbar", &s_max, 255);
createTrackbar("R3_MIN: ", "Trackbar", &v_min, 255);
createTrackbar("R3_MAX: ", "Trackbar", &v_max, 255);
createTrackbar("Conture: ", "Trackbar", &conture, 255);
createTrackbar(" Threshold:", "Trackbar", &thresh, max_thresh);

//cap.read(src);
Mat threshold_output, df;

Ptr<CLAHE> clahe = createCLAHE();


clahe->setClipLimit(4);
clahe->apply(src, src_hsv);
imshow("CLAHE", src_hsv);

cvtColor(src, src_hsv, CV_BGR2GRAY);


//threshold( src, src_hsv, thresh, 255, THRESH_BINARY +
THRESH_OTSU);
inRange(src_hsv, Scalar(h_min, s_min, v_min), Scalar(h_max,
s_max, v_max), threshold_output);
erode(threshold_output, df, getStructuringElement(MORPH_ELLIPSE,
Size(8, 8)));

vector<vector<Point> > contours;


vector<Vec4i> hierarchy;

findContours(df, contours, hierarchy, CV_RETR_TREE,


CV_CHAIN_APPROX_SIMPLE, Point(0, 0));

vector<vector<Point> >hull(contours.size());

for (int i = 0; i < contours.size(); i++)


{
convexHull(Mat(contours[i]), hull[i], false);
}

cout << s << " trtrr" << contours.size() << endl;


for (int i = 0; i< contours.size(); i++)
{
if (contourArea(contours[i]) > conture * 40)
{
drawContours(src, hull, i, Scalar(0, 0, 0), 3, 8,
vector<Vec4i>(), 0, Point());
s++;
}
}
sprintf(str, "Jumlah apelk = %d", s);
putText(src, str, Point(30, 140), FONT_HERSHEY_SIMPLEX, 0.4,
Scalar::all(255), 2, 8);
s = 0;

imshow("asli", src);
imshow("gray", src_hsv);
imshow("filter gray", threshold_output);
imshow("filter gray2", df);
// moveWindow("asli", 10, 400);

if (waitKey(30) == 27)break;
}
return 0;
}

Você também pode gostar