Trouble in OPENCV trackbar. - opencv

I got a trouble in using a trackbar in opencv . I want it for changing the reference image in SURF for object recognition but the problem is only one reference image is detected in my program.
I know this is very basic but I am new to opencv. I hope someone give me solution.
Thanks.
#include <iostream>
#include <opencv/cxcore.h>
#include <opencv2\imgproc\imgproc_c.h>
#include <stdio.h>
#include <math.h>
#include <opencv\highgui.h>
#include <opencv\cv.h>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/nonfree/features2d.hpp>
#include <opencv2/legacy/legacy.hpp>
#include <opencv2\nonfree\nonfree.hpp>
using namespace std;
#include "MareMatchingClass.h"
int colorInt;
int g_switch_value=0;
// Trackbar/switch callback
void switch_callback( int position ){
if( g_switch_value == 0 ){
colorInt = 0;
}else{
colorInt = 1;
}
}
int main()
{
cv::initModule_nonfree();
IplImage* PatchImg;
cvNamedWindow("mainWin",CV_WINDOW_AUTOSIZE);
cvCreateTrackbar( "Switch","mainWin", &g_switch_value, 1, switch_callback );
if( colorInt == 0)
{
PatchImg = cvLoadImage("D:/id2.jpg", CV_LOAD_IMAGE_GRAYSCALE);
}
else
{
PatchImg = cvLoadImage("D:/id.jpg", CV_LOAD_IMAGE_GRAYSCALE);
}
//Create Matching class
CMareMatchingClass MMathing;
//Input PatchImg
MMathing.ExtractPatchSurf(PatchImg);
double cornerPt[9]={
MMathing.PatchWidth/2, 0, MMathing.PatchWidth,
0, MMathing.PatchHeight, MMathing.PatchHeight,
1, 1, 1};
CvMat* McornerPt2 = cvCreateMat(3, 3, CV_64FC1);
memcpy(McornerPt2->data.db, cornerPt, sizeof(double)*9);
int c;
IplImage* img;
IplImage* BackGroundImg = NULL;
CvCapture* capture = cvCaptureFromCAM(0);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, 320);
cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_HEIGHT, 240 );
while(1)
{
cvGrabFrame(capture);
img = cvRetrieveFrame(capture);
if(BackGroundImg == NULL)
{
BackGroundImg = cvCreateImage(cvSize(img->width, img->height), 8, 1);
}
cvCvtColor(img, BackGroundImg, CV_RGB2GRAY);
Rect4Pt rect4pt;
if(MMathing.GetObjectRectAndBestH(BackGroundImg, &rect4pt) != 0)
{
cvLine(img, cvPoint(rect4pt.LeftTop.x, rect4pt.LeftTop.y),
cvPoint(rect4pt.RightTop.x, rect4pt.RightTop.y), cvScalar(255,0,0), 2);
cvLine(img, cvPoint(rect4pt.RightTop.x, rect4pt.RightTop.y),
cvPoint(rect4pt.RightBottom.x, rect4pt.RightBottom.y), cvScalar(255,0,0), 2);
cvLine(img, cvPoint(rect4pt.RightBottom.x, rect4pt.RightBottom.y),
cvPoint(rect4pt.LeftBottom.x, rect4pt.LeftBottom.y), cvScalar(255,0,0), 2);
cvLine(img, cvPoint(rect4pt.LeftBottom.x, rect4pt.LeftBottom.y),
cvPoint( rect4pt.LeftTop.x, rect4pt.LeftTop.y), cvScalar(255,0,0), 2);
Rect4Pt rect4ptZ;
MMathing.GetHMulRect(McornerPt2,&rect4ptZ);
}
cvShowImage("mainWin",img);
c = cvWaitKey(10);
if(c == 27)
break;
}
cvReleaseCapture(&capture);
cvDestroyAllWindows();
cvReleaseImage(&PatchImg);
cvReleaseImage(&BackGroundImg);
cvReleaseMat(&McornerPt2);
}

I think you have to move code
if(colorInt!=lastColorInt)
{
if( colorInt == 0)
{
PatchImg = cvLoadImage("D:/id2.jpg", CV_LOAD_IMAGE_GRAYSCALE);
}
else
{
PatchImg = cvLoadImage("D:/id.jpg", CV_LOAD_IMAGE_GRAYSCALE);
}
lastColorInt=colorInt;
}
inside the while loop and change it for looking for changing state of colorInt variable (as I change it, for example). Don't forget release allocated images.

Related

Why is webcam image processing slow while using Xcode in an OpenCV project?

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;
}

Why is OpenCV Gpu module performing faster than VisionWorks?

I have tried several functions of OpenCv gpu module and compared the same behavior with visionWorks immediate code. And surprisingly, it all circumstances the OpenCv Gpu Module is performing significantly faster than VisionWorks.
e-g
a Gaussian pyramid of level 4 implemented manually using opencv
#include <iostream>
#include <stdio.h>
#include <stdio.h>
#include <queue>
/* OPENCV RELATED */
#include <cv.h>
#include <highgui.h>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/stitching/detail/util.hpp"
#include "opencv2/stitching/detail/warpers.hpp"
#include "opencv2/stitching/warpers.hpp"
#include <opencv2/gpu/gpu.hpp>
#include "opencv2/opencv_modules.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/stitching/detail/autocalib.hpp"
#include "opencv2/stitching/detail/blenders.hpp"
#include "opencv2/stitching/detail/camera.hpp"
#include "opencv2/stitching/detail/exposure_compensate.hpp"
#include "opencv2/stitching/detail/matchers.hpp"
#include "opencv2/stitching/detail/motion_estimators.hpp"
#include "opencv2/stitching/detail/seam_finders.hpp"
#include "opencv2/stitching/detail/util.hpp"
#include "opencv2/stitching/detail/warpers.hpp"
#include "opencv2/stitching/warpers.hpp"
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
using namespace gpu;
using namespace cv::detail;
int main()
{
Mat m = imread("br1.png");
GpuMat d_m = GpuMat (m);
GpuMat d_m2;
GpuMat l1,l2,l3,l4;
int iter = 100;
int64 e = getTickCount();
float sum = 0;
sum = 0;
for(int i = 0 ; i < iter; i++)
{
e = getTickCount();
gpu::pyrDown(d_m,l1);
gpu::pyrDown(l1,l2);
gpu::pyrDown(l2,l3);
gpu::pyrDown(l3,l4);
sum+= (getTickCount() - e) / getTickFrequency();
}
cout <<"Time taken by Gussian Pyramid Level 4 \t\t\t"<<sum/iter<<" sec"<<endl;
//imwrite("cv_res.jpg",res);
return 0;
}
takes 2.5 ms on average for 100 iterations. Whereas, VisionWorks
#include <VX/vx.h>
#include <VX/vxu.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <stdio.h>
#include <stdio.h>
#include <queue>
/* OPENCV RELATED */
#include <cv.h>
#include <highgui.h>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/stitching/detail/util.hpp"
#include "opencv2/stitching/detail/warpers.hpp"
#include "opencv2/stitching/warpers.hpp"
#include <opencv2/gpu/gpu.hpp>
#include "opencv2/opencv_modules.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/stitching/detail/autocalib.hpp"
#include "opencv2/stitching/detail/blenders.hpp"
#include "opencv2/stitching/detail/camera.hpp"
#include "opencv2/stitching/detail/exposure_compensate.hpp"
#include "opencv2/stitching/detail/matchers.hpp"
#include "opencv2/stitching/detail/motion_estimators.hpp"
#include "opencv2/stitching/detail/seam_finders.hpp"
#include "opencv2/stitching/detail/util.hpp"
#include "opencv2/stitching/detail/warpers.hpp"
#include "opencv2/stitching/warpers.hpp"
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
using namespace gpu;
using namespace cv::detail;
vx_image createImageFromMat(vx_context& context, cv::Mat& mat);
vx_status createMatFromImage(vx_image& image, cv::Mat& mat);
/* Entry point. */
int main(int argc,char* argv[])
{
Mat cv_src1 = imread("br1.png", IMREAD_GRAYSCALE);
int width = 1280;
int height = 720;
int half_width = width/2;
int half_height = height/2;
Mat dstMat(cv_src1.size(), cv_src1.type());
Mat half_dstMat(Size(width/16,height/16),cv_src1.type());
/* Image data. */
if (cv_src1.empty() )
{
std::cerr << "Can't load input images" << std::endl;
return -1;
}
/* Create our context. */
vx_context context = vxCreateContext();
/* Image to process. */
vx_image image = createImageFromMat(context, cv_src1);
//NVXIO_CHECK_REFERENCE(image);
/* Intermediate images. */
vx_image dx = vxCreateImage(context, width, height, VX_DF_IMAGE_S16);
vx_image dy = vxCreateImage(context, width, height, VX_DF_IMAGE_S16);
vx_image mag = vxCreateImage(context, width, height, VX_DF_IMAGE_S16);
vx_image half_image = vxCreateImage(context, half_width, half_height, VX_DF_IMAGE_U8);
vx_image half_image_2 = vxCreateImage(context, half_width/2, half_height/2, VX_DF_IMAGE_U8);
vx_image half_image_3 = vxCreateImage(context, half_width/4, half_height/4, VX_DF_IMAGE_U8);
vx_image half_image_4 = vxCreateImage(context, half_width/8, half_height/8, VX_DF_IMAGE_U8);
int64 e = getTickCount();
int iter = 100;
float sum = 0.0;
e = getTickCount();
iter = 100;
for(int i = 0 ; i < iter; i ++)
{
/* RESIZEZ OPERATION */
if(vxuHalfScaleGaussian(context,image,half_image,3) != VX_SUCCESS)
{
cout <<"ERROR :"<<"failed to perform scaling"<<endl;
}
if(vxuHalfScaleGaussian(context,half_image,half_image_2,3) != VX_SUCCESS)
{
cout <<"ERROR :"<<"failed to perform scaling"<<endl;
}
if(vxuHalfScaleGaussian(context,half_image_2,half_image_3,3) != VX_SUCCESS)
{
cout <<"ERROR :"<<"failed to perform scaling"<<endl;
}
if(vxuHalfScaleGaussian(context,half_image_3,half_image_4,3) != VX_SUCCESS)
{
cout <<"ERROR :"<<"failed to perform scaling"<<endl;
}
sum += (getTickCount() - e) / getTickFrequency();
}
cout <<"Resize to half " <<sum/iter<<endl;
createMatFromImage(half_image_4,half_dstMat);
imwrite("RES.jpg",half_dstMat);
/* Tidy up. */
vxReleaseImage(&dx);
vxReleaseImage(&dy);
vxReleaseImage(&mag);
vxReleaseContext(&context);
}
vx_image createImageFromMat(vx_context& context, cv::Mat& mat)
{
vx_imagepatch_addressing_t src_addr = {
mat.cols, mat.rows, sizeof(vx_uint8), mat.cols * sizeof(vx_uint8), VX_SCALE_UNITY, VX_SCALE_UNITY, 1, 1 };
void* src_ptr = mat.data;
vx_image image = vxCreateImageFromHandle(context, VX_DF_IMAGE_U8, &src_addr, &src_ptr, VX_IMPORT_TYPE_HOST);
return image;
}
vx_status createMatFromImage(vx_image& image, cv::Mat& mat)
{
vx_status status = VX_SUCCESS;
vx_uint8 *ptr = NULL;
cout <<"Creating image "<<mat.cols << " " <<mat.rows <<endl;
vx_rectangle_t rect;
vxGetValidRegionImage(image, &rect);
vx_imagepatch_addressing_t addr = {
mat.cols, mat.rows, sizeof(vx_uint8), mat.cols * sizeof(vx_uint8), VX_SCALE_UNITY, VX_SCALE_UNITY, 1, 1 };
status = vxAccessImagePatch(image, &rect, 0, &addr, (void **)&ptr, VX_READ_ONLY);
mat.data = ptr;
return status;
}
takes 11.1 ms on single execution, and 96ms on average for 100 iterations.
If this is generally true, then what does visionWorks offer ?
I am running "cuda-repo-l4t-r21.3-6-5-local_6.5-50" version of L4T on Jetson TK1
You've made a mistake in VisionWorks code. You start timer only once e = getTickCount(); right before the loop, but you need to start it on each iteration.
iter = 100;
for(int i = 0 ; i < iter; i ++)
{
// START TIMER
e = getTickCount();
/* RESIZEZ OPERATION */
if(vxuHalfScaleGaussian(context,image,half_image,3) != VX_SUCCESS)
{
cout <<"ERROR :"<<"failed to perform scaling"<<endl;
}
if(vxuHalfScaleGaussian(context,half_image,half_image_2,3) != VX_SUCCESS)
{
cout <<"ERROR :"<<"failed to perform scaling"<<endl;
}
if(vxuHalfScaleGaussian(context,half_image_2,half_image_3,3) != VX_SUCCESS)
{
cout <<"ERROR :"<<"failed to perform scaling"<<endl;
}
if(vxuHalfScaleGaussian(context,half_image_3,half_image_4,3) != VX_SUCCESS)
{
cout <<"ERROR :"<<"failed to perform scaling"<<endl;
}
// STOP TIMER
sum += (getTickCount() - e) / getTickFrequency();
}
I think that the following code is mistake.
Mat cv_src1 = imread("br1.png", IMREAD_GRAYSCALE);
int width = 1280;
int height = 720;
I think that you should be set as follows.
Mat cv_src1 = imread("br1.png", IMREAD_GRAYSCALE);
vx_uint32 width = cv_src1.cols;
vx_uint32 height = cv_src1.rows;
And, I made sample code to reproduce.
But, VisionWorks(about 0.3ms) faster than GpuMat(about 0.4ms) on my environment.
https://gist.github.com/atinfinity/9c8c067db739b190ba17f2bd8dbe75d6
https://gist.github.com/atinfinity/e8c2f2da6486be51881e3924c13a311c
My environment is as follows.
GPU: NVIDIA GeForce GTX 680
OS: Windows 10 Pro 64bit
Compiler: Visual Studio 2013 Update5
VisionWorks:NVIDIA VisionWorks v1.0.25
OpenCV: OpenCV 3.1

capture’ was not declared in this scope capture = cvCaptureFromCAM( 0 ); how to fix it

I was following a tutorial on web for an OpenCV library to detect eyes
when i compile it this error appears I tried to fix it but didn't find a
solution.
main.cpp:59:1: error: ‘capture’ was not declared in this scope
capture = cvCaptureFromCAM( 0 );
The code is long I put only the part that I think causing this error .
: Full code
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <queue>
#include <stdio.h>
#include <math.h>
#include "constants.h"
#include "findEyeCenter.h"
#include "findEyeCorner.h"
/** Function Headers */
void detectAndDisplay( cv::Mat frame );
int main( )
{
cv::Mat frame;
if( !face_cascade.load( face_cascade_name ) ){ printf("--(!)Error loading face cascade, please change face_cascade_name in source code.\n"); return -1; };
createCornerKernels();
ellipse(skinCrCbHist, cv::Point(113, 155.6), cv::Size(23.4, 15.2),
43.0, 0.0, 360.0, cv::Scalar(255, 255, 255), -1);
capture = cvCaptureFromCAM( 0 );
if( capture)
{
while( true )
{
frame = cvQueryFrame( capture );
// mirror it
imshow("Video",frame);
cv::flip(frame, frame, 1);
frame.copyTo(debugImage);
// Apply the classifier to the frame
if( !frame.empty() ) {
detectAndDisplay( frame );
}
else {
printf(" --(!) No captured frame -- Break!");
break;
}
imshow(main_window_name,debugImage);
int c = cv::waitKey(10);
if( (char)c == 'c' ) { break; }
if( (char)c == 'f' ) {
imwrite("frame.png",frame);
}
}
}
releaseCornerKernels();
return 0;
}
}
try to use VideoCapture capture(0);

Can OpenCV be developed using C++ and C together

Can OpenCV be developed using C++ and C together? Following is the program where i meet this problem.It is coded with C and works well.But if I use
cv::Mat saveImage=cv::imread("D:\\opencvStudy\\opencv_test\\TaskDemo\\TaskDemo\\save.jpg");
cv::imshow("save",saveImage);
to replace
IplImage* saveImge =cvLoadImage("D:\\opencvStudy\\opencv_test\\TaskDemo\\TaskDemo\\save.jpg");
cvShowImage("saveimage",saveImge);
I met this:
Unhandled exception at 0x75709673 in TaskDemo.exe: Microsoft C++ exception: cv::Exception at memory location 0x0039ea0c..
Following is the whole program. Hope anyone could help me .Thanks very much
#include<opencv/cv.h>
#include<opencv/highgui.h>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/video/tracking.hpp"
#include <iostream>
#include <ctype.h>
CvPoint pt1 = cvPoint(0,0);
CvPoint pt2 = cvPoint(0,0);
bool is_selecting = false;
void cvMouseCallback(int mouseEvent,int x,int y,int flags,void* param)
{
switch(mouseEvent)
{
case CV_EVENT_LBUTTONDOWN:
pt1 = cvPoint(x,y);
pt2 = cvPoint(x,y);
is_selecting = true;
break;
case CV_EVENT_MOUSEMOVE:
if(is_selecting)
pt2 = cvPoint(x,y);
break;
case CV_EVENT_LBUTTONUP:
pt2 = cvPoint(x,y);
is_selecting = false;
break;
}
return;
}
int main(int argc,char* argv[])
{
char img_path[80] = "D:\\opencvStudy\\pic\\boldt.jpg";
char save_path[80] = "save.jpg";
char* window = "img";
IplImage* img = cvLoadImage(img_path);
IplImage* img_show = cvCloneImage(img);
cvNamedWindow(window,CV_WINDOW_AUTOSIZE);
cvSetMouseCallback(window,cvMouseCallback);
char text[80];
CvFont font;
cvInitFont(&font,CV_FONT_HERSHEY_PLAIN,1.0,1.0);
while(true)
{
cvCopy(img,img_show);
cvRectangle(img_show,pt1,pt2,cvScalar(255,255,255));
sprintf(text,"roi = cvRect(%d,%d,%d,%d)",pt1.x,pt1.y,std::abs(pt2.x-pt1.x),std::abs(pt2.y-pt1.y));
cvPutText(img_show,text,cvPoint(10,20),&font,cvScalar(0,0,255));
cvShowImage(window,img_show);
char key = cvWaitKey(10);
if (key='r')
{
cvSetImageROI(img,cvRect(pt1.x,pt1.y,std::abs(pt2.x-pt1.x),std::abs(pt2.y-pt1.y)));
cvSaveImage(save_path,img);
cvResetImageROI(img);
IplImage* saveImge = cvLoadImage("D:\\opencvStudy\\opencv_test\\TaskDemo\\TaskDemo\\save.jpg");
cvShowImage("saveimage",saveImge);
//cv::Mat saveImage=cv::imread("D:\\opencvStudy\\opencv_test\\TaskDemo\\TaskDemo\\save.jpg");
//cv::imshow("save",saveImage);
}
else if(key==27)
break;
}
cvReleaseImage(&img);
cvReleaseImage(&img_show);
return 0;
}
Update
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core/core.hpp"
#include <iostream>
#include <ctype.h>
using namespace std;
using namespace cv;
cv::Point pt1=Point(0,0);
cv::Point pt2=Point(0,0);
bool is_selecting=false;
static void onMouse(int mouseEvent,int x,int y,int flags,void* param)
{
switch(mouseEvent)
{
case CV_EVENT_LBUTTONDOWN://CV_EVENT_LBUTTONDOWN
pt1 = Point(x,y);
pt2 = Point(x,y);
is_selecting = true;
break;
case CV_EVENT_MOUSEMOVE:
if(is_selecting)
pt2 = Point(x,y);
break;
case CV_EVENT_LBUTTONUP:
pt2 = Point(x,y);
is_selecting = false;
break;
}
}
int main()
{
cv::Mat img=cv::imread("D:\\opencvStudy\\pic\\boldt.jpg");
cv::Mat img_show=img.clone();
cv::namedWindow("Task2",0);
cv::setMouseCallback("Task2",onMouse,0);
char text[80];
while(true)
{
img.copyTo(img_show);
cv::rectangle(img_show,pt1,pt2,cv::Scalar(255,255,255));
sprintf(text,"roi = cvRect(%d,%d,%d,%d)",pt1.x,pt1.y,std::abs(pt2.x-pt1.x),std::abs(pt2.y-pt1.y));
cv::putText(img_show,text,cvPoint(10,20),10,10,Scalar(0,0,255));
cv::imshow("Task2",img_show);
char key=cv::waitKey(10);
if (key='r')
{
cv::Mat save=img(cv::Rect(pt1.x,pt1.y,std::abs(pt2.x-pt1.x),std::abs(pt2.y-pt1.y)));
cv::imwrite("save.jpg",save);
cv::Mat saveImage=cv::imread("D:\\opencvStudy\\opencv_test\\TaskDemo\\TaskDemo\\save.jpg");
cv::imshow("save",saveImage);
}
else if(key==27)
break;
}
return 0;
}
The problem is with conflicting headers. You should not include old and new at the same time like this:
#include<opencv/cv.h>
#include<opencv/highgui.h>
#include "opencv2/highgui/highgui.hpp"
Instead, include the new headers only, like this:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
The reason for this is that the C++ headers also include the C interface.
UPDATE:
Of course if you use cv::Mat then you need to use the new functions for that as well.
CvCopy becomes cv::copy, there is no cvReleaseImage needed, cvRectangle becomes cv::rectangle, cvSetImageROI is img(rect), cvPoint becomes cv::Point cvRect becomes cv::Rect
cvCloneImage becomes img.clone() and so on...
Or you need some conversion from cv::Mat to IplImage to use the old functions. There are some questions on SO dealing with converting back-and-forth.
UPDATE2:
It is best to remove all cv:: since you are using using namespace cv.
Then check for functions and variables left with the old cv prefix, and remove those prefixes. (I've still found one: cvPoint).
Hang on, you are using char text[80]!
I think that is again a source of problems. It is best to switch it to
#include <sstream>
//...
stringstream ss;
ss << "Rect(" << pt1.x << ", " << ... << ")";
//...
putText(img_show, ss.str(), Point(10,20), FONT_HERSHEY_PLAIN, 1, Scalar(0, 0, 255) );
Note that the font (I use) is not 10, but FONT_HERSHEY_PLAIN (or some other FONT_ constant).

OpenCV 2: How to save a ROI

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;
}

Resources