OpenCV Image To Matrix In txt files - opencv

I am doing this to get each pixel value of Image and printing it on Console
include "stdafx.h"
include "opencv2/imgproc/imgproc.hpp"
include "opencv2/highgui/highgui.hpp"
include <stdlib.h>
include <stdio.h>
using namespace cv;
int main( int argc, char** argv )
{
IplImage *img = cvLoadImage("lena.jpg");
CvMat *mat = cvCreateMat(img->height,img->width,CV_32FC3 );
cvConvert( img, mat );
for(int i=0;i<10;i++)
{
for(int j=0;j<10;j++)
{
CvScalar scal = cvGet2D( mat,j,i);
printf( "(%.f,%.f,%.f) ",scal.val[0], scal.val[1], scal.val[2] );
}
printf("\n");
}
waitKey(1);
return 0;
}
Is there better way to get each pixel value along with there header and channel values in txt.files

I would recommend against using the C API if you can help it. The C++ API is much easier to use. As for storage of a matrix in a file, have a look at the FileStorage class available in OpenCV.
It's as easy as:
Write
FileStorage fs("test.yml", FileStorage::WRITE);
Mat cameraMatrix = (Mat_<double>(3,3) << 1000, 0, 320, 0, 1000, 240, 0, 0, 1);
fs << "cameraMatrix" << cameraMatrix;
...
fs.release();
Read
FileStorage fs("test.yml", FileStorage::READ);
Mat cameraMatrixFromFile;
fs["cameraMatrix"] >> cameraMatrixFromFile;
...
fs.release();
Hope that helps!

Related

OpenCV convexityDefects drawing

Hi. I have the above image and use the "findContours" function.
And then I use the "convexity defects" functions to find the corner points.
The result is as follows.
The problem with this code is that it can not find the rounded corners.You can not find a point like the following.
This is my code
#include "opencv2/imgcodecs.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/videoio.hpp"
#include <opencv2/highgui.hpp>
#include <opencv2/video.hpp>
#include <iostream>
#include <sstream>
#include <fstream>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
cv::Mat image = cv::imread("find_Contours.png");
//Prepare the image for findContours
cv::cvtColor(image, image, CV_BGR2GRAY);
cv::threshold(image, image, 128, 255, CV_THRESH_BINARY);
//Find the contours. Use the contourOutput Mat so the original image doesn't get overwritten
std::vector<std::vector<cv::Point> > contours;
cv::Mat contourOutput = image.clone();
cv::findContours(contourOutput, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
////convexityDefects
vector<vector<Point> >hull(contours.size());
vector<vector<int> > hullsI(contours.size()); // Indices to contour points
vector<vector<Vec4i>> defects(contours.size());
for (int i = 0; i < contours.size(); i++)
{
convexHull(contours[i], hull[i], false);
convexHull(contours[i], hullsI[i], false);
if (hullsI[i].size() > 3) // You need more than 3 indices
{
convexityDefects(contours[i], hullsI[i], defects[i]);
}
}
///// Draw convexityDefects
for (int i = 0; i < contours.size(); ++i)
{
for (const Vec4i& v : defects[i])
{
float depth = v[3]/256;
if (depth >= 0) // filter defects by depth, e.g more than 10
{
int startidx = v[0]; Point ptStart(contours[i][startidx]);
int endidx = v[1]; Point ptEnd(contours[i][endidx]);
int faridx = v[2]; Point ptFar(contours[i][faridx]);
circle(image, ptFar, 4, Scalar(255, 255, 255), 2);
cout << ptFar << endl;
}
}
}
//
cv::imshow("Input Image", image);
cvMoveWindow("Input Image", 0, 0);
//
waitKey(0);
}
Can someone make the code and find the red dot? please help.
now i want find "convexity defects" from inside,not outside like this image:
Someone can help me??
It is very important to use
convexHull(contours[i], hullsI[i], true);
That is, with the last argument "true" for indices. I'm almost certain this is the reason it cannot find all the defects. Before fixing this, it is not much sense try to find other bugs (if any).

how to track objects within the ROI using dlib?

I'm trying to get the stream and defining the ROI and tracking an object within ROI using dlib correlation tracker but there is a error in compilation, not found any code or explanation which can describe any solution of this error. Thanks in advance.
cvcap.cpp
#include <stdio.h>
#include <opencv2/opencv.hpp>
#include "dlib/image_processing.h"
#include "dlib/gui_widgets.h"
#include "dlib/image_io.h"
#include "dlib/dir_nav.h"
using namespace dlib;
using namespace std;
int main(int argc, char * argv[]){
CvCapture* camera = cvCaptureFromFile(argv[1]);
if (camera==NULL)
printf("camera is null\n");
else
printf("camera is not null\n");
cvNamedWindow("CvCapture");
while (cvWaitKey(1000)!=atoi("q")){
double t1 = (double)cvGetTickCount();
IplImage *img = cvQueryFrame(camera);
cvSetImageROI(img, cvRect(140, 150, 340, 150));
IplImage *img1 = cvCreateImage(cvGetSize(img), img->depth, img->nChannels);
cvCopy(img, img1, NULL);
cvResetImageROI(img);
cvShowImage("ROI",img1);
correlation_tracker tracker;
tracker.start_track(img1, centered_rect(point(120,100), 80, 150));
image_window win;
tracker.update(img1);
win.set_image(img1);
win.clear_overlay();
win.add_overlay(tracker.get_position());
cout << "hit enter to process next frame" << endl;
cin.get();
double t2=(double)cvGetTickCount();
printf("time: %gms fps: %.2g\n",(t2-t1)/(cvGetTickFrequency()*1000.), 1000./((t2-t1)/(cvGetTickFrequency()*1000.)));
cvShowImage("CvCapture",img1);
}
cvReleaseCapture(&camera);
}
the error is :
In file included from dlib/image_processing.h:24:0,
from cvcap.cpp:3:
dlib/image_processing/correlation_tracker.h: In instantiation of ‘dlib::point_transform_affine dlib::correlation_tracker::make_chip(const image_type&,
dlib::drectangle, std::vector<dlib::matrix<std::complex<double> > >&) const [with image_type = _IplImage*]’:
dlib/image_processing/correlation_tracker.h:65:47: required from ‘void dlib::correlation_tracker::start_track(const image_type&, const dlib::drectang
le&) [with image_type = _IplImage*]’
cvcap.cpp:36:70: required from here
dlib/image_processing/correlation_tracker.h:301:67: error: invalid use of incomplete type ‘struct dlib::image_traits<_IplImage*>’
typedef typename image_traits<image_type>::pixel_type pixel_type;
Update
i edited my code and now it is compiling but when i'm running my code, tracking box appears but it is not tracking the objects.
for(;;) {
if(!vcap.read(image)) {
std::cout << "No frame" << std::endl;
break;
} else {
std::cout << "Starting" << std::endl;
array2d<rgb_pixel> img;
assign_image(img, cv_image<rgb_pixel>(image));
tracker.start_track(img, centered_rect(point(413,260), 98, 126));
for (unsigned long i = 0; i < img.size(); i++) {
tracker.update(img);
win.set_image(img);
win.clear_overlay();
win.add_overlay(tracker.get_position());
}
}
}
You're passing an IplImage to the dlib routine. But if you look at the docs it says you have to convert your opencv images to cv_images before passing them to dlib functions. And you can see this with the error pointing out IplImage doesn't have a pixel_type trait. A fix would be.
IplImage *img1 = cvCreateImage(cvGetSize(img), img->depth, img->nChannels);
...
correlation_tracker tracker;
// Not sure if the tracker wants a single channel image
// change rgb_alpha_pixel to uchar in that case.
tracker.start_track(dlib::cv_image<dlib::rgb_alpha_pixel>(img1), centered_rect(point(120,100), 80, 150));
Pixel types and the Correlation tracker
EDIT: Passed your stuff to opencv 3 and this is compiling for me. Do you really need to use opencv 2?
#include <stdio.h>
#include <opencv2/opencv.hpp>
#include "dlib/image_processing.h"
#include "dlib/gui_widgets.h"
#include "dlib/image_io.h"
#include "dlib/dir_nav.h"
#include <dlib/opencv/cv_image.h>
using namespace cv;
using namespace dlib;
using namespace std;
int main(int argc, char * argv[]){
VideoCapture cap(0);
Mat frame;
while (cap.read(frame)) {
cvtColor(frame, frame, CV_RGB2GRAY);
cv_image<unsigned char> img(frame);
correlation_tracker tracker;
tracker.start_track(img, centered_rect(point(120,100), 80, 150));
image_window win;
tracker.update(img);
win.set_image(img);
win.clear_overlay();
win.add_overlay(tracker.get_position());
cout << "hit enter to process next frame" << endl;
cv::waitKey(0);
}
}
and with an uglier opencv 2..
#include <stdio.h>
#include <opencv2/opencv.hpp>
#include "dlib/image_processing.h"
#include "dlib/gui_widgets.h"
#include "dlib/image_io.h"
#include "dlib/dir_nav.h"
#include <dlib/opencv/cv_image.h>
using namespace cv;
using namespace dlib;
using namespace std;
int main(int argc, char * argv[]){
CvCapture* camera = cvCaptureFromFile(argv[1]);
if (camera==NULL)
printf("camera is null\n");
else
printf("camera is not null\n");
cvNamedWindow("CvCapture");
while (cvWaitKey(1000)!=atoi("q")) {
double t1 = (double)cvGetTickCount();
IplImage *img = cvQueryFrame(camera);
cvSetImageROI(img, cvRect(140, 150, 340, 150));
IplImage *img1 = cvCreateImage(cvGetSize(img), img->depth, img->nChannels);
cvCopy(img, img1, NULL);
cvResetImageROI(img);
cvShowImage("ROI",img1);
cvCvtColor(img1, img1, CV_RGB2GRAY);
cv_image<unsigned char> img2(img1);
correlation_tracker tracker;
tracker.start_track(img2, centered_rect(point(120,100), 80, 150));
image_window win;
tracker.update(img2);
win.set_image(img2);
win.clear_overlay();
win.add_overlay(tracker.get_position());
cout << "hit enter to process next frame" << endl;
cin.get();
double t2=(double)cvGetTickCount();
printf("time: %gms fps: %.2g\n",(t2-t1)/(cvGetTickFrequency()*1000.), 1000./((t2-t1)/(cvGetTickFrequency()*1000.)));
cvShowImage("CvCapture",img1);
}
cvReleaseCapture(&camera);
}
As you see the error came exactly from what I told you before.

What is the data type of the Output matrix in the buildCostMatrix function?

I am passing a Mat container in the function. But I am unaware of what will be the output. How shall I display the output? Because when I am displaying it as an image, it is showing a blank matrix. Please provide suggestions. Thank you in advance.
This is my code
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include"opencv2/opencv.hpp"
#include"opencv2/shape.hpp"
using namespace std;
using namespace cv;
/**
* #function main
*/
int main()
{
Mat src, dst;
Mat src1,dst1;
/// Load image
src = imread("photo.jpg" );
src1= imread("photo1.jpg");
if( !src.data )
{ return -1; }
if( !src1.data )
{ return -1; }
int bins = 256;
int histSize[] = {bins};
// Set ranges for histogram bins
float lranges[] = {0, 256};
const float* ranges[] = {lranges};
// create matrix for histogram
cv::Mat hist,hist1, out;
int channels[] = {0};double k;
int const hist_height = 256;
cv::Ptr<HistogramCostExtractor> model = createChiHistogramCostExtractor(25,0.2f);
cv::Mat3b hist_image = cv::Mat3b::zeros(hist_height, bins);
cv::calcHist(&src, 1, channels, cv::Mat(), hist, 1, histSize, ranges, true, false);
cv::calcHist(&src1, 1, channels, cv::Mat(), hist1, 1, histSize, ranges, true, false);
//double cost[256][256];
// int costrows = std::max(hist.rows,hist1.rows)+nDummies;
//out.create(costrows,costrows,CV_32F);
cout << hist_height;
model->buildCostMatrix(hist,hist1,out);
normalize(out, out, 0, 1, NORM_MINMAX, -1, Mat() );
cout << out;
cv::waitKey();
return 0;
}
The type of the cost matrix is: CV_32FC1, i.e. a single channel float matrix.
You can see that in the source code where _costMatrix is created as:
_costMatrix.create(costrows, costrows, CV_32FC1);

Image Processing Opencv

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

opencv cvblob -- render blobs other than white

I am trying to detect objects with cvblob. Somehow, my code only marks the white objects. How to mark objects of other colors, like a can of beer or a bottle of water.
Here is my code:
#include "highgui.h"
#include "cv.h"
#include "cvaux.h"
#include "iostream"
#include <stdio.h>
#include <ctype.h>
#include <cvblob.h>
using namespace cv;
using namespace std;
using namespace cvb;
int main(int argc, char** argv) {
CvTracks tracks;
cvNamedWindow("frame", CV_WINDOW_AUTOSIZE);
cvMoveWindow("frame", 50, 100);
CvCapture* capture;
IplImage* frame = 0;
capture = cvCreateCameraCapture( 0 ); //capture frames from cam on index 0: /dev/video0/
if (!capture) {
return -1;
}
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, 320);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, 240);
frame = cvQueryFrame(capture);
while(frame) {
IplImage *gray = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 1);
cvCvtColor(frame, gray, CV_BGR2GRAY);
cvThreshold(gray, gray, 150, 255, CV_THRESH_BINARY);
IplImage *labelImg=cvCreateImage(cvGetSize(gray), IPL_DEPTH_LABEL, 1);
CvBlobs blobs;
unsigned int result=cvLabel(gray, labelImg, blobs);
cvFilterByArea(blobs, 500, 1000000);
// cvRenderBlobs(labelImg, blobs, frame, frame, CV_BLOB_RENDER_BOUNDING_BOX);
cvRenderBlobs(labelImg, blobs, frame, frame, CV_BLOB_RENDER_CENTROID);
cvUpdateTracks(blobs, tracks, 200., 5);
cvRenderTracks(tracks, frame, frame, CV_TRACK_RENDER_ID|CV_TRACK_RENDER_BOUNDING_BOX);
for (CvBlobs::const_iterator it=blobs.begin(); it!=blobs.end(); ++it) {
cout << "Blob #" << it->second->label << ": Area=" << it->second->area << ", Centroid=(" << it->second->centroid.x << ", " << it->second->centroid.y << ")" << endl;
}
cvShowImage("frame", frame);
cout << "----------------------------" << endl;
frame = cvQueryFrame(capture);
char c = cvWaitKey(10);
if(c==27)
break;
}
}
Any tip is appreciated.
Milo
That's the option by default and you cannot change it if you don't change the source code in cvblob library.
If you really want to change this is so easy, you can create a copy of the same method adding a new input var like CvScalar to select output color. It's so easy.
The method cvRenderBlob will be in cvcontour.cpp.
I've been made many improvement in cvblob library and in next months I will push it to the creator.
Try adding:
"cvInRangeS(hsvframe,cvScalar(23,41,133),cvScalar(40,150,255),threshy);//for yellow"
Before Filtering the blobs. Its a range of HSV(instead of RGB) values that defines the threshold of the desire color.
Hope it helps.

Resources