I am new to OpenCV. Currently, trying to load and save a defined ROI of an image.
For OpenCV 1.x, I got it working with the following function...
#include <cv.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
void SaveROI(const CStringA& inputFile, const CStringA& outputFile)
{
if (ATLPath::FileExists(inputFile))
{
CvRect rect;
rect.x = 8;
rect.y = 90;
rect.width = 26;
rect.height = 46;
IplImage* imgInput = cvLoadImage(inputFile.GetString(), 1);
IplImage* imgRoi = cvCloneImage(imgInput);
cvSetImageROI(imgRoi, rect);
cvSaveImage(outputFile.GetString(), imgRoi);
cvReleaseImage(&imgInput);
cvReleaseImage(&imgRoi);
}
}
How can this be done with the OpenCV 2 or C++. I tried the following without a success, the whole image is saved.
void SaveROICPP(const CStringA& inputFile, const CStringA& outputFile)
{
if (ATLPath::FileExists(inputFile))
{
cv::Mat imgInput = cv::imread(inputFile.GetString());
if (imgInput.data != NULL)
{
cv::Mat imgRoi = imgInput(cv::Rect(8, 90, 26, 46));
imgInput.copyTo(imgRoi);
cv::imwrite(outputFile.GetString(), imgRoi);
}
}
}
Any help or suggestion?
You just don't need to call copyTo:
void SaveROICPP(const CStringA& inputFile, const CStringA& outputFile)
{
if (ATLPath::FileExists(inputFile))
{
cv::Mat imgInput = cv::imread(inputFile.GetString());
if (imgInput.data != NULL)
{
cv::Mat imgRoi = imgInput(cv::Rect(8, 90, 26, 46));
cv::imwrite(outputFile.GetString(), imgRoi);
}
}
}
In your version copyTo sees that imgInput is bigger then imgRoi and reallocates a new full-size matrix to make the copy. imgRoi is already a sub-image and you can simply pass it to any OpenCV function.
Here is some tested code for blending, cropping and saving new images.
You crop and then save that region in a new file.
#include <cv.h>
#include <highgui.h>
#include <math.h>
// alphablend <imageA> <image B> <x> <y> <width> <height>
// <alpha> <beta>
IplImage* crop( IplImage* src, CvRect roi){
// Must have dimensions of output image
IplImage* cropped = cvCreateImage( cvSize(roi.width,roi.height), src->depth, src->nChannels );
// Say what the source region is
cvSetImageROI( src, roi );
// Do the copy
cvCopy( src, cropped );
cvResetImageROI( src );
cvNamedWindow( "check", 1 );
cvShowImage( "check", cropped );
cvSaveImage ("style.jpg" , cropped);
return cropped;
}
int main(int argc, char** argv){
IplImage *src1, *src2;
CvRect myRect;
// IplImage* cropped ;
src1=cvLoadImage(argv[1],1);
src2=cvLoadImage(argv[2],1);
{
int x = atoi(argv[3]);
int y = atoi(argv[4]);
int width = atoi(argv[5]);
int height = atoi(argv[6]);
double alpha = (double)atof(argv[7]);
double beta = (double)atof(argv[8]);
cvSetImageROI(src1, cvRect(x,y,width,height));
cvSetImageROI(src2, cvRect(100,200,width,height));
myRect = cvRect(x,y,width,height) ;
cvAddWeighted(src1, alpha, src2, beta,0.0,src1);
cvResetImageROI(src1);
crop (src1 , myRect);
cvNamedWindow( "Alpha_blend", 1 );
cvShowImage( "Alpha_blend", src1 );
cvWaitKey(0);
}
return 0;
}
Related
Why is webcam image processing is very slow while using Xcode for this OpenCV project, and only one out of three windows are working (similar spaces and HSV windows are not turning up) and are very slow? How to increase the speed of execution of the program?
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
using namespace cv;
using namespace std;
Mat img, hsv, res;
char *win1 = "RGB";
char *win2 = "HSV";
char *win3 = "similar spaces";
uchar thresh = 5;
void setColor(uchar hval){
int i,j;
for (i = 0; i < res.rows; ++i){
for (j = 0; j < res.cols; ++j){
if( hsv.at<Vec3b>(i,j)[0] <= hval+thresh
&& hsv.at<Vec3b>(i,j)[0] >= hval-thresh)
res.at<uchar>(i,j) = 255;
else res.at<uchar>(i,j) = 0;
}
}
imshow(win3, res);
}
void MouseCallBackFunc(int event, int x, int y, int flags, void* userdata){
if(event==EVENT_LBUTTONDOWN){
cout<<"\t x,y : "<<x<<','<<y<<endl;
cout<<'\t'<<img.at<Vec3b>(y,x)<<endl;
setColor(hsv.at<Vec3b>(y,x)[0]);
}
}
int main()
{
img = imread("/usr/share/opencv/samples/cpp/stuff.jpg", CV_LOAD_IMAGE_COLOR);
hsv = Mat::zeros(img.size(), CV_8UC3);
res = Mat::zeros(img.size(), CV_8UC1);
char c;
int i,j;
namedWindow(win2, CV_WINDOW_NORMAL);
namedWindow(win3, CV_WINDOW_NORMAL);
cvtColor(img, hsv, CV_RGB2HSV);
imshow(win1, img);
imshow(win2, hsv);
imshow(win3, res);
setMouseCallback(win1, MouseCallBackFunc, NULL);
// VideoCapture stream(0); //0 is the id of video device.0 if you have only one camera.
// if (!stream.isOpened()) { //check if video device has been initialised
// cout << "cannot open camera";
// }
// while (true) {
// Mat cameraFrame;
// stream.read(cameraFrame);
// imshow("test", cameraFrame);
// c = waitKey(30);
// if(c==27)
// break;
// }
while((c=waitKey(300))!=27){}
return 0;
}
I want to find subpixel and I resarched this topic However I think that subpixels must be such as 152.6 , 49.3 ...
I find this document in opencv http://docs.opencv.org/2.4/modules/imgproc/doc/feature_detection.html?highlight=cornersubpix#cornersubpix
And I try this code
#include <iostream>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace cv;
using namespace std;
Mat src, src_gray;
int maxCorners = 10;
int maxTrackbar = 50;
RNG rng(11111);
char* source_window = "Image";
void goodFeaturesToTrack_Demo( int, void* );
int main( int argc, char** argv )
{
src = imread( "a.png", 1 );
cvtColor( src, src_gray, CV_BGR2GRAY );
namedWindow( source_window, CV_WINDOW_AUTOSIZE );
createTrackbar( "Max corners:", source_window, &maxCorners, maxTrackbar, goodFeaturesToTrack_Demo);
imshow( source_window, src );
goodFeaturesToTrack_Demo( 0, 0 );
waitKey(0);
return(0);
}
void goodFeaturesToTrack_Demo( int, void* )
{
if( maxCorners < 1 )
{ maxCorners = 1; }
vector<Point2f> corners;
double qualityLevel = 0.01;
double minDistance = 10;
int blockSize = 3;
bool useHarrisDetector = false;
double k = 0.04;
Mat copy;
copy = src.clone();
goodFeaturesToTrack( src_gray,corners,maxCorners,qualityLevel,minDistance,Mat(),blockSize,useHarrisDetector,k );
cout<<"** Number of corners detected: "<<corners.size()<<endl;
int r = 4;
for( int i = 0; i < corners.size(); i++ )
{ circle( copy, corners[i], r, Scalar(rng.uniform(0,255), rng.uniform(0,255),rng.uniform(0,255)), -1, 8, 0 ); }
namedWindow( source_window, CV_WINDOW_AUTOSIZE );
imshow( source_window, copy );
Size winSize = Size( 10, 10 );
Size zeroZone = Size( -1, -1 );
TermCriteria criteria = TermCriteria( CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 40, 0.001 );
cornerSubPix( src_gray, corners, winSize, zeroZone, criteria );
for( int i = 0; i < corners.size(); i++ )
{ cout<<" -- Refined Corner ["<<i<<"] ("<<corners[i].x<<","<<corners[i].y<<")"<<endl; }
}
But I have this result:
this code ofind only corner's subpixel I want to find edge's subpixel
I am having doubt in opencv. I'm trying to implement SURF algorithm. When I trying to build the code but I'm getting the following error.
*****error LNK2019: unresolved external symbol _cvExtractSURF referenced in function _main
1>SAMPLE.obj : error LNK2019: unresolved external symbol _cvSURFParams referenced in function _main*****
I have gone through all the posts related to my topic in this forum, but couldn't figure out the problem with my code. Please help me in resolving my problem.
code :
#include <stdio.h>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc_c.h>
#include <opencv2\objdetect\objdetect.hpp>
#include <opencv2\calib3d\calib3d.hpp>
#include <opencv2\core\core.hpp>
#include <opencv2\legacy\legacy.hpp>
#include <opencv2\legacy\compat.hpp>
#include <opencv2/nonfree/nonfree.hpp>
#include <opencv\opensurf\surf.h>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
CvMemStorage* storage = cvCreateMemStorage(0);
cvNamedWindow("Image", 1);
int key = 0;
static CvScalar red_color[] ={0,0,255};
IplImage* capture= cvLoadImage( "testface.jpg");
CvMat* prevgray = 0, *image = 0, *gray =0;
while( key != 'q' )
{
int firstFrame = gray == 0;
IplImage* frame =capture;
if(!frame)
break;
if(!gray)
{
image = cvCreateMat(frame->height, frame->width, CV_8UC1);
}
//Convert the RGB image obtained from camera into Grayscale
cvCvtColor(frame, image, CV_BGR2GRAY);
//Define sequence for storing surf keypoints and descriptors
CvSeq *imageKeypoints = 0, *imageDescriptors = 0;
int i;
//Extract SURF points by initializing parameters
CvSURFParams params = cvSURFParams(500,1);
cvExtractSURF( image, 0, &imageKeypoints, &imageDescriptors, storage, params );
printf("Image Descriptors: %d\n", imageDescriptors->total);
//draw the keypoints on the captured frame
for( i = 0; i < imageKeypoints->total; i++ )
{
CvSURFPoint* r = (CvSURFPoint*)cvGetSeqElem( imageKeypoints, i );
CvPoint center;
int radius;
center.x = cvRound(r->pt.x);
center.y = cvRound(r->pt.y);
radius = cvRound(r->size*1.2/9.*2);
cvCircle( frame, center, radius, red_color[0], 1, 8, 0 );
}
cvShowImage( "Image", frame );
cvWaitKey(0);
}
cvDestroyWindow("Image");
return 0
}
Thank you,
Sreelakshmi Priya
I am trying to detect ears in a profile image(side view) of face.I tried using harrcascades (haarcascade_mcs_rightear,haarcascade_mcs_leftear,left_ear.xml,right_ear.xml) provided in opencv.I am able to detect profile face.But I am not able to detect ears with any one of haarcascade.I am specifying region of interest using profile face detector.I am not able to find out where i am going wrong.Please help me with that.A code snippet for the same would be of great help.Thanks in advance.Following is the code with comments.
#include <stdio.h>
#include<conio.h>
#include "cv.h"
#include "highgui.h"
using namespace std;
using namespace cv;
CvMemStorage *storage;
int detectFeature(int,char *imname,IplImage* image,CvRect featureROI, Rect* feature_box);
const char *file_profileface = "haarcascade_profileface.xml";
const char *ear_profileface = "left_ear.xml";//cascade name
CvRect profile_face;
CvRect ear;
int main()
{
int flagFaceDetect;
storage = cvCreateMemStorage(0);
assert(storage);
Rect faceRect;Rect leftEar;Rect rightEar;
char myimage1[50];
sprintf(myimage1,"profile%d.jpg",1);
IplImage* img = cvLoadImage(myimage1, CV_LOAD_IMAGE_COLOR);
/*first detect profile face and then detect ears*/
Rect* rectptr = &faceRect;//rectangle for profile face
CvRect face_roi = cvGetImageROI(img);
flagFaceDetect = detectFeature(0,myimage1,img,face_roi,rectptr);
rectptr = &leftEar;
//set ROI for ear with respect to profile face rectangle
CvRect leftear_roi = cvRect(faceRect.x+faceRect.x*3/4,faceRect.y+faceRect.height /4,faceRect.x+faceRect.width+faceRect.width/10,faceRect.y+faceRect.height-faceRect.height/4);
flagFaceDetect = detectFeature(1,myimage1,img,leftear_roi,rectptr);
getch();
return 0;
}
int detectFeature(int feature_index,char *imname,IplImage* image,CvRect featureROI, Rect* feature_box) {//general function to locate feature
cvSetImageROI(image, featureROI);
CvSeq* feature;
CvHaarClassifierCascade* featureCascade;
if(feature_index==0)//cascade for profile face
featureCascade = (CvHaarClassifierCascade*) cvLoad(file_profileface, 0, 0, 0);
if(feature_index==1)//cascade for ear
featureCascade = (CvHaarClassifierCascade*) cvLoad(ear_profileface, 0, 0, 0);
// feature = cvHaarDetectObjects(image,featureCascade,storage,1.1,2,CV_HAAR_DO_CANNY_PRUNING, cvSize(50,50));
feature = cvHaarDetectObjects(image,featureCascade,storage,1.2, 3,0,cvSize(18,12));
cvResetImageROI(image);
IplImage* displayImage = cvLoadImage(imname, CV_LOAD_IMAGE_COLOR);
CvRect* r;
int index_max_area;
int x1, x2, y1, y2; // opposite vertices of the rectangle
if (feature->total == 0) {
cout<<"here";
return 0;
}
else {
CvRect *fture = (CvRect*)cvGetSeqElem(feature, 0);
feature_box->x=fture->x;
feature_box->y=fture->y;
feature_box->height=fture->height;
feature_box->width=fture->width;
/* draw a red rectangle around the feature*/
cvRectangle(displayImage,
cvPoint(fture->x+fture->x*3/4,fture->y+fture->height/4),
cvPoint(fture->x+fture->width+fture->width/10,fture->y+fture->height-fture->height/4),
CV_RGB(0, 0, 255),
1, 8, 0
);
cvShowImage("frame",displayImage);
cvWaitKey(0);
return 1;
}
}
I'm trying to display a video from my webcam (which was working grand) and now I'm trying to implement circle detection into this video stream.
Unhandled exception at 0x001a1a4d in test.exe: 0xC0000005: Access violation reading location 0x00000004.)
The error is linked to the line of code:
cvCircle( img, cvPoint(cvRound(p[0]),cvRound(p[1])), 3, CV_RGB(255,0,0), -1, 8, 0 );.
Can anyone help please?
#include <stdio.h>
#include "cv.h"
#include "highgui.h"
#include <iostream>
#include <math.h>
#include <string.h>
#include <conio.h>
using namespace std;
IplImage* img = 0;
CvMemStorage * cstorage;
CvMemStorage * hstorage;
void detectCircle( IplImage *frame );
int main( int argc, char **argv )
{
CvCapture *capture = 0;
IplImage *frame = 0;
int key = 0;
hstorage = cvCreateMemStorage( 0 );
cstorage = cvCreateMemStorage( 0 );
//CvVideoWriter *writer = 0;
//int colour = 1;
//int fps = 25;
//int frameW = 640;
//int frameH = 480;
//writer = cvCreateVideoWriter("test.avi",CV_FOURCC('P', 'I', 'M', '1'),fps,cvSize(frameW,frameH),colour);
//initialise camera
capture = cvCaptureFromCAM( 0 );
//check if camera present
if ( !capture )
{
fprintf( stderr, "cannot open webcam\n");
return 1;
}
//create a window
cvNamedWindow( "Snooker", CV_WINDOW_AUTOSIZE );
while(key !='q')
{
//get frame
frame = cvQueryFrame(capture);
//int nFrames = 50;
//for (int i=0; i<nFrames;i++){
//cvGrabFrame(capture);
//frame = cvRetrieveFrame(capture);
//cvWriteFrame(writer, frame);
//}
//check for frame
if( !frame ) break;
detectCircle(frame);
//display current frame
//cvShowImage ("Snooker", frame );
//exit if Q pressed
key = cvWaitKey( 20 );
}
// free memory
cvDestroyWindow( "Snooker" );
cvReleaseCapture( &capture );
cvReleaseMemStorage( &cstorage);
cvReleaseMemStorage( &hstorage);
//cvReleaseVideoWriter(&writer);
return 0;
}
void detectCircle( IplImage * img )
{
int px;
int py;
int edge_thresh = 1;
IplImage *gray = cvCreateImage( cvSize(img->width,img->height), 8, 1);
IplImage *edge = cvCreateImage( cvSize(img->width,img->height), 8, 1);
cvCvtColor(img, gray, CV_BGR2GRAY);
gray->origin = 1;
// color threshold
cvThreshold(gray,gray,100,255,CV_THRESH_BINARY);
// smooths out image
cvSmooth(gray, gray, CV_GAUSSIAN, 11, 11);
// get edges
cvCanny(gray, edge, (float)edge_thresh, (float)edge_thresh*3, 5);
// detects circle
CvSeq* circle = cvHoughCircles(gray, cstorage, CV_HOUGH_GRADIENT, 1, gray->height/50, 5, 35);
// draws circle and its centerpoint
float* p = (float*)cvGetSeqElem( circle, 0 );
cvCircle( img, cvPoint(cvRound(p[0]),cvRound(p[1])), 3, CV_RGB(255,0,0), -1, 8, 0 );
cvCircle( img, cvPoint(cvRound(p[0]),cvRound(p[1])), cvRound(p[2]), CV_RGB(200,0,0), 1, 8, 0 );
px=cvRound(p[0]);
py=cvRound(p[1]);
cvShowImage ("Snooker", img );
}