I have been working on head pose estimation on depth data. And I have read G Fanelli's paper-"Real Time Head Pose Estimation from Consumer Depth Cameras" "Real Time Head Pose Estimation with Random Regression Forests". I test the data and the code Fanelli published on the website(http://www.vision.ee.ethz.ch/~gfanelli/head_pose/head_forest.html). However when I run the code, there is a problem. The error information is "usage: ./head_pose_estimation config_file depth_image". I think it is about file reading but I don't how to fix it.
and the code is like this:
int main(int argc, char* argv[])
{
if( argc != 3 )
{
cout << "usage: ./head_pose_estimation config_file depth_image" << endl;
exit(-1);
}
loadConfig(argv[1]);
CRForestEstimator estimator;
if( !estimator.loadForest(g_treepath.c_str(), g_ntrees) ){
cerr << "could not read forest!" << endl;
exit(-1);
}
string depth_fname(argv[2]);
//read calibration file (should be in the same directory as the depth image!)
string cal_filename = depth_fname.substr(0,depth_fname.find_last_of("/")+1);
cal_filename += "depth.cal";
ifstream is(cal_filename.c_str());
if (!is){
cerr << "depth.cal file not found in the same folder as the depth image! " << endl;
return -1;
}
//read intrinsics only
float depth_intrinsic[9]; for(int i =0; i<9; ++i) is >> depth_intrinsic[i];
is.close();
Mat depthImg;
//read depth image (compressed!)
if (!loadDepthImageCompressed( depthImg, depth_fname.c_str() ))
return -1;
Mat img3D;
img3D.create( depthImg.rows, depthImg.cols, CV_32FC3 );
//get 3D from depth
for(int y = 0; y < img3D.rows; y++)
{
Vec3f* img3Di = img3D.ptr<Vec3f>(y);
const int16_t* depthImgi = depthImg.ptr<int16_t>(y);
for(int x = 0; x < img3D.cols; x++){
float d = (float)depthImgi[x];
if ( d < g_max_z && d > 0 ){
img3Di[x][0] = d * (float(x) - depth_intrinsic[2])/depth_intrinsic[0];
img3Di[x][1] = d * (float(y) - depth_intrinsic[5])/depth_intrinsic[4];
img3Di[x][2] = d;
}
else{
img3Di[x] = 0;
}
}
}
g_means.clear();
g_votes.clear();
g_clusters.clear();
string pose_filename(depth_fname.substr(0,depth_fname.find_last_of('_')));
pose_filename += "_pose.bin";
cv::Vec<float,POSE_SIZE> gt;
bool have_gt = false;
//try to read in the ground truth from a binary file
FILE* pFile = fopen(pose_filename.c_str(), "rb");
if(pFile){
have_gt = true;
have_gt &= ( fread( >[0], sizeof(float),POSE_SIZE, pFile) == POSE_SIZE );
fclose(pFile);
}
//do the actual estimate
estimator.estimate( img3D,
g_means,
g_clusters,
g_votes,
g_stride,
g_maxv,
g_prob_th,
g_larger_radius_ratio,
g_smaller_radius_ratio,
false,
g_th
);
cout << "Heads found : " << g_means.size() << endl;
//assuming there's only one head in the image!
if(g_means.size()>0){
cout << "Estimated: " << g_means[0][0] << " " << g_means[0][1] << " " << g_means[0][2] << " " << g_means[0][3] << " " << g_means[0][4] << " " << g_means[0][5] <<endl;
float pt2d_est[2];
float pt2d_gt[2];
if(have_gt){
cout << "Ground T.: " << gt[0] << " " << gt[1] << " " << gt[2] << " " << gt[3] << " " << gt[4] << " " << gt[5] <<endl;
cv::Vec<float,POSE_SIZE> err = (gt-g_means[0]);
//multiply(err,err,err);
for(int n=0;n<POSE_SIZE;++n)
err[n] = err[n]*err[n];
float h_err = sqrt(err[0]+err[1]+err[2]);
float a_err = sqrt(err[3]+err[4]+err[5]);
cout << "Head error : " << h_err << " mm " << endl;
cout << "Angle error : " << a_err <<" degrees " << endl;
pt2d_gt[0] = depth_intrinsic[0]*gt[0]/gt[2] + depth_intrinsic[2];
pt2d_gt[1] = depth_intrinsic[4]*gt[1]/gt[2] + depth_intrinsic[5];
}
pt2d_est[0] = depth_intrinsic[0]*g_means[0][0]/g_means[0][2] + depth_intrinsic[2];
pt2d_est[1] = depth_intrinsic[4]*g_means[0][1]/g_means[0][2] + depth_intrinsic[5];
}
return 0;
}
can anyone could tell me how to fix the problem?Thanks so much!
You should always read the readme.txt (here attached in head_pose_estimation.tgz) before testing an application:
To run the example code, type ./head_pose_estimation config.txt
data/frame_XXXX_depth.bin. The config.txt file contains all parameters
needed for the head pose estimation, e.g., the path to the forest, the
stride, and z threshold used to segment the person from the
background.
Related
I`m using a one_vs_one_trainer and one_vs_one_decision_function for classify 128D face descriptors, and i want to detect unknown face.
I`m detecting faces using OpenCV and my wrapper, then i followed the guide and computed the 128D face descriptors, that i stored in files. Next, i trained one_vs_one classifier following this tutorial. All works perfectly, but when i try to classify unknown face it returns some label.
I used code from guides, but if you want to look at my code - it is here
Is there a better way to identify faces? Maybe, its simpler to use OpenCV`s methods, or other from Dlib?
Thanks for Davis!
Here is forum thread on SourceForge.
The answer is:
Use a bunch of binary classifiers rather than one vs one. If all the binary
classifiers say they don't match then you know the person doesn't match any
of them.
And i implemented this as follows:
#include <iostream>
#include <ctime>
#include <vector>
#include <dlib/svm.h>
using namespace std;
using namespace dlib;
int main() {
typedef matrix<double, 128, 1> sample_type;
typedef histogram_intersection_kernel<sample_type> kernel_type;
typedef svm_c_trainer<kernel_type> trainer_type;
typedef decision_function<kernel_type> classifier_type;
std::vector<sample_type> samples;
std::vector<double> labels;
sample_type sample;
// Samples ->
sample = -0.104075,0.0353173,...,0.114782,-0.0360935;
samples.emplace_back(sample);
labels.emplace_back(0);
sample = -0.0842,-0.0103397,...,0.0938285,0.010045;
samples.emplace_back(sample);
labels.emplace_back(0);
sample = -0.0978358,0.0709425,...,0.052436,-0.0582029;
samples.emplace_back(sample);
labels.emplace_back(0);
sample = -0.126522,0.0319873,...,0.12045,-0.0277105;
samples.emplace_back(sample);
labels.emplace_back(0);
sample = -0.10335,-0.0261625,...,0.0600661,0.00703168,-8.67462e-05,-0.0598214,-0.104442,-0.046698,0.0553857,-0.0880691,0.0482511,0.0331484;
samples.emplace_back(sample);
labels.emplace_back(0);
sample = -0.0747794,0.0599716,...,-0.0440207,-6.45183e-05;
samples.emplace_back(sample);
labels.emplace_back(1);
sample = -0.0280804,0.0900723,...,-0.0267513,0.00824318;
samples.emplace_back(sample);
labels.emplace_back(1);
sample = -0.0721213,0.00700722,...,-0.0128318,0.100784;
samples.emplace_back(sample);
labels.emplace_back(1);
sample = -0.122747,0.0737782,0.0375799,...,0.0168201,-0.0246723;
samples.emplace_back(sample);
labels.emplace_back(1);
sample = -0.0218071,0.118063,...,-0.0735178,0.04046;
samples.emplace_back(sample);
labels.emplace_back(1);
sample = -0.0680787,0.0490121,-0.0228516,...,-0.0366242,0.0287891;
samples.emplace_back(sample);
labels.emplace_back(2);
sample = 0.00152394,0.107174,...,-0.0479925,0.0182667;
samples.emplace_back(sample);
labels.emplace_back(2);
sample = -0.0334521,0.165314,...,-0.0385227,-0.0215499;
samples.emplace_back(sample);
labels.emplace_back(2);
sample = 0.0276394,0.106774,...,-0.0496831,-0.020857;
samples.emplace_back(sample);
labels.emplace_back(2);
// <- Samples
// Unique labels ->
std::vector<double> total_labels;
for(double &label : labels) {
if(find(total_labels.begin(), total_labels.end(), label) == total_labels.end())
total_labels.emplace_back(label);
}
// <- Unique labels
// Init trainers ->
std::vector<trainer_type> trainers;
int num_trainers = total_labels.size() * (total_labels.size() - 1) / 2;
cout << "Number of trainers is " << num_trainers << endl;
for(int i = 0; i < num_trainers; i++) {
trainers.emplace_back(trainer_type());
trainers[i].set_kernel(kernel_type());
trainers[i].set_c(10);
}
// <- Init trainers
// Init classifiers ->
std::vector<pair<double, double>> classifiersLabels;
std::vector<classifier_type> classifiers;
int label1 = 0, label2 = 1;
for(trainer_type &trainer : trainers) {
std::vector<sample_type> samples4pair;
std::vector<double> labels4pair;
for(int i = 0; i < samples.size(); i++) {
if(labels[i] == total_labels[label1]) {
samples4pair.emplace_back(samples[i]);
labels4pair.emplace_back(-1);
}
if(labels[i] == total_labels[label2]) {
samples4pair.emplace_back(samples[i]);
labels4pair.emplace_back(+1);
}
}
classifiers.emplace_back(trainer.train(samples4pair, labels4pair));
classifiersLabels.emplace_back(make_pair(total_labels[label1],
total_labels[label2]));
label2++;
if(label2 == total_labels.size()) {
label1++;
label2 = label1 + 1;
}
}
// <- Init classifiers
double threshold = 0.3;
auto classify = [&](){
std::map<double, int> votes;
for(int i = 0; i < classifiers.size(); i++) {
cout << "Classifier #" << i << ":" << endl;
double prediction = classifiers[i](sample);
cout << prediction << ": ";
if(abs(prediction) < threshold) {
cout << "-1" << endl;
} else if (prediction < 0) {
votes[classifiersLabels[i].first]++;
cout << classifiersLabels[i].first << endl;
} else {
votes[classifiersLabels[i].second]++;
cout << classifiersLabels[i].second << endl;
}
}
cout << "Votes: " << endl;
for(auto &vote : votes) {
cout << vote.first << ": " << vote.second << endl;
}
auto max = std::max_element(votes.begin(), votes.end(),
[](const pair<double, int>& p1, const pair<double, int>& p2) {
return p1.second < p2.second; });
double label = votes.empty() ? -1 : max->first;
cout << "Label is " << label << endl;
};
// Test ->
cout << endl;
sample = -0.0971093, ..., 0.123482, -0.0399552;
cout << "True: 0 - " << endl;
classify();
cout << endl;
sample = -0.0548414, ..., 0.0277335, 0.0460183;
cout << "True: 1 - " << endl;
classify();
cout << endl;
sample = -0.0456186,0.0617834,...,-0.0387607,0.0366309;
cout << "True: 1 - " << endl;
classify();
cout << endl;
sample = -0.0500396, 0.0947202, ..., -0.0540899, 0.0206803;
cout << "True: 2 - " << endl;
classify();
cout << endl;
sample = -0.0702862, 0.065316, ..., -0.0279446, 0.0453012;
cout << "Unknown - " << endl;
classify();
cout << endl;
sample = -0.0789684, 0.0632067, ..., 0.0330486, 0.0117508;
cout << "Unknown - " << endl;
classify();
cout << endl;
sample = -0.0941284, 0.0542927, ..., 0.00855513, 0.00840678;
cout << "Unknown - " << endl;
classify();
// <- Test
return 0;
}
I am using Caffe for deep learning. My program is in C++.
Every iteration of forward at net_->Forward(&loss);, we pass through all layers as defined in the prototxt file and how can I visualize each layer's output in C++.
Inside net.cpp file inside Caffe library, this loop iterate to forward layer by layer.
template <typename Dtype>
Dtype Net<Dtype>::ForwardFromTo(int start, int end) {
CHECK_GE(start, 0);
CHECK_LT(end, layers_.size());
Dtype loss = 0;
for (int i = start; i <= end; ++i) {
//cout << "Forwarding " << layer_names_[i] << endl;
Dtype layer_loss = layers_[i]->Forward(bottom_vecs_[i], top_vecs_[i]);
loss += layer_loss;
if (debug_info_) { ForwardDebugInfo(i); }
}
return loss;
}
top_vecs_[i] is output of each layer and how can I visualize it?
According to Shai's suggestion, what I did is as follow inside ForwardDebugInfo().
for (int top_id = 0; top_id < top_vecs_[layer_id].size(); ++top_id) {
Blob<Dtype>& blob = *top_vecs_[layer_id][top_id];
const string& blob_name = blob_names_[top_id_vecs_[layer_id][top_id]];
string name = blob_name;
for (int i = 0; i < name.length(); ++i) {
if (name[i] == '/')
name[i] = '_';
}
string foldname = "images/"+name;
if (stat(foldname.c_str(), &st) == -1) {
mkdir(foldname.c_str(), 0700);
}
//cout<<"blob_name " << blob_name << " layer_id is " << layer_id << " blob.num() " << blob.num() << " blob.channels() " << blob.channels() << " blob.height() " << blob.height() << " blob.width() " << blob.width() << endl;
///////Plotting output of individual layer
if(blob.height()>1 && blob.width()>1){
cv::Size ss(blob.width(), blob.height());
Dtype* data = blob.mutable_cpu_data();
for(int k=0; k < blob.channels(); k++)
{
cv::Mat channel(ss, CV_32FC1, data);
stringstream s;
s << k;
cv::imwrite(foldname+"/"+s.str()+".jpg",channel*255.0);
channel.release();
data += ss.area();
}
}
// mainImg.release();
/////////////////////////////////////////
const Dtype data_abs_val_mean = blob.asum_data() / blob.count();
LOG_IF(INFO, Caffe::root_solver())
<< " [Forward] "
<< "Layer " << layer_names_[layer_id]
<< ", top blob " << blob_name
<< " data: " << data_abs_val_mean;
}
I'm trying to write a program with opencv and C++. I have an image and I am trying to get the saturation value of determined pixel which is in the (x, y) point. I use the next sentence to do it:
saturation_level = hsv_chanels[1].at<uchar>(x, y);
The thing is that the program builds OK, but when I try to run, it sometimes works fine and sometimes terminates with this error:
Segmentation fault: 11
Do someone know why this error is appearing? I read that this error appears because of the my computer memory but I don't know why it only appears sometimes.
EDIT:
This is the function I call to find the homography:
Mat ObtenHomografiaSuelo (vector <KeyPoint> keypoints1, vector <KeyPoint> keypoints2, Mat imagen1, Mat imagen2){
//*****************************************************************************
//Find homography mat
//*****************************************************************************
vector < Point2f > image_points[2];
int cont = 0;
vector<Mat> chanels_hsv1; //[0]->H, [1]->S, [2]->V
split( image1, chanels_hsv1 );
vector<Mat> chanels_hsv2;
split( image2, chanels_hsv2 );
for(vector<KeyPoint>::const_iterator it = keypoints1.begin(); it!= keypoints1.end(); ++it){
// Get the position of left keypoints
float x = (it->pt.x);
float y = (it->pt.y);
cout << "1" << endl;
float saturation_level = chanels_hsv1[1].at<uchar>(x, y);
cout << "2" << endl;
double max_level = 70.0;
cout << "3" << endl;
if ((y < camSize.height/4) && (saturatio_level < max_level) ){
cout << "1:" << endl;
waitKey (100);
cout << "y: " << y;
cout << " Saturation_Level: " << nivel_saturacion << endl;
image_points[0].push_back(Point2f(x,y));
cout << "done" << endl;
cont ++;
}
}
cont = 0;
for (vector<KeyPoint>::const_iterator it = keypoints2.begin(); it!=keypoints2.end(); ++it) {
// Get the position of left keypoints
float x = (it->pt.x);
float y = (it->pt.y);
float saturation_level = chanels_hsv2[1].at<uchar>(x, y);
double max_level = 70.0;
if ((y < (camSize.height)/4) && (saturation_level < max_level)){
cout << "2" << endl;
waitKey (100);
cout << "y: " << y;
cout << " Saturation_Level: " << nivel_saturacion << endl;
image_points[1].push_back(Point2f(x,y));
cont ++;
}
}
cout << "We are obtain: " << cont << " points to do the homography" << endl;
waitKey();
Mat H;
H = Mat::zeros(4, 4, CV_64F);
if (cont < 4) {
cout << "Few points to do the homography" << endl;
}
else{
if (image_points[0].size() > image_points[1].size()){
image_points[0].resize(image_points[1].size());
}
else if (image_points[1].size() > image_points[0].size()){
image_points[1].resize(image_points[0].size());
}
H = findHomography (image_points[0], image_points[1], CV_RANSAC, 3);
cout << "done_matrix" << endl;
}
return H;
}
Before to call the function I detect keypoints using Harris or any other detector and the image I passed to the function is a HSV_image converted by cvtColor function.
The error appears in the line that I mentioned before because in the terminal I can se:
1
Segmentation Fault: 11
I've just finished to correct the error, I think it was because I wasn't using efficiently my function. I was using two 'for' staments to cross my two vectors of keypoints detected and the errors sometimes appears at first and others at second one. I don't really know why was the error, I just change my code to do the same think more efficiently and finally it works.
I just changed this lines:
for(vector<KeyPoint>::const_iterator it = keypoints1.begin(); it!= keypoints1.end(); ++it){
// Get the position of left keypoints
float x = (it->pt.x);
float y = (it->pt.y);
cout << "1" << endl;
float saturation_level = chanels_hsv1[1].at<uchar>(x, y);
cout << "2" << endl;
double max_level = 70.0;
cout << "3" << endl;
if ((y < camSize.height/4) && (saturatio_level < max_level) ){
cout << "1:" << endl;
waitKey (100);
cout << "y: " << y;
cout << " Saturation_Level: " << nivel_saturacion << endl;
image_points[0].push_back(Point2f(x,y));
cout << "done" << endl;
cont ++;
}
cont = 0;
for (vector<KeyPoint>::const_iterator it = keypoints2.begin(); it!=keypoints2.end(); ++it) {
// Get the position of left keypoints
float x = (it->pt.x);
float y = (it->pt.y);
float saturation_level = chanels_hsv2[1].at<uchar>(x, y);
double max_level = 70.0;
if ((y < (camSize.height)/4) && (saturation_level < max_level)){
cout << "2" << endl;
waitKey (100);
cout << "y: " << y;
cout << " Saturation_Level: " << nivel_saturacion << endl;
image_points[1].push_back(Point2f(x,y));
cont ++;
}
}
by this ones:
for (int i = 0; i < good_matches.size(); i++) {
int idx1=good_matches[i].queryIdx;
int idx2=good_matches[i].trainIdx;
if (((keypoints[0][idx1].pt.y < (camSize.height/4)) && (canales_hsv1[1].at<uchar>(keypoints[0][idx1].pt.x, keypoints[0][idx1].pt.y) < nivel_maximo)) || ((keypoints[1][idx2].pt.y < (camSize.height/4)) && (canales_hsv2[1].at<uchar>(keypoints[1][idx1].pt.x, keypoints[1][idx2].pt.y) < nivel_maximo)) ) {
cout << "entro" << endl;
matched_points[0].push_back(keypoints[0][idx1].pt);
matched_points[1].push_back(keypoints[1][idx2].pt);
contador ++;
}
}
Currently I only cross the matched keypoints instead of all the keypoints, it requires less computers operations and now it works OK.
I'm writing a tictactoe application which communicates between a server and client file. Currently, my program hangs when trying to read in the players move. The client is showing successful write to the pipe but the server is not reading the information. Any help would be appreciated. Heres the offending code from both portions. Edit: I just realized the formatting got completely buggered in the copy/paste, I am sorry.
client main() :
//used to define int holder for server read in
const int MAX = 2;
//used to define buffers to transfer information
const int BUFFERS = 10;
//path of the global pipe
const string PRIMARY = "/home/mking/GPipe";
int main() {
//variables
size_t result;
srand(time(NULL) );
int s = rand() % 10000;
if (s < 1000) { s += 1000; }
cout << s << endl;
string userWrite = "/temp/" + to_string(s);
s = rand() % 10000;
if (s < 1000) { s += 1000; }
cout << s << endl;
string serverWrite = "/temp/" + to_string(s);
cout << PRIMARY << endl;
cout << "User pipe is " << userWrite << endl;
cout << "Server pipe is " << serverWrite << endl;
// send personal pipe information through global pipe to server
FILE * comms = fopen(PRIMARY.c_str(), "w");
cout << "Comms open" << endl;
result = fwrite(userWrite.c_str(), 1, userWrite.length(), comms);
if (result < userWrite.length()) { cout << endl << endl << endl << endl << endl << "write error, userfifo" << endl; }
result = fwrite(serverWrite.c_str(), 1, serverWrite.length(), comms);
if (result < userWrite.length()) { cout << endl << endl << endl << endl << endl << "write error, serverfifo" << endl; }
cout << "Comms written to" << endl;
//done with comms so close it
fclose(comms);
// for some reason sending /tmp/ caused a hang also, so i improvised
userWrite.erase(2,1);
serverWrite.erase(2,1);
// make the personal pipes
cout << userWrite << " " << serverWrite << endl;
mkfifo(userWrite.c_str(), 0777);
mkfifo(serverWrite.c_str(), 0777);
// open the personal pipes with read or write privelege
cout << "fifos made" << endl;
FILE * pwrite = fopen(userWrite.c_str(), "w");
cout << "pwrite open" << endl;
FILE * pread = fopen(serverWrite.c_str(), "r");
cout << "pread open" << endl;
// if either pipe did not get made correctly, print an error
if (pwrite == NULL ) { cout << "pwrite is wrong" << endl; }
if (pread == NULL ) { cout << "pread is wrong" << endl; }
// used to transfer information between pipes
string buffer = "/temp/0000";
string catcher = "/temp/0000";
// initialize curses functions
initscr();
noecho();
keypad(stdscr,TRUE);
cbreak();
WINDOW * screen = newwin(LINES/2, COLS/2, 0, 0);
wclear(screen);
keypad(screen,TRUE);
//wait for input before playing the game
int c = getch();
displayOpening(screen);
c = getch();
//initialize the game data types
int row = 0;
int column = 0;
vector<pair<int, int> > userMoves;
vector<pair<int,int> > serverMoves;
int charInt[MAX];
bool invalid = 0;
//until game is over or user exits
while (1) {
// update the board
displayBoard(screen,userMoves,serverMoves, row, column, invalid);
// based on user input, do stuff, supports wsad or arrow keys
switch(c = getch() ) {
// if go up, move up a row or go back to bottom if at top
case KEY_UP:
case 'w':
if (row == 0) { row = 2; }
else { row--; }
break;
// if go down, move down a row or go back to the top if at bottom
case KEY_DOWN:
case 's':
if (row == 2) { row = 0; }
else { row++; }
break;
// if go left, move left a column or go back to the far right if at far left
case KEY_LEFT:
case 'a':
if (column == 0) { column = 2; }
else { column--; }
break;
// if go right, move right a column or go back to the far left if at far right
case KEY_RIGHT:
case 'd':
if (column == 2) { column = 0; }
else { column++; }
break;
// if spacebar is pressed, enter move if valid, otherwise tell invalid and get more input
case ' ':
if (checkX(row, column, userMoves, serverMoves)) {
invalid = 0;
// no longer used function, thought maybe was the issue
//addX(row,column,userMoves,buffer);
//catch information in buffer to send to server
buffer[8] = (row + '0');
buffer[9] = (column + '0');
//cout << "buffer 0 and 1 are " << int(buffer[0]) << " " << int(buffer[1]) << endl;
// add newest move to the list of user moves
userMoves.push_back(make_pair(row,column));
// check if the game is over, send a game over message to server if so and exit/clean up pipes
if (checkValid(userMoves,serverMoves) == 0 || (userMoves.size() + serverMoves.size() == 9) ) {
youwin(screen);
buffer[8] = (3 + '0');
buffer[9] = (3 + '0');
result = fwrite(buffer.c_str(), 1, buffer.length(), pwrite);
if (result < BUFFERS) { cout << endl << endl << endl << endl << endl << "write error, usermove" << endl; }
fclose(pread);
fclose(pwrite);
unlink(userWrite.c_str());
unlink(serverWrite.c_str());
endwin();
return 0;
}
//mvwaddch(screen, 12, 1, 'k');
//wrefresh(screen);
//cout << endl << endl << endl << endl << endl << buffer << " " << buffer.length() << endl;
// write newest move to server, currently where hangs!!!!!!
result = fwrite(buffer.c_str(),1,buffer.length(),pwrite);
if (result < BUFFERS) { cout << endl << endl << endl << endl << endl << "write error, usermove" << endl; }
//cout << endl << "written successfully" << endl;
//mvwaddch(screen,12,1,'l');
//wrefresh(screen);
// read in server counter move
result = fread(&catcher[0],1,BUFFERS,pread);
if (result < BUFFERS) { cout << endl << endl << endl << endl << endl << "read error, servermove" << endl; }
// catch newest computer move
charInt[0] = (catcher[8] - '0');
charInt[1] = (catcher[9] - '0');
// if the server says it won, clean up pipes and exit
if (charInt[0] == 3 && charInt[1] == 3) {
youlose(screen);
fclose(pread);
fclose(pwrite);
unlink(userWrite.c_str());
unlink(serverWrite.c_str());
endwin();
return 0;
}
// check if the server made a valid move
if (checkX(charInt[0], charInt[1], userMoves, serverMoves)) { invalid = 1; }
//addX(charInt[0],charInt[1],serverMoves,catcher);
// add newest server move to list of server moves
serverMoves.push_back(make_pair(charInt[0],charInt[1]));
// if server has won or a draw, tell the server and clean up pipes/exit
if (checkValid(userMoves,serverMoves) == 0) {
youlose(screen);
buffer[8] = (3 + '0');
buffer[9] = (3 + '0');
result = fwrite(&buffer[0],1,BUFFERS,pwrite);
if (result < BUFFERS) { cout << endl << endl << endl << endl << endl << "write error, usermove" << endl; }
fclose(pread);
fclose(pwrite);
unlink(userWrite.c_str());
unlink(serverWrite.c_str());
endwin();
return 0;
}
}
// if the move was invalid say so
else { invalid = 1; }
break;
// if user wants to exit, tell the server and clean up/exit
case 'q':
buffer[8] = 3 + '0';
buffer[9] = 3 + '0';
result = fwrite(&buffer[0],sizeof(char),BUFFERS,pwrite);
if (result < BUFFERS) { cout << endl << endl << endl << endl << endl << "write error, usermove" << endl; }
fclose(pread);
fclose(pwrite);
unlink(userWrite.c_str());
unlink(serverWrite.c_str());
endwin();
return 0;
break;
default:
break;
}
}
return 0;
}
server main() :
const int GRID = 9;
const int MAX_G = 10;
const int MAX_L = 10;
const string PRIMARY="/home/mking/GPipe";
int main() {
// variables to hold personal pipe input
char userWrite[MAX_L];
char serverWrite[MAX_L];
// open global pipe and prepare for input
cout << PRIMARY << endl;
FILE * comms = fopen(PRIMARY.c_str(), "r");
cout << "comms open" << endl;
pid_t pid;
bool valid = 1;
int charInt[MAX_G];
char prev[] = "/temp/0000";
size_t result;
// run until forced to close
while(1) {
// get the personal pipe names
//cout << "about to read user" << endl;
result = fread(&userWrite[0], sizeof(char),MAX_L,comms);
if (result < MAX_L && result > 0) { cout << "read error, user" << endl; }
//cout << "read user" << endl;
result = fread(&serverWrite[0], sizeof(char), MAX_L,comms);
if (result < MAX_L && result > 0) { cout << "read error, server" << endl; }
//cout << "read server" << endl;
//cout << "User pipe is " << userWrite << endl;
//cout << "Server pipe is " << serverWrite << endl;
// if a new pipe was detected, fork and play against a client
if (strcmp(prev, userWrite) != 0) { pid = fork(); }
strcpy(prev, userWrite);
// if a chiled, play against a client
if (pid == 0) {
//close comms and open personal pipes
cout << "In child" << endl;
fclose(comms);
string user(userWrite);
string server(serverWrite);
// was having issues with fread earlier also, roundabout fix
user.erase(2,1);
server.erase(2,1);
// set up pipes
cout << "opened pipes " << user << " " << server << endl;
FILE * userFifo = fopen(user.c_str(), "r");
cout << "opened user pipe" << endl;
FILE * serverFifo = fopen(server.c_str(), "w");
cout << "opened server pipe" << endl;
// set up data for server to check moves
pair<int,int> move;
vector<pair<int,int> > userMoves;
vector<pair<int,int> > serverMoves;
char buffer[MAX_G] = {'/','t','e','m','p','/','0','0' };
char filler[MAX_G];
vector<bool> untaken (GRID, 1);
// while game not over
while (valid) {
// get a new move, HANGS HERE!!!!!
cout << "waiting for user move" << endl;
result = fread(&filler[0], sizeof(char), MAX_G, userFifo);
if (result < MAX_G) { cout << "read error, usermove" << endl; }
cout << "move read in" << endl;
// catch user move
charInt[0] = filler[6] - '0';
charInt[1] = filler[7] - '0';
cout << charInt[0] << " " << charInt[1] << endl;
// if user says game over, close pipes
if (charInt[0] == 3 && charInt[1] == 3) {
fclose(userFifo);
fclose(serverFifo);
exit(0);
}
// add user move to list of moves
userMoves.push_back(make_pair(charInt[0], charInt[1]));
// mark location of taken moves
untaken[(userMoves.back().first * 3 + userMoves.back().second)] = 0;
// see if game can be ended and add a server move
valid = checkX(userMoves,serverMoves, untaken);
untaken[(serverMoves.back().first * 3 + serverMoves.back().second)] = 0;
//prepare server move for writing
buffer[6] = serverMoves.back().first + '0';
buffer[7] = serverMoves.back().second + '0';
//buffer[0] = -1;
//buffer[1] = -1;
// write servermove to client
//cout << buffer[0] << " " << buffer[1] << endl;
result = fwrite(&buffer[0],sizeof(char),MAX_G,serverFifo);
if (result < MAX_G) { cout << "write error, servermove" << endl; }
}
// close pipes if game is over
fclose(userFifo);
fclose(serverFifo);
exit(0);
}
}
fclose(comms);
return 0;
}
I have writtent a small C++ console application with code::blocks that loads
an array of values from a CSV file, performs a special "inverted" random dithering on the values, and exports the result as a PBM file (a bitmap).
The density of black pixels on the final PBM picture depends on 3 independent variables: "Reflectance of the white", "Reflectance of the black", and the values of the CSV.
The reason I use a CSV file is because I don't know how I can directly load a TIFF file into my script. The values of my file "wall.csv" are produced by a python script that transforms any tiff file in a csv...
Could you please check my code and advise for a solution to load a TIFF and detect automatically the size of the image in pixels?
The variables colo and lines define the size of the image contained as ASCII data in the CSV...
And the image values are loaded in the vector <float> CSV
What library would you use to load the tiff?
Thanks!
code:
#include <deque>
#include <cmath>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <random>
#include <cstdlib>
using namespace std;
deque <float> CSV; // CSV input values, "PHOTOMETRY"
deque <float> RND; // will contain random values from 0.0 to 1.0
int colo = 0; // variables inputed
int lines = 0; // lines
float YBK = 0; // Reflectance White
float YW = 0; // Reflectance Black
float Lmax = 0; // variables to be computed
float Lmin = 10000000; // arbitrarily high value
float NBK = 0; // will contain a normalized Black value
float NW = 1; // normalized white value
float CRATIO = 0; // Black to White dynamic ratio
float LRATIO = 0; // Lowest to Highest pixel value dynamic ratio
float Z = 0; // processing variables
float X = 0;
float aBK = 0; // computed density of black at each pixel
float vRND = 0; // random value container
float IO = 0;
int main(){
cout << "please put a file named wall.csv" << endl << "in the same forler as this executable" << endl << endl;
cout << "how many:" << endl << "columns does the CSV has?" << endl;
cin >> colo;
cout << "lines does the CSV has?" << endl;
cin >> lines;
cout << "reflectance of the WHITE (CIE Y)?" << endl;
cin >> YW;
cout << "reflectance of the BLACK (CIE Y)?" << endl;
cin >> YBK;
NBK = YBK / YW; // normalized BK
CRATIO = NW / NBK; // correction Ratio
int C = lines * colo; // cells
cout << endl << " there are: " << colo << " columns";
cout << endl << " and : " << lines << " lines " ;
cout << endl << " that makes " << C << " cells " << endl;
cout << endl << " correction ratio is: " << CRATIO << endl << endl;
///_____ IMPORT THE PHOTOMETRIC DATA
cout << "...importing the photometric data" << endl;
float x = 0; // a variable that will contain a value from the file
ifstream ifs ("wall.csv");
char dummy;
for (int i = 0; i < lines; ++i){
for (int i = 0; i < colo; ++i){
ifs >> x;
if (x > Lmax) {
Lmax = x; // determines the highest pixel value
}
if (x < Lmin) {
Lmin = x; // determines the lowest pixel value
}
CSV.push_back(x);
// So the dummy won't eat digits
if (i < (colo - 1))
ifs >> dummy;
}}
ifstream ifs_close();
LRATIO = Lmax / Lmin;
cout << "...photometric data imported" << endl;
cout << endl << " maximum Luminance is: " << Lmax;
cout << endl << " minimum Luminance is: " << Lmin << endl;
cout << endl << "...luminance ratio is: " << LRATIO;
if (LRATIO > CRATIO) {
cout << endl << "...luminance ratio is: " << LRATIO;
cout << endl << "...this is too high, ending..." << '\a';
return(0);
}
cout << endl << "...luminance can be corrected :)" << endl;
///______ CREATE RANDOM VALUES BETWEEN 0 & 1
std::default_random_engine generator;
std::uniform_real_distribution <double> distribution(0.0,1.0);
for (int i=0; i<C; ++i) {
double number = distribution(generator);
RND.push_back(number);
}
cout << endl << "...random values created" << endl;
///_______ process & export to PBM
ofstream output_file("./wall.pbm");
output_file << "P1" << "\n" << colo << " " << lines << "\n"; /// PBM HEADER
cout << endl << "...file header written" << endl;
cout << endl << "...computing";
int CELLS = C; // copy the amount of cells
int LINEW = colo;
int PERCENT = 100;
while (CELLS > 0) {
while (LINEW > 0) {
Z = Lmin/CSV.front(); /// processing calculus
X = (NBK - Z)/(NBK - NW);
aBK = (1 - X);
vRND = RND.front();
if (aBK > (vRND)) {
IO = 1;
}
else {
IO = 0;
}
LINEW = LINEW - 1;
CELLS = CELLS - 1;
PERCENT = PERCENT - CELLS / C;
output_file << IO << "\n";
//cout << ERR << " "; /// fancy...
CSV.erase(CSV.begin());
RND.erase(RND.begin());
}
LINEW = colo;
}
cout << endl << "...computing done" << endl;
cout << "...file written";
output_file.close();
return(0);
}
Check out lib tiff. OpenCV just uses lib tiff as well.
http://www.libtiff.org/