Error opencv & openframework While cropping image - image-processing

I have the following code:
IplImage* f( IplImage* src )
{
// Must have dimensions of output image
IplImage* cropped = cvCreateImage( cvSize(1280,500), src->depth, src->nChannels );
// Say what the source region is
cvSetImageROI( src, cvRect( 0,0, 1280,500 ) );
// Do the copy
cvCopy( src, cropped );
cvResetImageROI( src );
return cropped;
}
void testApp::setup(){
img.loadImage("test.jpg");
finder.setup("haarcascade_frontalface_default.xml");
finder.findHaarObjects(img);
}
//--------------------------------------------------------------
void testApp::update(){
}
//--------------------------------------------------------------
ofRectangle cur;
void testApp::draw(){
img = f(img);
img.draw(0, 0);
ofNoFill();
for(int i = 0; i < finder.blobs.size(); i++) {
cur = finder.blobs[i].boundingRect;
ofRect(cur.x-20, cur.y-20, cur.width+50, cur.height+50);
}
}
It produces an error. I think it's because I don't convert IplImage to ofImage. Can someone please tell me how to do it?

I would imagine that your instance of img, that your passing to f(), is an instance of ofxCVImage or similar. As far as I know ofx store a protected variable of iplimage, as such you can't cast ofxCVImage to an iplimage.
You might try
img = f(img.getCvImage()) // ofxCvImage::getCvImage() returns IplImage

Related

How to convert Mat to IplImage in Javacv?

Is any one know how i can convert Mat to IplImage ?
to achieve this i have converted Mat to BufferedImage but again not able to find conversion in BufferedImage to IplImage.
is there any way where i can convert Mat to IplImage?
Thanks
I believe you can convert BufferedImage to IplImage as follows.
public static IplImage toIplImage(BufferedImage src) {
Java2DFrameConverter bimConverter = new Java2DFrameConverter();
OpenCVFrameConverter.ToIplImage iplConverter = new OpenCVFrameConverter.ToIplImage();
Frame frame = bimConverter.convert(src);
IplImage img = iplConverter.convert(frame);
IplImage result = img.clone();
img.release();
return result;
}
I got this from this question. Try this for now. I'll check if direct conversion is possible.
UPDATE:
Please have a look at this api docs. I haven't tested the following. Wrote it just now. Please do try and let me know.
public static IplImage toIplImage(Mat src) {
OpenCVFrameConverter.ToIplImage iplConverter = new OpenCVFrameConverter.ToIplImage();
OpenCVFrameConverter.ToMat matConverter = new OpenCVFrameConverter.ToMat();
Frame frame = matConverter.convert(src);
IplImage img = iplConverter.convert(frame);
IplImage result = img.clone();
img.release();
return result;
}

Gathering the confidence with JAVACV program

Trying to figure out a way to gather the confidence level when it actually does the face recognizing on the target image. I have searched through a few examples but haven't found anything I can see how to implement. All help appreciated, thanks guys.
public static void facecompare() {
String trainingDir = "C:/TrainingDirectory"; //training directory
IplImage testImage = cvLoadImage("C:/TargetImages/boland_straight_happy_open_4.pgm"); //the target image
File root = new File(trainingDir);
FilenameFilter pngFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".pgm");
}
};
File[] imageFiles = root.listFiles(pngFilter);
MatVector images = new MatVector(imageFiles.length);
int[] labels = new int[imageFiles.length];
int counter = 0;
int label;
IplImage img;
IplImage grayImg;
for (File image : imageFiles) {
img = cvLoadImage(image.getAbsolutePath());
label = Integer.parseInt(image.getName().split("\\-")[0]);
grayImg = IplImage.create(img.width(), img.height(), IPL_DEPTH_8U, 1);
cvCvtColor(img, grayImg, CV_BGR2GRAY);
images.put(counter, grayImg);
labels[counter] = label;
counter++;
}
IplImage greyTestImage = IplImage.create(testImage.width(), testImage.height(), IPL_DEPTH_8U, 1);
// FaceRecognizer faceRecognizer = createFisherFaceRecognizer();
// FaceRecognizer faceRecognizer = createEigenFaceRecognizer();
FaceRecognizer faceRecognizer = createLBPHFaceRecognizer();
faceRecognizer.train(images, labels);
cvCvtColor(testImage, greyTestImage, CV_BGR2GRAY);
int predictedLabel = faceRecognizer.predict(greyTestImage);
System.out.println("Predicted label: " + predictedLabel);
}
There is another predict method that returns the confidence:
// pointer-like output parameters
// only the first element of these arrays will be changed
int[] plabel = new int[1];
double[] pconfidence = new double[1];
faceRecognizer.predict(greyTestImage, plabel, pconfidence);
int predictedLabel = plabel[0];
double confidence = pconfidence[0];

JavaCV/OpenCV cvDrawContours modifies original image

I am experimenting with JavaCV (OpenCV) and I am confused with the following behavior.
My programm simply:
Grab an image
Create a grayscale version of the image (leaving the original image untouched)
Threshold the grayscale image
Find contours in the grayscale image (cloning the image since cvFindContours modifies the image and we want to display it as is)
Draw contours on the original color image
The problem is that unless I clone the grabbedImage (see commented line), the grayscale image is modified and contours are drawn on it. Also, it is as if multiple contours are drawn on the grabbedImage.
I also tried to add a sleep to the loop and it fixes the problem. Could it be that I get the same (modified) grabbedImage multiple time? I checked the java reference and it's different but could it be the same buffer?
Any idea?
Thank you
package com.mdarveau.opencvtest;
import static com.googlecode.javacv.cpp.opencv_core.*;
import static com.googlecode.javacv.cpp.opencv_imgproc.*;
import com.googlecode.javacpp.Loader;
import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.FrameGrabber;
import com.googlecode.javacv.cpp.opencv_core.CvContour;
import com.googlecode.javacv.cpp.opencv_core.CvMemStorage;
import com.googlecode.javacv.cpp.opencv_core.CvScalar;
import com.googlecode.javacv.cpp.opencv_core.CvSeq;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
import com.googlecode.javacv.cpp.opencv_objdetect;
public class Demo {
public static void main( String[] args ) throws Exception {
// Preload the opencv_objdetect module to work around a known bug.
Loader.load( opencv_objdetect.class );
FrameGrabber grabber = FrameGrabber.createDefault( 1 );
grabber.start();
IplImage grabbedImage = grabber.grab();
int width = grabbedImage.width();
int height = grabbedImage.height();
IplImage grayImage = IplImage.create( width, height, IPL_DEPTH_8U, 1 );
CvMemStorage storage = CvMemStorage.create();
CanvasFrame filterProbe = new CanvasFrame( "Filtered", CanvasFrame.getDefaultGamma() / grabber.getGamma() );
CanvasFrame enhancedProbe = new CanvasFrame( "Enhanced", CanvasFrame.getDefaultGamma() / grabber.getGamma() );
while ( filterProbe.isVisible() && enhancedProbe.isVisible() && (grabbedImage = grabber.grab()) != null ) {
cvClearMemStorage( storage );
// Convert to grayscale image...
cvCvtColor( grabbedImage, grayImage, CV_BGR2GRAY );
// UNCOMMENT FIXES THE PROBLEM grabbedImage = grabbedImage.clone();
// Let's find some contours! but first some thresholding...
cvThreshold( grayImage, grayImage, 128, 255, CV_THRESH_BINARY );
// To check if an output argument is null we may call either isNull() or equals(null).
CvSeq contour = new CvSeq( null );
// cvFindContours modifies the image so clone it first since we want to keep the grayscale version
cvFindContours( grayImage.clone(), storage, contour, Loader.sizeof( CvContour.class ), CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE );
while ( contour != null && !contour.isNull() ) {
if ( contour.elem_size() > 0 ) {
CvSeq points = cvApproxPoly( contour, Loader.sizeof( CvContour.class ), storage, CV_POLY_APPROX_DP, cvContourPerimeter( contour ) * 0.02, 0 );
cvDrawContours( grabbedImage, points, CvScalar.BLUE, CvScalar.BLUE, -1, 1 /*CV_FILLED*/, CV_AA );
}
contour = contour.h_next();
}
filterProbe.showImage( grayImage );
enhancedProbe.showImage( grabbedImage );
}
filterProbe.dispose();
enhancedProbe.dispose();
grabber.stop();
}
}
This is the expected behavior of cvFindContours():
The function modifies the image while extracting the contours.

Opencv: image, retrieved from camera capture is always gray

I am always getting a grey screen when showing image using opencv, the image is captured from camera.
capture = cvCaptureFromCAM(-1);
cvGrabFrame(capture);
image = cvRetrieveFrame(capture);
cvShowImage("name", image);
after this I see the grey screen, even if I do in cycle. But the same code works well on another computer. What is the problem? The same opencv library version is used on both computers. Working in the Visual Studio 2010, C++
Opencv version 2.2.0
EDIT 1: The camera used in both computers is the same.
And I have tried to rebuild the opencv on the computer where the problem happens, it didn't help.
I had the same problem in OpenCvSharp. I don't know what's the cause, but for some reason, calling the "WaitKey" method after displaying the image solved it.
CvCapture mov = new CvCapture(filepath);
IplImage frame = mov.QueryFrame();
CvWindow win1 = new CvWindow(window name);
win1.ShowImage(frame);
CvWindow.WaitKey(1);
Your problem sounds very weird.
Try to use cvQueryFrame instead of cvRetrieveFrame() and let me know if it does make a difference.
Here is a code of using opencv for face detection, the concept of capturing an image is very similar:
int main( int argc, const char** argv )
{
CvCapture* capture;
Mat frame;
//-- 1. Load the cascades
if( !face_cascade.load( face_cascade_name ) ){ printf("--(!)Error loading\n"); return -1; };
if( !eyes_cascade.load( eyes_cascade_name ) ){ printf("--(!)Error loading\n"); return -1; };
//-- 2. Read the video stream
capture = cvCaptureFromCAM( -1 );
if( capture )
{
while( true )
{
frame = cvQueryFrame( capture );
//-- 3. Apply the classifier to the frame
if( !frame.empty() )
{ detectAndDisplay( frame ); }
else
{ printf(" --(!) No captured frame -- Break!"); break; }
int c = waitKey(10);
if( (char)c == 'c' ) { break; }
}
}return 0;
}

"QImage with no type" compile error message

Hello Can anyone help me figure out how to solve this bug message? I am trying to rewrite a Qt3 working code into Qt4 for converting IplImage to QImage and found the "right conversion types" however my code as below results in " ISO C++ forbids declaration of 'QImage' with no type"
....
QImage *qqImage;
if (this->data->nChannels == 1)
{
QVector<QRgb> myColorTable;
for (int i = 0; i < 256; i++)
myColorTable.push_back(qRgb(i, i, i)); //colorTable[i]);
qqImage = new QImage(qImageBuffer, width, height, QImage::Format_Indexed8);
}
else
{
qqImage = new QImage(qImageBuffer, width, height, QImage::Format_RGB32);
}
return qqImage;
The code piece below works on my Qt4 app, give it a try.
// img1 and img2 are Mat objects, img1 is grayscale,
// img2 is three channel RGB image
QImage qimg1,qimg2;
if (this->data->nChannels == 1){
qimg1=QImage(img1.data,img1.cols,img1.rows,QImage::Format_Indexed8);
}
else {
qimg2=QImage(img2.data,img2.cols,img2.rows,QImage::Format_RGB888);
}

Resources