Where did torch::jit::load go? - libtorch

Namespace "torch::jit" is missing member "load"
The official reference says it is there, but I can't use it.
It's not just an intelligence problem, but when I run it, it throws an error saying that there is no "jit::load".
Why?
source code
#include <torch/torch.h>
#include <iostream>
#include <Windows.h>
#include <gdiplus.h>
#include <gdipluspixelformats.h> // PixelFormat24bppRGB
#include <vector>
#include <cstdlib>
#pragma comment(lib, "gdiplus.lib")
int main()
{
Gdiplus::GdiplusStartupInput input;
ULONG_PTR token;
Gdiplus::GdiplusStartup(&token, &input, NULL);
std::vector<uint8_t> pixels;
Gdiplus::BitmapData bmpData;
LARGE_INTEGER freq, start, end;
QueryPerformanceFrequency(&freq);
std::wstring path = L"C:\\Users\\baiji\\Documents\\triggerBot\\data2\\0.jpg";
std::wstring path2 = L"D:\\screenshot\\result\\output.bmp";
auto image = Gdiplus::Bitmap::FromFile(path2.c_str());
QueryPerformanceCounter(&start);
int bWidth = image->GetWidth();
int bHeight = image->GetHeight();
std::cout << bWidth << std::endl;
std::cout << bHeight << std::endl;
auto stride = 3 * bWidth;
pixels.resize(stride * bHeight);
Gdiplus::Rect rect(0, 0, bWidth, bHeight);
image->LockBits(&rect, Gdiplus::ImageLockModeRead, PixelFormat24bppRGB, &bmpData);
for (int y = 0; y < bHeight; ++y) {
memcpy(pixels.data() + y * stride, (byte*)bmpData.Scan0 + y * bmpData.Stride, stride);
}
image->UnlockBits(&bmpData);
Gdiplus::GdiplusShutdown(token);
uint8_t buf1, buf2;
for (int i = 2;i < pixels.size(); i += 3) {
buf1 = pixels[i - 2];
buf2 = pixels[i];
pixels[i-2] = buf2;
pixels[i] = buf1;
}
std::cout << "要素数: " << pixels.size() << "\n";
torch::Tensor tsr = torch::tensor(torch::ArrayRef<uint8_t>(pixels)).to(torch::kFloat64) / 256;
torch::Tensor input = torch::reshape(tsr, { bWidth,bHeight,3 });
torch::jit::script::Module module;
module = torch::jit::load("model to path/traced_model.pt");
QueryPerformanceCounter(&end);
double time = static_cast<double>(end.QuadPart - start.QuadPart) * 1000.0 / freq.QuadPart;
std::cout << time << "ms\n";
//system("PAUSE");
return 1;
}
How can I run torch::jit::load?

Related

<random> generates same number in Windows, but not in Linux

I do not why, but in Windows (with MinGW) this code generates for 3/4 time the same pseudo-random number.
I think that is because I set badly the seed, but I can not correct it.
Thank you for your help.
Here there is the code:
#include <iostream>
#include <random>
#include <chrono>
int main()
{
double Nprove = 50.0;
double p = 0.2;
const int Ncampioni = 100; // number of samples
int cappa = 0;
double sample[Ncampioni];
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::mt19937 gen(seed);
std::binomial_distribution<> d(Nprove, 0.9);
for(cappa = 0; cappa < Ncampioni; cappa = cappa +1){
sample[cappa] = d(gen);
std::cout << cappa << "," << sample[cappa] << std::endl;
}
}

Infinite loop in random.tcc (GCC 6.1.0) (May be bug in Armadillo)

I found the C++ 11 random number generator in GCC 6.1.0 causes codes stuck in Mac OS X 10.11.5, a simple code snippet is as following:
#include <iostream>
#include <armadillo>
using namespace std;
using namespace arma;
int main(int argc, char const* argv[])
{
cout << "check 1" << endl;
cout << arma_rng::randn<double>() << endl;
cout << "check 2" << endl;
return 0;
}
I debugged this code by using lldb, and locked the suspicious part in random.tcc file of libstdc++:
/**
* Polar method due to Marsaglia.
*
* Devroye, L. Non-Uniform Random Variates Generation. Springer-Verlag,
* New York, 1986, Ch. V, Sect. 4.4.
*/
template<typename _RealType>
template<typename _UniformRandomNumberGenerator>
typename normal_distribution<_RealType>::result_type
normal_distribution<_RealType>::
operator()(_UniformRandomNumberGenerator& __urng,
const param_type& __param)
{
result_type __ret;
__detail::_Adaptor<_UniformRandomNumberGenerator, result_type>
__aurng(__urng);
if (_M_saved_available)
{
_M_saved_available = false;
__ret = _M_saved;
}
else
{
result_type __x, __y, __r2;
do
{
__x = result_type(2.0) * __aurng() - 1.0;
__y = result_type(2.0) * __aurng() - 1.0;
__r2 = __x * __x + __y * __y;
}
while (__r2 > 1.0 || __r2 == 0.0);
const result_type __mult = std::sqrt(-2 * std::log(__r2) / __r2);
_M_saved = __x * __mult;
_M_saved_available = true;
__ret = __y * __mult;
}
__ret = __ret * __param.stddev() + __param.mean();
return __ret;
}
where __aurng() always return 0, so __r2 > 1.0 || __r2 == 0.0 will never be met.
UPDATE:
I found it may be a bug in Armadillo library, since I tried the following codes which is OK:
#include <iostream>
#include <random>
using namespace std;
int main(int argc, const char *argv[])
{
mt19937_64 rng;
normal_distribution<double> dist;
cout << dist(rng) << endl;
return 0;
}

Finding incorrect implementation of JudyArray

I'm trying to give a better error report (possible bug) for this case (about judySArray give incorrect result, but I don't know which key that give incorrect result).
The code here from this folder, note on this blog. Dependencies: judySArray.h and cedar.h
// judy.cpp
#include "deps/judySArray.h"
#include <string>
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
typedef judySArray<double> MSD;
const int MAX_DATA = 12000000;
const char i2ch[] = {'0','1','2','3','4','5','6','7','8','9','a','B','c','D','e','F'};
int get_first_digit(double d) {
while(d > 10) d /= 10;
return d;
}
string to_rhex(int v) {
char hex[32];
int start = 0;
while(v>0) {
hex[start] = i2ch[v%16];
v /= 16;
++start;
}
hex[start] = 0;
return hex;
}
void add_or_inc(MSD &m, const string& key,double set, double inc, int& ctr) {
const char* cstr = key.c_str();
double it = m.find(cstr);
if(!it) {
m.insert(cstr,set);
return;
}
m.insert(cstr,it+inc);
++ctr;
}
int main() {
MSD m(64);
int dup1 = 0, dup2 = 0, dup3 = 0;
for(int z=MAX_DATA;z>0;--z) {
int val2 = MAX_DATA-z;
int val3 = MAX_DATA*2-z;
string key1 = to_string(z);
string key2 = to_string(val2);
string key3 = to_rhex(val3);
add_or_inc(m,key1,z,val2,dup1);
add_or_inc(m,key2,val2,val3,dup2);
add_or_inc(m,key3,val3,z,dup3);
}
cout << dup1 << ' ' << dup2 << ' ' << dup3 << endl;
int total = 0, verify = 0, count = 0;
for(auto &it = m.begin();m.success(); m.next()) {
total += get_first_digit(it.value);
verify += strlen((const char *) it.key);
count += 1;
}
cout << total << ' ' << verify << ' ' << count << endl;
}
other implementation (map, unordered_map, hat-trie and cedar) give correct result:
6009354 6009348 611297
36186112 159701682 23370001
but judy didn't:
6009354 6009348 611297
36186112 159701681 23370000
The problem is, which key that have incorrect result?
I've tried to build a code that insert those keys on another data structure (that is cedar), but that incorrect keys still not detected:
// judy.cpp
#include "deps/judySArray.h"
#include <string>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <vector>
using namespace std;
typedef judySArray<double> MSD;
const int MAX_DATA = 12000000;
const char i2ch[] = {'0','1','2','3','4','5','6','7','8','9','a','B','c','D','e','F'};
int get_first_digit(double d) {
while(d > 10) d /= 10;
return d;
}
string to_rhex(int v) {
char hex[32];
int start = 0;
while(v>0) {
hex[start] = i2ch[v%16];
v /= 16;
++start;
}
hex[start] = 0;
return hex;
}
void add_or_inc(MSD &m, const string& key,double set, double inc, int& ctr) {
const char* cstr = key.c_str();
double it = m.find(cstr);
if(!it) {
m.insert(cstr,set);
return;
}
m.insert(cstr,it+inc);
++ctr;
}
#include "deps/cedar.h"
class MSD2 {
public:
vector<double> data;
typedef cedar::da<int> CI;
CI da;
bool exists(const string& key,double &old) {
int idx = -1;
bool found = da.exactMatchExists(key.c_str(),key.size(),&idx);
if(found) old = data[idx];
return found;
}
void insert(const string& key,double val) {
da.update(key.c_str(),key.size(),data.size());
data.push_back(val);
}
void update(const string& key,double val) {
int idx = -1;
bool found = da.exactMatchExists(key.c_str(),key.size(),&idx);
if(found) {
data[idx] = val;
return;
}
insert(key,val);
}
};
void add_or_inc(MSD2 &m, const string& key,double set, double inc, int& ctr) {
double old;
if(!m.exists(key,old)) {
m.insert(key,set);
return;
}
m.update(key,old+inc);
++ctr;
}
int main() {
MSD m(64);
MSD2 m2;
int dup1 = 0, dup2 = 0, dup3 = 0;
int vup1 = 0, vup2 = 0, vup3 = 0;
for(int z=MAX_DATA;z>0;--z) {
int val2 = MAX_DATA-z;
int val3 = MAX_DATA*2-z;
string key1 = to_string(z);
string key2 = to_string(val2);
string key3 = to_rhex(val3);
add_or_inc(m,key1,z,val2,dup1);
add_or_inc(m,key2,val2,val3,dup2);
add_or_inc(m,key3,val3,z,dup3);
add_or_inc(m2,key1,z,val2,vup1);
add_or_inc(m2,key2,val2,val3,vup2);
add_or_inc(m2,key3,val3,z,vup3);
}
cout << dup1 << ' ' << dup2 << ' ' << dup3 << endl;
cout << vup1 << ' ' << vup2 << ' ' << vup3 << endl;
int total = 0, verify = 0, count = 0;
int xotal = 0, xerify = 0, xount = 0;
union { int i; int x; } b;
size_t from = 0, p = 0;
char key[256] = {0};
for (b.i = m2.da.begin(from, p); b.i != MSD2::CI::CEDAR_NO_PATH; b.i = m2.da.next(from, p)) {
double it2 = m2.data[b.x]; // <-- find cedar's
xotal += get_first_digit(it2);
m2.da.suffix(key,p,from);
xerify += strlen(key);
xount += 1;
double it = m.find(key); // <-- find judy's
if(it != it2) { // if value doesn't match, print:
cout << "mismatch value for " << key << " : " << it2 << " vs " << it << endl;
}
}
for(auto &it = m.begin();m.success(); m.next()) {
total += get_first_digit(it.value);
verify += strlen((const char *) it.key);
count += 1;
}
cout << total << ' ' << verify << ' ' << count << endl;
cout << xotal << ' ' << xerify << ' ' << xount << endl;
}
compile with: clang++ -std=c++11 judy-findbug.cpp (or g++ -std=c++11)
the output would be:
6009354 6009348 611297
6009354 6009348 611297
36186112 159701681 23370000 <-- judy's
36186112 159701682 23370001 <-- cedar's
cedar has one more value than judy's (that is correct), but it didn't detected by the code above..
How to find that incorrect key(s)?
The bug on the code is someone (me) uncomment the assert(value != 0).
The bug was Karl's Judy implementation should not store null values (0 value).
Solution: use Doug Baskins' Judy implementation.

How to write a video?

I'm using opencv with visual studio 2010 in Windows 7 with 32 bit OS.... While running the sample program of People detection, it shows the output video playing in a window... But I'm unable to open the output video, stored in a particular location... Kindly help me... Thankyou...
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <opencv2/core/core.hpp>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
Mat img; char _filename[1024];
HOGDescriptor hog;
hog.setSVMDetector(HOGDescriptor::getDefaultPeopleDetector());
namedWindow("people detector", 1);
CvCapture *cap=cvCaptureFromFile("E:/Phase_I_output/2.walk.avi");
img=cvQueryFrame(cap);
for(;;)
{
img=cvQueryFrame(cap);
if(img.empty())
break;
fflush(stdout);
vector<Rect> found, found_filtered;
double t = (double)getTickCount();
int can = img.channels();
hog.detectMultiScale(img, found, 0, Size(8,8), Size(32,32), 1.05, 2);
t = (double)getTickCount() - t;
printf("tdetection time = %gms\n", t*1000./cv::getTickFrequency());
size_t i, j;
for( i = 0; i < found.size(); i++ )
{
Rect r = found[i];
for( j = 0; j < found.size(); j++ )
if( j != i && (r & found[j]) == r)
break;
if( j == found.size() ) found_filtered.push_back(r);
}
for( i = 0; i < found_filtered.size(); i++ )
{
Rect r = found_filtered[i];
r.x += cvRound(r.width*0.1);
r.width = cvRound(r.width*0.8);
r.y += cvRound(r.height*0.07);
r.height = cvRound(r.height*0.8);
rectangle(img, r.tl(), r.br(), cv::Scalar(0,255,0), 3);
}
Size size2 = Size(640,480);
int codec = CV_FOURCC('M', 'J', 'P', 'G');
VideoWriter writer2("E:/Phase_I_output/video_.avi",codec,50.0,size2,true);
writer2.open("E:/Phase_I_output/video_.avi",codec,15.0,size2,true);
writer2.write(img);
imshow("people detector", img);
if(waitKey(1) == 27)
break;
}
std::cout << "Completed" << std::endl ;
waitKey();
return 0;
}
You should initialize the videowriter before the infinite loop, and release the videowriter (not necessary with the C++ API) and the videocapture once there are no more frame to grab :
Size size2 = Size(640,480);
int codec = CV_FOURCC('M', 'J', 'P', 'G');
VideoWriter writer2("E:/Phase_I_output/video_.avi",codec,50.0,size2,true);
writer2.open("E:/Phase_I_output/video_.avi",codec,50.0,size2,true);
for(;;){
//do your stuff
//write the current frame
writer2.write(img);
}
cvReleaseVideoWriter( writer2 );
cvReleaseCapture( &cap );
You should also use the C++ API of openCV. I believe every function beginning with 'cv' is part of the C API (and no longer supported). Check the openCV documentation to find the corresponding C++ function.
For example :
img=cvQueryFrame(cap);
Will become :
cap >> img;
Edit
I corrected your code to use the C++ API of openCV, and it's working fine (the people detection seems to give false positive though). Here is the code :
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <opencv2/core/core.hpp>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
Mat img;
string _filename;
_filename = "path/to/video.avi";
HOGDescriptor hog;
hog.setSVMDetector(HOGDescriptor::getDefaultPeopleDetector());
namedWindow("people detector", WND_PROP_AUTOSIZE);
VideoCapture cap = VideoCapture(_filename);
if(!cap.isOpened()){
cout<<"error opening : "<<_filename<<endl;
return 1;
}
Size size2 = Size(640,480);
int codec = static_cast<int>(cap.get(CV_CAP_PROP_FOURCC));
double fps = cap.get(CV_CAP_PROP_FPS);
VideoWriter writer2("../outputVideo_.avi",codec,fps,size2,true);
for(;;)
{
cap >> img;
if(img.empty()){
cout<<"frame n° "<<cap.get(CV_CAP_PROP_FRAME_COUNT)<<endl;
break;
}
fflush(stdout);
vector<Rect> found, found_filtered;
double t = (double)getTickCount();
int can = img.channels();
hog.detectMultiScale(img, found, 0, Size(8,8), Size(32,32), 1.05, 2);
t = (double)getTickCount() - t;
printf("tdetection time = %gms\n", t*1000./cv::getTickFrequency());
size_t i, j;
for( i = 0; i < found.size(); i++ )
{
Rect r = found[i];
for( j = 0; j < found.size(); j++ )
if( j != i && (r & found[j]) == r)
break;
if( j == found.size() ) found_filtered.push_back(r);
}
for( i = 0; i < found_filtered.size(); i++ )
{
Rect r = found_filtered[i];
r.x += cvRound(r.width*0.1);
r.width = cvRound(r.width*0.8);
r.y += cvRound(r.height*0.07);
r.height = cvRound(r.height*0.8);
rectangle(img, r.tl(), r.br(), Scalar(0,255,0), 3);
}
//writer2.write(img);
writer2 << img;
imshow("people detector", img);
if(waitKey(1) == 27)
{
break;
}
}
writer2.release();
cap.release();
cout << "Completed" << endl ;
waitKey();
destroyAllWindows();
return 0;
}

Debug Assertion Failed - MSVCP110D.dll

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
string token = "000000:::AAAA:::000011:::Hello 8:::::::D Jay!";
string * stringArray = new string[token.size()];
string interim;
int r = 0;
int arrayCounter = 0;
for(int x = 0; x < token.length(); x++)
{
if(token[x] != ':')
{
interim[r] = token[x];
r++;
}
}
for (int x = 0; x < r; x++)
{
cout << interim[x] << endl;
}
system("pause");
return 0;
}
I am new and learning, and have narrowed it down to the line:
interim[r] = token[x];
..But i don't know why it crashes. Advice? I am coding in Visual C++ VSE2012
The string interim has a size of zero. Setting interim[r] = token[x] modifies the string at location r without changing its size. With a size of zero this is undefined behavior.
interim += token[x] is probably what you want.
Example:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string token = "000000:::AAAA:::000011:::Hello 8:::::::D Jay!";
string interim;
for(int x = 0; x < token.length(); x++)
{
if(token[x] != ':')
{
interim += token[x];
}
}
cout << interim << endl;
system("pause");
return 0;
}
Output:
000000AAAA000011Hello 8D Jay!
Press any key to continue . . .

Resources