How can I get properly one resolution feed from camera in OpenCV (640x320) but cut it into half and display only one half of the frame (320x240). So not to scale down, but to actually crop. I am using OpenCV 2.4.5, VS2010 and C++
This quite standard code gets 640x480 input resolution and I made some changes to crop resolution to 320x240. Should I use Mat instead of IplImage, and if so what would be the best way?
#include "stdafx.h"
#include <iostream>
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace std;
char key;
int main()
{
cvNamedWindow("Camera_Output", 1); //Create window
CvCapture* capture = cvCaptureFromCAM(1); //Capture using camera 1 connected to system
cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_WIDTH, 640 );
cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_HEIGHT, 480 );
while(1){ //Create loop for live streaming
IplImage* framein = cvQueryFrame(capture); //Create image frames from capture
/* sets the Region of Interest - rectangle area has to be __INSIDE__ the image */
cvSetImageROI(framein, cvRect(0, 0, 320, 240));
/* create destination image - cvGetSize will return the width and the height of ROI */
IplImage *frameout = cvCreateImage(cvGetSize(framein), framein->depth, framein->nChannels);
/* copy subimage */
cvCopy(framein, frameout, NULL);
/* always reset the Region of Interest */
cvResetImageROI(framein);
cvShowImage("Camera_Output", frameout); //Show image frames on created window
key = cvWaitKey(10); //Capture Keyboard stroke
if (char(key) == 27){
break; //ESC key loop will break.
}
}
cvReleaseCapture(&capture); //Release capture.
cvDestroyWindow("Camera_Output"); //Destroy Window
return 0;
}
I think you don't check whether you are getting a CvCapture. On my system with only one camera your code doesn't work because you query camera 1. But the first camera should be 0 Thus change this code.
CvCapture* capture = cvCaptureFromCAM(1); //Capture using camera 1 connected to system
to (note I change 1 to 0):
CvCapture* capture = cvCaptureFromCAM(0); //Capture using camera 1 connected to system
if (! capture ){
/*your error handling*/
}
Further than that your code seems to be working for me. You might also check the other pointer values whether you are not getting NULL.
You can easily crop a video by calling the following function.
cvSetMouseCallback("image", mouseHandler, NULL);
The mouseHandler function is like that.
void mouseHandler(int event, int x, int y, int flags, void* param){
if (event == CV_EVENT_LBUTTONDOWN && !drag)
{
/* left button clicked. ROI selection begins */
select_flag=0;
point1 = Point(x, y);
drag = 1;
}
if (event == CV_EVENT_MOUSEMOVE && drag)
{
/* mouse dragged. ROI being selected */
Mat img1 = img.clone();
point2 = Point(x, y);
rectangle(img1, point1, point2, CV_RGB(255, 0, 0), 3, 8, 0);
imshow("image", img1);
}
if (event == CV_EVENT_LBUTTONUP && drag)
{
point2 = Point(x, y);
rect = Rect(point1.x,point1.y,x-point1.x,y-point1.y);
drag = 0;
roiImg = img(rect);
}
if (event == CV_EVENT_LBUTTONUP)
{
/* ROI selected */
select_flag = 1;
drag = 0;
}
}
For the details you can visit the following link.:How to Crop Video from Webcam using OpenCV
this is easy in python... but the key idea is that cv2 arrays can be referenced and sliced. all you need is a slice of framein.
the following code takes a slice from (0,0) to (320,240). note that numpy arrays are indexed with column priority.
# Required modules
import cv2
# Constants for the crop size
xMin = 0
yMin = 0
xMax = 320
yMax = 240
# Open cam, decode image, show in window
cap = cv2.VideoCapture(0) # use 1 or 2 or ... for other camera
cv2.namedWindow("Original")
cv2.namedWindow("Cropped")
key = -1
while(key < 0):
success, img = cap.read()
cropImg = img[yMin:yMax,xMin:xMax] # this is all there is to cropping
cv2.imshow("Original", img)
cv2.imshow("Cropped", cropImg)
key = cv2.waitKey(1)
cv2.destroyAllWindows()
Working Example of cropping Faces from live camera
void CropFaces::DetectAndCropFaces(Mat frame, string locationToSaveFaces) {
std::vector<Rect> faces;
Mat frame_gray;
// Convert to gray scale
cvtColor(frame, frame_gray, COLOR_BGR2GRAY);
// Equalize histogram
equalizeHist(frame_gray, frame_gray);
// Detect faces
face_cascade.detectMultiScale(frame_gray, faces, 1.1, 3,
0 | CASCADE_SCALE_IMAGE, Size(30, 30));
// Iterate over all of the faces
for (size_t i = 0; i < faces.size(); i++) {
// Find center of faces
Point center(faces[i].x + faces[i].width / 2, faces[i].y + faces[i].height / 2);
Mat face = frame_gray(faces[i]);
std::vector<Rect> eyes;
Mat croppedRef(frame, faces[i]);
cv::Mat cropped;
// Copy the data into new matrix
croppedRef.copyTo(cropped);
string fileName = locationToSaveFaces+ "\\face_" + to_string(faces[i].x) + ".jpg";
resize(cropped, cropped, Size(65, 65));
imwrite(fileName, cropped);
}
// Display frame
imshow("DetectAndSave", frame);
}
void CropFaces::PlayVideoForCropFaces(string locationToSaveFaces) {
VideoCapture cap(0); // Open default camera
Mat frame;
face_cascade.load("haarcascade_frontalface_alt.xml"); // load faces
while (cap.read(frame)) {
DetectAndCropFaces(frame, locationToSaveFaces); // Call function to detect faces
if (waitKey(30) >= 0) // pause
break;
}
}
Related
I am detecting shapes in real time with the help of OpenCv in C++ programming language. I found a code that reads from the folder and detect shapes. But in My case camera should detect in real time. How can I use raspicam::RaspiCam_Cv capture; instead of CvCapture *capture = cvCaptureFromAVI("a.avi"); in C++.
#include <cv.h>
#include <highgui.h>
using namespace std;
IplImage* imgTracking=0;
int lastX1 = -1;
int lastY1 = -1;
int lastX2 = -1;
int lastY2 = -1;
void trackObject(IplImage* imgThresh){
CvSeq* contour; //hold the pointer to a contour
CvSeq* result; //hold sequence of points of a contour
CvMemStorage *storage = cvCreateMemStorage(0); //storage area for all contours
//finding all contours in the image
cvFindContours(imgThresh, storage, &contour, sizeof(CvContour), CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0));
//iterating through each contour
while(contour)
{
//obtain a sequence of points of the countour, pointed by the variable 'countour'
result = cvApproxPoly(contour, sizeof(CvContour), storage, CV_POLY_APPROX_DP, cvContourPerimeter(contour)*0.02, 0);
//if there are 3 vertices in the contour and the area of the triangle is more than 100 pixels
if(result->total==3 && fabs(cvContourArea(result, CV_WHOLE_SEQ))>100 )
{
//iterating through each point
CvPoint *pt[3];
for(int i=0;i<3;i++){
pt[i] = (CvPoint*)cvGetSeqElem(result, i);
}
int posX=( pt[0]->x + pt[1]->x + pt[2]->x )/3;
int posY=( pt[0]->y + pt[1]->y + pt[2]->y )/3;
if(posX > 360 ){
if(lastX1>=0 && lastY1>=0 && posX>=0 && posY>=0){
// Draw a red line from the previous point to the current point
cvLine(imgTracking, cvPoint(posX, posY), cvPoint(lastX1, lastY1), cvScalar(0,0,255), 4);
}
lastX1 = posX;
lastY1 = posY;
}
else{
if(lastX2>=0 && lastY2>=0 && posX>=0 && posY>=0){
// Draw a blue line from the previous point to the current point
cvLine(imgTracking, cvPoint(posX, posY), cvPoint(lastX2, lastY2), cvScalar(255,0,0), 4);
}
lastX2 = posX;
lastY2 = posY;
}
}
//obtain the next contour
contour = contour->h_next;
}
cvReleaseMemStorage(&storage);
}
int main(){
//load the video file to the memory
CvCapture *capture = cvCaptureFromAVI("a.avi");
if(!capture){
printf("Capture failure\n");
return -1;
}
IplImage* frame=0;
frame = cvQueryFrame(capture);
if(!frame) return -1;
//create a blank image and assigned to 'imgTracking' which has the same size of original video
imgTracking=cvCreateImage(cvGetSize(frame),IPL_DEPTH_8U, 3);
cvZero(imgTracking); //covert the image, 'imgTracking' to black
cvNamedWindow("Video");
//iterate through each frames of the video
while(true){
frame = cvQueryFrame(capture);
if(!frame) break;
frame=cvCloneImage(frame);
//smooth the original image using Gaussian kernel
cvSmooth(frame, frame, CV_GAUSSIAN,3,3);
//converting the original image into grayscale
IplImage* imgGrayScale = cvCreateImage(cvGetSize(frame), 8, 1);
cvCvtColor(frame,imgGrayScale,CV_BGR2GRAY);
//thresholding the grayscale image to get better results
cvThreshold(imgGrayScale,imgGrayScale,100,255,CV_THRESH_BINARY_INV);
//track the possition of the ball
trackObject(imgGrayScale);
// Add the tracking image and the frame
cvAdd(frame, imgTracking, frame);
cvShowImage("Video", frame);
//Clean up used images
cvReleaseImage(&imgGrayScale);
cvReleaseImage(&frame);
//Wait 10mS
int c = cvWaitKey(10);
//If 'ESC' is pressed, break the loop
if((char)c==27 ) break;
}
cvDestroyAllWindows();
cvReleaseImage(&imgTracking);
cvReleaseCapture(&capture);
return 0;
}
I cannot use raspicam::RaspiCam_Cv capture; keyword instead of CvCapture *capture = cvCaptureFromAVI(); I should detect shapes in real time for example when triangle comes then call some function. Please help me
I have a problem with the code for the simpleBlobDetector. I can build and run all the code just fine, but the blobs that the program detects are only the size of a pixel or so. I've already tried to change the param.minArea and maxArea but it doesn't work. So Im asking you guys for help. By the way the image i was using is in grayscale already so it isn't because of my threshold command that it isn't working. Thanks before hand!
Martin.
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main(){
Mat src;
Mat dst;
src = imread("C:\\Users\\martin\\Desktop\\ThermalImage2.png", CV_LOAD_IMAGE_GRAYSCALE); //Load an image from directory path
if (! src.data){
cout << "Could not open or find the image" << endl ; // Look for invalid input
return -1;
}
else{
double thresh = 130; // Threshold
double maxValue = 255; // Value assigned to the pixel if it is over 'thresh'
threshold(src, dst, thresh, maxValue, THRESH_BINARY); // threshold the picture src and call it dst
namedWindow("thresholdedPicture", WINDOW_AUTOSIZE); // Create a window
imshow("thresholdedPicture", dst); // display thresholded picture in the window
}
SimpleBlobDetector::Params params; // Set parameters for the object detection
params.minDistBetweenBlobs = 10; //Minimum distance between blobs
params.filterByColor = true;
params.blobColor = 255;
params.filterByArea = true; // filter by area of the blob
params.minArea = 1 ;// Minimum area of the blob
params.maxArea = 100000; // Maximum area of the blob
vector<KeyPoint> keypoints;
cv::SimpleBlobDetector detector(params); // Set up the blob detector with the parameters (params)
detector.detect(dst, keypoints); // Input thresholded picture for detection of the blobs
Mat dst_blob_dect; // New array to store the picture with the blobs detected
drawKeypoints( dst, keypoints, dst_blob_dect, Scalar(0,0,255), DrawMatchesFlags::DRAW_RICH_KEYPOINTS ); //Drawing a red line around the detected objects
namedWindow("keypoints", WINDOW_AUTOSIZE); // Create a window
imshow("keypoints", dst_blob_dect); // Show the picture with the blobs detected in the window "keypoints"
waitKey(0); // Press any key and the main function returns 0
return 0;}
Try this and use different values for params.minDistBetweenBlobs.
#include "stdafx.h"
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <opencv2/opencv.hpp>
#include <stdio.h>
using namespace std;
using namespace cv;
int main(){
Mat src;
Mat dst;
src = imread("C:\\Users\\sanche8x\\Pictures\\gather.png", CV_LOAD_IMAGE_GRAYSCALE); //Load an image from directory path
if (! src.data){
cout << "Could not open or find the image" << endl ; // Look for invalid input
return -1;
}
else{
double thresh = 130; // Threshold
double maxValue = 255; // Value assigned to the pixel if it is over 'thresh'
threshold(src, dst, thresh, maxValue, THRESH_BINARY); // threshold the picture src and call it dst
namedWindow("thresholdedPicture", WINDOW_AUTOSIZE); // Create a window
imshow("thresholdedPicture", dst); // display thresholded picture in the window
}
SimpleBlobDetector::Params params; // Set parameters for the object detection
params.minDistBetweenBlobs = 10; //Minimum distance between blobs
params.filterByColor = true;
params.blobColor = 255;
params.filterByCircularity = false;
params.filterByConvexity = false;
params.filterByInertia = false;
params.filterByArea = true; // filter by area of the blob
params.minArea = 1 ;// Minimum area of the blob
params.maxArea = 100000; // Maximum area of the blob
vector<KeyPoint> keypoints;
cv::SimpleBlobDetector detector(params); // Set up the blob detector with the parameters (params)
detector.detect(dst, keypoints); // Input thresholded picture for detection of the blobs
Mat dst_blob_dect; // New array to store the picture with the blobs detected
drawKeypoints( dst, keypoints, dst_blob_dect, Scalar(0,0,255), DrawMatchesFlags::DRAW_RICH_KEYPOINTS ); //Drawing a red line around the detected objects
namedWindow("keypoints", WINDOW_AUTOSIZE); // Create a window
imshow("keypoints", dst_blob_dect); // Show the picture with the blobs detected in the window "keypoints"
waitKey(0); // Press any key and the main function returns 0
return 0;
}
I'm using OpenCV 3 on Ubuntu. the following code is used to detect a face in an image and save the cropped part. The output isn't being shown but the cropped image is saved in my folder.
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
using namespace std;
using namespace cv;
// Function Headers
void detectAndDisplay(Mat frame);
// Global variables
// Copy this file from opencv/data/haarscascades to target folder
string face_cascade_name = "/home/sruthi/opencv/data/haarcascades/haarcascade_frontalface_alt.xml";
CascadeClassifier face_cascade;
string window_name = "Capture - Face detection";
int filenumber; // Number of file to be saved
string filename;
// Function main
int main(void)
{
// Load the cascade
if (!face_cascade.load(face_cascade_name)){
printf("--(!)Error loading\n");
return (-1);
}
// Read the image file
Mat frame = imread("/home/sruthi/Downloads/pic.jpg");
// Apply the classifier to the frame
if (!frame.empty()){
detectAndDisplay(frame);
}
else{
printf(" --(!) No captured frame -- Break!");
//break;
}
int c = waitKey(10);
if (27 == char(c)){
//break;
}
return 0;
}
// Function detectAndDisplay
void detectAndDisplay(Mat frame)
{
std::vector<Rect> faces;
Mat frame_gray;
Mat crop;
Mat res;
Mat gray;
string text;
stringstream sstm;
cvtColor(frame, frame_gray, COLOR_BGR2GRAY);
equalizeHist(frame_gray, frame_gray);
// Detect faces
face_cascade.detectMultiScale(frame_gray, faces, 1.1, 2, 0 | CASCADE_SCALE_IMAGE, Size(30, 30));
// Set Region of Interest
cv::Rect roi_b;
cv::Rect roi_c;
size_t ic = 0; // ic is index of current element
int ac = 0; // ac is area of current element
size_t ib = 0; // ib is index of biggest element
int ab = 0; // ab is area of biggest element
for (ic = 0; ic < faces.size(); ic++) // Iterate through all current elements (detected faces)
{
roi_c.x = faces[ic].x;
roi_c.y = faces[ic].y;
roi_c.width = (faces[ic].width);
roi_c.height = (faces[ic].height);
ac = roi_c.width * roi_c.height; // Get the area of current element (detected face)
roi_b.x = faces[ib].x;
roi_b.y = faces[ib].y;
roi_b.width = (faces[ib].width);
roi_b.height = (faces[ib].height);
ab = roi_b.width * roi_b.height; // Get the area of biggest element, at beginning it is same as "current" element
if (ac > ab)
{
ib = ic;
roi_b.x = faces[ib].x;
roi_b.y = faces[ib].y;
roi_b.width = (faces[ib].width);
roi_b.height = (faces[ib].height);
}
crop = frame(roi_b);
resize(crop, res, Size(128, 128), 0, 0, INTER_LINEAR); // This will be needed later while saving images
cvtColor(crop, gray, CV_BGR2GRAY); // Convert cropped image to Grayscale
// Form a filename
filename = "";
stringstream ssfn;
ssfn << filenumber << ".jpg";
filename = ssfn.str();
filenumber++;
imwrite(filename, gray);
Point pt1(faces[ic].x, faces[ic].y); // Display detected faces on main window
Point pt2((faces[ic].x + faces[ic].height), (faces[ic].y + faces[ic].width));
rectangle(frame, pt1, pt2, Scalar(0, 255, 0), 2, 8, 0);
}
// Show image
sstm << "Crop area size: " << roi_b.width << "x" << roi_b.height << " Filename: " << filename;
text = sstm.str();
putText(frame, text, cvPoint(30, 30), FONT_HERSHEY_COMPLEX_SMALL, 0.8, cvScalar(0, 0, 255), 1, CV_AA);
imshow("original", frame);
if (!crop.empty())
{
imshow("detected", crop);
}
else
destroyWindow("detected");
}
But at the end of the execution I'm getting:
sruthi#sruthi-5547:~/c++$ ./crop
pure virtual method called
terminate called without an active exception
Aborted (core dumped)
I think there are two issues here.
First, your code works fine, but you should add cv::waitKey(); after imshow to prevent the window from closing (it will close after pressing a key).
Second, there is a bug in OpenCV 3.0.0 that causes the pure virtual method called error. If your program runs ok, I'd bet the error message is because of the bug. If you get the latest (and unreleased) OpenCV version from its github repository, it will be fixed.
In python you can do this:
import cv2
import sys
cascPath = sys.argv[1]
faceCascade = cv2.CascadeClassifier(cascPath)
video_capture = cv2.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.cv.CV_HAAR_SCALE_IMAGE
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
if cv2.waitKey(1) & 0xFF == ord('c'):
crop = frame[y: y + h, x: x + w]
cv2.imwrite("face.jpg", crop)
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
I am looking into the Hough Circle function. There are basically 4 parameters that i can play with to get the correct circle I wish.
So it come to my mind that I want to create a trackbar to monitor the status of the image being processed.
So I altered my code like this
#include <sstream>
#include <string>
#include <iostream>
#include <vector>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <opencv\cv.h>
#include <opencv\highgui.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
using namespace cv;
int main(int argc, char** argv) {
//Create a window for trackbars
namedWindow("Trackbar Window", CV_WINDOW_AUTOSIZE);
//Create trackbar to change brightness
int iSliderValue1 = 50;
createTrackbar("Brightness", "Trackbar Window", &iSliderValue1, 100);
//Create trackbar to change contrast
int iSliderValue2 = 50;
createTrackbar("Contrast", "Trackbar Window", &iSliderValue2, 100);
int param1 = 10;
createTrackbar("param1", "Trackbar Window", ¶m1, 300);
int param2 = 10;
createTrackbar("param2", "Trackbar Window", ¶m2, 300);
Mat src;
VideoCapture capture;
capture.open("movingBall.wmv");
capture.read(src);
capture.set(CV_CAP_PROP_FRAME_HEIGHT, 480);
capture.set(CV_CAP_PROP_FRAME_WIDTH, 640);
if (!src.data) {
std::cout << "ERROR:\topening image" << std::endl;
return -1;
}
cv::namedWindow("image1", CV_WINDOW_AUTOSIZE);
cv::namedWindow("image2", CV_WINDOW_AUTOSIZE);
while (true){
capture.read(src);
Mat dst;
int iBrightness = iSliderValue1 - 50;
double dContrast = iSliderValue2 / 50.0;
src.convertTo(src, -1, dContrast, iBrightness);
cv::imshow("image1", 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
param1, // Canny high threshold
param2, // minimum number of votes
0, 0); // min and max radius
std::cout << circles.size() << std::endl;
std::cout << "end of test" << std::endl;
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(src, center, 3, Scalar(0, 255, 0), -1, 8, 0);
// circle outline
circle(src, center, radius, Scalar(0, 0, 255), 3, 8, 0);
}
/*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(0,0,0), // color
2); // thickness
++itc;
}*/
cv::imshow("image2", src_gray2);
cvWaitKey(33);
}
return 0;
}
As seen at the Hough Circle function there, i used int param1; as the value i wish to change. However, the code has no syntax errors but it is unable to be compiled.
I wish to know if is there something wrong with my trackbar setup..
Thank you
Here i have tried it using Python you can try to port from it...
import cv2
import numpy as np
img = cv2.imread('C:/Python34/images/2.jpg',0)
cv2.namedWindow('image')
def nothing(x):
pass
cv2.createTrackbar('Param 1','image',0,100,nothing)
cv2.createTrackbar('Param 2','image',0,100,nothing)
switch = '0 : OFF \n1 : ON'
cv2.createTrackbar(switch, 'image',0,1,nothing)
while(1):
cv2.imshow('image',img)
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
#To Get Parameter values from Trackbar Values
para1 = cv2.getTrackbarPos('Param 1','image')
para2 = cv2.getTrackbarPos('Param 2','image')
s = cv2.getTrackbarPos(switch,'image')
if s == 0:
cv2.imshow('image', img)
else:
#For finding Hough Circles according to trackbar parameters
circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,20,para1,para2,minRadius=0,maxRadius=0)
circles = np.uint16(np.around(circles))
#For drawing Hough Circles
for i in circles[0,:]:
cv2.circle(img,(i[0],i[1]),i[2],(0,255,0),2)
cv2.circle(img,(i[0],i[1]),2,(0,0,255),3)
cv2.imshow('image', img)
cv2.waitKey(0)
img = cv2.imread('C:/Python34/images/2.jpg',0)
cv2.destroyAllWindows()
You can use the above code as your refrence, firstly it creates a window and trackbars for switch and two parameter for hough circle.
then in the while loop para1 and para2 will store position of trackbars as value of canny parameter.
this is then used in cv2.HoughCircles function and the circles are drawn.
the image is again loaded so that every time you change parameter the output is given on fresh image to avoid confusing.
hope this might be useful.
One whole day I have tried a lot to get all the related matches (with matchtemplate function) in sub-Image , which is ROI i have already extracted from the original image with the mousecallback function. So my code is below for the Matchingfunction
////Matching Function
void CTemplate_MatchDlg::OnBnTemplatematch()
{
namedWindow("reference",CV_WINDOW_AUTOSIZE);
while(true)
{
Mat ref = imread("img.jpg"); // Original Image
mod_ref = cvCreateMat(ref.rows,ref.cols,CV_32F);// resizing the image to fit in picture box
resize(ref,mod_ref,Size(),0.5,0.5,CV_INTER_AREA);
Mat tpl =imread("Template.jpg"); // TEMPLATE IMAGE
cvSetMouseCallback("reference",find_mouseHandler,0);
Mat aim=roiImg1.clone(); // SUB_IMAGE FROM ORIGINALIMAGE
// aim variable contains the ROI matrix
// next, want to perform template matching in that ROI // and display results on original image
if(select_flag1 == 1)
{
// imshow("ref",aim);
Mat res(aim.rows-tpl.rows+1, aim.cols-tpl.cols+1,CV_32FC1);
matchTemplate(aim, tpl, res, CV_TM_CCOEFF_NORMED);
threshold(res, res, 0.8, 1., CV_THRESH_TOZERO);
while (1)
{
double minval, maxval, threshold = 0.8;
Point minloc, maxloc;
minMaxLoc(res, &minval, &maxval, &minloc, &maxloc);
//// Draw Bound boxes for detected templates in sub matrix
if (maxval >= threshold)
{
rectangle(
aim,
maxloc,
Point(maxloc.x + tpl.cols, maxloc.y + tpl.rows),
CV_RGB(0,255,0), 1,8,0
);
floodFill(res, maxloc, cv::Scalar(0), 0, cv::Scalar(.1), cv::Scalar(1.));
}else
break;
}
}
////Bounding box for ROI selection with mouse
rectangle(mod_ref, rect2, CV_RGB(255, 0, 0), 1, 8, 0); // rect2 is ROI
// my idea is to get all the matches in ROI with bounding boxes
// no need to mark any matches outside the ROI
//Clearly i want to process only ROI
imshow("reference", mod_ref); // show the image with the results
waitKey(10);
}
//cvReleaseMat(&mod_ref);
destroyWindow("reference");
}
/// ImplementMouse Call Back
void find_mouseHandler(int event, int x, int y, int flags, void* param)
{
if (event == CV_EVENT_LBUTTONDOWN && !drag)
{
/* left button clicked. ROI selection begins*/
point1 = Point(x, y);
drag = 1;
}
if (event == CV_EVENT_MOUSEMOVE && drag)
{
/* mouse dragged. ROI being selected*/
Mat img3 = mod_ref.clone();
point2 = Point(x, y);
rectangle(img3, point1, point2, CV_RGB(255, 0, 0), 1, 8, 0);
imshow("reference", img3);
//
}
if (event == CV_EVENT_LBUTTONUP && drag)
{
Mat img4=mod_ref.clone();
point2 = Point(x, y);
rect1 = Rect(point1.x,point1.y,x-point1.x,y-point1.y);
drag = 0;
roiImg1 = mod_ref(rect1); //SUB_IMAGE MATRIX
imshow("reference", img4);
}
if (event == CV_EVENT_LBUTTONUP)
{
/* ROI selected */
select_flag1 = 1;
drag = 0;
}
}
build and debugging process successfully done. But, when I click the Match button in dialog I'm getting the error:
Unhandled exception at 0x74bf812f in Match.exe: Microsoft C++ exception: cv::Exception at memory location 0x001ae150..
So my idea is to get all the matches in the Sub-image when compare with the TEMPLATE IMAGE and show the final result (matches with bounding boxes) in the ORIGINAL IMAGE itself.
Anyone help me in this regard!! Help would be appreciated greatly!!
My code below is a modification of the original tutorial provided by OpenCV.
It loads an image from the command-line and displays it on the screen so the user can draw a rectangle somewhere to select the sub-image to be the template. After that operation is done, the sub-image will be inside a green rectangle:
Press any key to let the program perform the template matching. A new window titled "Template Match:" appears displaying the original image plus a blue rectangle that shows the matched area:
#include <cv.h>
#include <highgui.h>
#include <iostream>
const char* ref_window = "Draw rectangle to select template";
std::vector<cv::Point> rect_points;
void mouse_callback(int event, int x, int y, int flags, void* param)
{
if (!param)
return;
cv::Mat* ref_img = (cv::Mat*) param;
// Upon LMB click, store the X,Y coordinates to define a rectangle.
// Later this info is used to set a ROI in the reference image.
switch (event)
{
case CV_EVENT_LBUTTONDOWN:
{
if (rect_points.size() == 0)
rect_points.push_back(cv::Point(x, y));
}
break;
case CV_EVENT_LBUTTONUP:
{
if (rect_points.size() == 1)
rect_points.push_back(cv::Point(x, y));
}
break;
default:
break;
}
if (rect_points.size() == 2)
{
cv::rectangle(*ref_img,
rect_points[0],
rect_points[1],
cv::Scalar(0, 255, 0),
2);
cv::imshow(ref_window, *ref_img);
}
}
int main(int argc, char* argv[])
{
if (argc < 2)
{
std::cout << "Usage: " << argv[0] << " <image>" << std::endl;
return -1;
}
cv::Mat source = cv::imread(argv[1]); // original image
if (source.empty())
{
std::cout << "!!! Failed to load source image." << std::endl;
return -1;
}
// For testing purposes, our template image will be a copy of the original.
// Later we will present it in a window to the user, and he will select a region
// as a template, and then we'll try to match that to the original image.
cv::Mat reference = source.clone();
cv::namedWindow(ref_window, CV_WINDOW_AUTOSIZE);
cv::setMouseCallback(ref_window, mouse_callback, (void*)&reference);
cv::imshow(ref_window, reference);
cv::waitKey(0);
if (rect_points.size() != 2)
{
std::cout << "!!! Oops! You forgot to draw a rectangle." << std::endl;
return -1;
}
// Create a cv::Rect with the dimensions of the selected area in the image
cv::Rect template_roi = cv::boundingRect(rect_points);
// Create THE TEMPLATE image using the ROI from the rectangle
cv::Mat template_img = cv::Mat(source, template_roi);
// Create the result matrix
int result_cols = source.cols - template_img.cols + 1;
int result_rows = source.rows - template_img.rows + 1;
cv::Mat result;
// Do the matching and normalize
cv::matchTemplate(source, template_img, result, CV_TM_CCORR_NORMED);
cv::normalize(result, result, 0, 1, cv::NORM_MINMAX, -1, cv::Mat());
/// Localizing the best match with minMaxLoc
double min_val = 0, max_val = 0;
cv::Point min_loc, max_loc, match_loc;
int match_method = CV_TM_CCORR_NORMED;
cv::minMaxLoc(result, &min_val, &max_val, &min_loc, &max_loc, cv::Mat());
// When using CV_TM_CCORR_NORMED, max_loc holds the point with maximum
// correlation.
match_loc = max_loc;
// Draw a rectangle in the area that was matched
cv:rectangle(source,
match_loc,
cv::Point(match_loc.x + template_img.cols , match_loc.y + template_img.rows),
cv::Scalar(255, 0, 0), 2, 8, 0 );
imshow("Template Match:", source);
cv::waitKey(0);
return 0;
}