How to repeat tensor in libtorch - libtorch

I am using libtorch to inference, I have read data from txt file to vector and convert to tensor, I want to repeat a tensor three times then change it to 3D,
I tried this
std::vector<std::vector<float>> feature_data(255, std::vector<float>(221));
ifstream f_data("../data.txt"); //
if (! f_data) {
cout << "Error, file couldn't be opened" << endl;
return 1;
}
for(int i=0;i<255;i++)
{
for(int j=0;j<221;j++)
{
if ( !f_data )
{
std::cout << "read error" << std::endl;
break;
}
f_data >> feature_data[i][j];
}
}
auto data_options = torch::TensorOptions().dtype(at::kFloat);
auto feature_tensor = torch::zeros({255,221}, data_options);
for (int i = 0; i < 255; i++)
feature_tensor.slice(0, i,i+1) = torch::from_blob(feature_data[i].data(), {221},
data_options);
// begin to repeat three times
auto tensor_clone = feature_tensor.clone();
auto one_time_clone = torch::cat({feature_tensor, tensor_clone}, 0);
auto two_times_clone = torch::cat({one_time_clone, tensor_clone}, 0);
auto transformed_asr = two_times_clone.view({3, 255, 221});
it looks troublesome and I am not sure if it is right, is there an easy way?

...
for (int i = 0; i < 255; i++)
feature_tensor.slice(0, i,i+1) = torch::from_blob(feature_data[i].data(), {221},
data_options);
auto tensor_clone = feature_tensor.repeat({3, 1});
...

Related

Error when debugging sample in OPENCV Camera Calibration using OPEN CV. Assertion failed ( count >=0) cornersubpix. Opencv 3.2 with VS15

I am getting an error when using Camera_Calibration.cpp on OpenCv Tutorial (photo). i running it in release mode.
.
I got assertion fail. I debugged this project by command window with in_VID5.xml
in_VID5.xml:
<?xml version="1.0"?>
<opencv_storage>
<Settings>
<!-- Number of inner corners per a item row and column. (square, circle) -->
<BoardSize_Width>7</BoardSize_Width>
<BoardSize_Height>5</BoardSize_Height>
<!-- The size of a square in some user defined metric system (pixel, millimeter)-->
<Square_Size>30</Square_Size>
<!-- The type of input used for camera calibration. One of: CHESSBOARD CIRCLES_GRID ASYMMETRIC_CIRCLES_GRID -->
<Calibrate_Pattern>"CHESSBOARD"</Calibrate_Pattern>
<!-- The input to use for calibration.
To use an input camera -> give the ID of the camera, like "1"
To use an input video -> give the path of the input video, like "/tmp/x.avi"
To use an image list -> give the path to the XML or YAML file containing the list of the images, like "/tmp/circles_list.xml"
-->
<Input>"1"</Input>
<!-- If true (non-zero) we flip the input images around the horizontal axis.-->
<Input_FlipAroundHorizontalAxis>0</Input_FlipAroundHorizontalAxis>
<!-- Time delay between frames in case of camera. -->
<Input_Delay>100</Input_Delay>
<!-- How many frames to use, for calibration. -->
<Calibrate_NrOfFrameToUse>10</Calibrate_NrOfFrameToUse>
<!-- Consider only fy as a free parameter, the ratio fx/fy stays the same as in the input cameraMatrix.
Use or not setting. 0 - False Non-Zero - True-->
<Calibrate_FixAspectRatio> 1 </Calibrate_FixAspectRatio>
<!-- If true (non-zero) tangential distortion coefficients are set to zeros and stay zero.-->
<Calibrate_AssumeZeroTangentialDistortion>1</Calibrate_AssumeZeroTangentialDistortion>
<!-- If true (non-zero) the principal point is not changed during the global optimization.-->
<Calibrate_FixPrincipalPointAtTheCenter> 1 </Calibrate_FixPrincipalPointAtTheCenter>
<!-- The name of the output log file. -->
<Write_outputFileName>"out_camera_data.xml"</Write_outputFileName>
<!-- If true (non-zero) we write to the output file the feature points.-->
<Write_DetectedFeaturePoints>1</Write_DetectedFeaturePoints>
<!-- If true (non-zero) we write to the output file the extrinsic camera parameters.-->
<Write_extrinsicParameters>1</Write_extrinsicParameters>
<!-- If true (non-zero) we show after calibration the undistorted images.-->
<Show_UndistortedImage>1</Show_UndistortedImage>
</Settings>
</opencv_storage>
My code:
#include
#include <sstream>
#include <time.h>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace std;
void help()
{
cout << "This is a camera calibration sample." << endl
<< "Usage: calibration configurationFile" << endl
<< "Near the sample file you'll find the configuration file, which has detailed help of "
"how to edit it. It may be any OpenCV supported file format XML/YAML." << endl;
}
class Settings
{
public:
Settings() : goodInput(false) {}
enum Pattern { NOT_EXISTING, CHESSBOARD, CIRCLES_GRID, ASYMMETRIC_CIRCLES_GRID };
enum InputType { INVALID, CAMERA, VIDEO_FILE, IMAGE_LIST };
void write(FileStorage& fs) const //Write serialization for this class
{
fs << "{" << "BoardSize_Width" << boardSize.width
<< "BoardSize_Height" << boardSize.height
<< "Square_Size" << squareSize
<< "Calibrate_Pattern" << patternToUse
<< "Calibrate_NrOfFrameToUse" << nrFrames
<< "Calibrate_FixAspectRatio" << aspectRatio
<< "Calibrate_AssumeZeroTangentialDistortion" << calibZeroTangentDist
<< "Calibrate_FixPrincipalPointAtTheCenter" << calibFixPrincipalPoint
<< "Write_DetectedFeaturePoints" << bwritePoints
<< "Write_extrinsicParameters" << bwriteExtrinsics
<< "Write_outputFileName" << outputFileName
<< "Show_UndistortedImage" << showUndistorsed
<< "Input_FlipAroundHorizontalAxis" << flipVertical
<< "Input_Delay" << delay
<< "Input" << input
<< "}";
}
void read(const FileNode& node) //Read serialization for this class
{
node["BoardSize_Width"] >> boardSize.width;
node["BoardSize_Height"] >> boardSize.height;
node["Calibrate_Pattern"] >> patternToUse;
node["Square_Size"] >> squareSize;
node["Calibrate_NrOfFrameToUse"] >> nrFrames;
node["Calibrate_FixAspectRatio"] >> aspectRatio;
node["Write_DetectedFeaturePoints"] >> bwritePoints;
node["Write_extrinsicParameters"] >> bwriteExtrinsics;
node["Write_outputFileName"] >> outputFileName;
node["Calibrate_AssumeZeroTangentialDistortion"] >> calibZeroTangentDist;
node["Calibrate_FixPrincipalPointAtTheCenter"] >> calibFixPrincipalPoint;
node["Input_FlipAroundHorizontalAxis"] >> flipVertical;
node["Show_UndistortedImage"] >> showUndistorsed;
node["Input"] >> input;
node["Input_Delay"] >> delay;
interprate();
}
void interprate()
{
goodInput = true;
if (boardSize.width <= 0 || boardSize.height <= 0)
{
cerr << "Invalid Board size: " << boardSize.width << " " << boardSize.height << endl;
goodInput = false;
}
if (squareSize <= 10e-6)
{
cerr << "Invalid square size " << squareSize << endl;
goodInput = false;
}
if (nrFrames <= 0)
{
cerr << "Invalid number of frames " << nrFrames << endl;
goodInput = false;
}
if (input.empty()) // Check for valid input
inputType = INVALID;
else
{
if (input[0] >= '0' && input[0] <= '9')
{
stringstream ss(input);
ss >> cameraID;
inputType = CAMERA;
}
else
{
if (readStringList(input, imageList))
{
inputType = IMAGE_LIST;
nrFrames = (nrFrames < imageList.size()) ? nrFrames : imageList.size();
}
else
inputType = VIDEO_FILE;
}
if (inputType == CAMERA)
inputCapture.open(cameraID);
if (inputType == VIDEO_FILE)
inputCapture.open(input);
if (inputType != IMAGE_LIST && !inputCapture.isOpened())
inputType = INVALID;
}
if (inputType == INVALID)
{
cerr << " Inexistent input: " << input;
goodInput = false;
}
flag = 0;
if (calibFixPrincipalPoint) flag |= CV_CALIB_FIX_PRINCIPAL_POINT;
if (calibZeroTangentDist) flag |= CV_CALIB_ZERO_TANGENT_DIST;
if (aspectRatio) flag |= CV_CALIB_FIX_ASPECT_RATIO;
calibrationPattern = NOT_EXISTING;
if (!patternToUse.compare("CHESSBOARD")) calibrationPattern = CHESSBOARD;
if (!patternToUse.compare("CIRCLES_GRID")) calibrationPattern = CIRCLES_GRID;
if (!patternToUse.compare("ASYMMETRIC_CIRCLES_GRID")) calibrationPattern = ASYMMETRIC_CIRCLES_GRID;
if (calibrationPattern == NOT_EXISTING)
{
cerr << " Inexistent camera calibration mode: " << patternToUse << endl;
goodInput = false;
}
atImageList = 0;
}
Mat nextImage()
{
Mat result;
if (inputCapture.isOpened())
{
Mat view0;
inputCapture >> view0;
view0.copyTo(result);
}
else if (atImageList < (int)imageList.size())
result = imread(imageList[atImageList++], CV_LOAD_IMAGE_COLOR);
return result;
}
static bool readStringList(const string& filename, vector<string>& l)
{
l.clear();
FileStorage fs(filename, FileStorage::READ);
if (!fs.isOpened())
return false;
FileNode n = fs.getFirstTopLevelNode();
if (n.type() != FileNode::SEQ)
return false;
FileNodeIterator it = n.begin(), it_end = n.end();
for (; it != it_end; ++it)
l.push_back((string)*it);
return true;
}
public:
Size boardSize; // The size of the board -> Number of items by width and height
Pattern calibrationPattern;// One of the Chessboard, circles, or asymmetric circle pattern
float squareSize; // The size of a square in your defined unit (point, millimeter,etc).
int nrFrames; // The number of frames to use from the input for calibration
float aspectRatio; // The aspect ratio
int delay; // In case of a video input
bool bwritePoints; // Write detected feature points
bool bwriteExtrinsics; // Write extrinsic parameters
bool calibZeroTangentDist; // Assume zero tangential distortion
bool calibFixPrincipalPoint;// Fix the principal point at the center
bool flipVertical; // Flip the captured images around the horizontal axis
string outputFileName; // The name of the file where to write
bool showUndistorsed; // Show undistorted images after calibration
string input; // The input ->
int cameraID;
vector<string> imageList;
int atImageList;
VideoCapture inputCapture;
InputType inputType;
bool goodInput;
int flag;
private:
string patternToUse;
};
void write(FileStorage& fs, const std::string&, const Settings& x)
{
x.write(fs);
}
void read(const FileNode& node, Settings& x, const Settings& default_value = Settings())
{
if (node.empty())
x = default_value;
else
x.read(node);
}
enum { DETECTION = 0, CAPTURING = 1, CALIBRATED = 2 };
bool runCalibrationAndSave(Settings& s, Size imageSize, Mat& cameraMatrix, Mat& distCoeffs,
vector<vector<Point2f> > imagePoints);
int main(int argc, char* argv[])
{
help();
Settings s;
const string inputSettingsFile = argc > 1 ? argv[1] : "in_VID5.xml";
FileStorage fs(inputSettingsFile, FileStorage::READ); // Read the settings
if (!fs.isOpened())
{
cout << "Could not open the configuration file: \"" << inputSettingsFile << "\"" << endl;
return -1;
}
fs["Settings"] >> s;
fs.release(); // close Settings file
if (!s.goodInput)
{
cout << "Invalid input detected. Application stopping. " << endl;
return -1;
}
vector<vector<Point2f> > imagePoints;
Mat cameraMatrix, distCoeffs;
Size imageSize;
int mode = s.inputType == Settings::IMAGE_LIST ? CAPTURING : DETECTION;
clock_t prevTimestamp = 0;
const Scalar RED(0, 0, 255), GREEN(0, 255, 0);
const char ESC_KEY = 27;
for (int i = 0;; ++i)
{
Mat view;
bool blinkOutput = false;
view = s.nextImage();
//----- If no more image, or got enough, then stop calibration and show result -------------
if (mode == CAPTURING && imagePoints.size() >= (unsigned)s.nrFrames)
{
if (runCalibrationAndSave(s, imageSize, cameraMatrix, distCoeffs, imagePoints))
mode = CALIBRATED;
else
mode = DETECTION;
}
if (view.empty()) // If no more images then run calibration, save and stop loop.
{
if (imagePoints.size() > 0)
runCalibrationAndSave(s, imageSize, cameraMatrix, distCoeffs, imagePoints);
break;
}
imageSize = view.size(); // Format input image.
if (s.flipVertical) flip(view, view, 0);
vector<Point2f> pointBuf;
bool found;
switch (s.calibrationPattern) // Find feature points on the input format
{
case Settings::CHESSBOARD:
found = findChessboardCorners(view, s.boardSize, pointBuf,
CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_FAST_CHECK | CV_CALIB_CB_NORMALIZE_IMAGE);
break;
case Settings::CIRCLES_GRID:
found = findCirclesGrid(view, s.boardSize, pointBuf);
break;
case Settings::ASYMMETRIC_CIRCLES_GRID:
found = findCirclesGrid(view, s.boardSize, pointBuf, CALIB_CB_ASYMMETRIC_GRID);
break;
}
if (found) // If done with success,
{
// improve the found corners' coordinate accuracy for chessboard
if (s.calibrationPattern == Settings::CHESSBOARD)
{
Mat viewGray;
cvtColor(view, viewGray, CV_BGR2GRAY);
cornerSubPix(viewGray, pointBuf, Size(11, 11),
Size(-1, -1), TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.1));
}
if (mode == CAPTURING && // For camera only take new samples after delay time
(!s.inputCapture.isOpened() || clock() - prevTimestamp > s.delay*1e-3*CLOCKS_PER_SEC))
{
imagePoints.push_back(pointBuf);
prevTimestamp = clock();
blinkOutput = s.inputCapture.isOpened();
}
// Draw the corners.
drawChessboardCorners(view, s.boardSize, Mat(pointBuf), found);
}
//----------------------------- Output Text ------------------------------------------------
string msg = (mode == CAPTURING) ? "100/100" :
mode == CALIBRATED ? "Calibrated" : "Press 'g' to start";
int baseLine = 0;
Size textSize = getTextSize(msg, 1, 1, 1, &baseLine);
Point textOrigin(view.cols - 2 * textSize.width - 10, view.rows - 2 * baseLine - 10);
if (mode == CAPTURING)
{
if (s.showUndistorsed)
msg = format("%d/%d Undist", (int)imagePoints.size(), s.nrFrames);
else
msg = format("%d/%d", (int)imagePoints.size(), s.nrFrames);
}
putText(view, msg, textOrigin, 1, 1, mode == CALIBRATED ? GREEN : RED);
if (blinkOutput)
bitwise_not(view, view);
//------------------------- Video capture output undistorted ------------------------------
if (mode == CALIBRATED && s.showUndistorsed)
{
Mat temp = view.clone();
undistort(temp, view, cameraMatrix, distCoeffs);
}
//------------------------------ Show image and check for input commands -------------------
imshow("Image View", view);
char key = waitKey(s.inputCapture.isOpened() ? 50 : s.delay);
if (key == ESC_KEY)
break;
if (key == 'u' && mode == CALIBRATED)
s.showUndistorsed = !s.showUndistorsed;
if (s.inputCapture.isOpened() && key == 'g')
{
mode = CAPTURING;
imagePoints.clear();
}
}
// -----------------------Show the undistorted image for the image list ------------------------
if (s.inputType == Settings::IMAGE_LIST && s.showUndistorsed)
{
Mat view, rview, map1, map2;
initUndistortRectifyMap(cameraMatrix, distCoeffs, Mat(),
getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0),
imageSize, CV_16SC2, map1, map2);
for (int i = 0; i < (int)s.imageList.size(); i++)
{
view = imread(s.imageList[i], 1);
if (view.empty())
continue;
remap(view, rview, map1, map2, INTER_LINEAR);
imshow("Image View", rview);
char c = waitKey();
if (c == ESC_KEY || c == 'q' || c == 'Q')
break;
}
}
return 0;
}
double computeReprojectionErrors(const vector<vector<Point3f> >& objectPoints,
const vector<vector<Point2f> >& imagePoints,
const vector<Mat>& rvecs, const vector<Mat>& tvecs,
const Mat& cameraMatrix, const Mat& distCoeffs,
vector<float>& perViewErrors)
{
vector<Point2f> imagePoints2;
int i, totalPoints = 0;
double totalErr = 0, err;
perViewErrors.resize(objectPoints.size());
for (i = 0; i < (int)objectPoints.size(); ++i)
{
projectPoints(Mat(objectPoints[i]), rvecs[i], tvecs[i], cameraMatrix,
distCoeffs, imagePoints2);
err = norm(Mat(imagePoints[i]), Mat(imagePoints2), CV_L2);
int n = (int)objectPoints[i].size();
perViewErrors[i] = (float)std::sqrt(err*err / n);
totalErr += err*err;
totalPoints += n;
}
return std::sqrt(totalErr / totalPoints);
}
void calcBoardCornerPositions(Size boardSize, float squareSize, vector<Point3f>& corners,
Settings::Pattern patternType /*= Settings::CHESSBOARD*/)
{
corners.clear();
switch (patternType)
{
case Settings::CHESSBOARD:
case Settings::CIRCLES_GRID:
for (int i = 0; i < boardSize.height; ++i)
for (int j = 0; j < boardSize.width; ++j)
corners.push_back(Point3f(float(j*squareSize), float(i*squareSize), 0));
break;
case Settings::ASYMMETRIC_CIRCLES_GRID:
for (int i = 0; i < boardSize.height; i++)
for (int j = 0; j < boardSize.width; j++)
corners.push_back(Point3f(float((2 * j + i % 2)*squareSize), float(i*squareSize), 0));
break;
}
}
bool runCalibration(Settings& s, Size& imageSize, Mat& cameraMatrix, Mat& distCoeffs,
vector<vector<Point2f> > imagePoints, vector<Mat>& rvecs, vector<Mat>& tvecs,
vector<float>& reprojErrs, double& totalAvgErr)
{
cameraMatrix = Mat::eye(3, 3, CV_64F);
if (s.flag & CV_CALIB_FIX_ASPECT_RATIO)
cameraMatrix.at<double>(0, 0) = 1.0;
distCoeffs = Mat::zeros(8, 1, CV_64F);
vector<vector<Point3f> > objectPoints(1);
calcBoardCornerPositions(s.boardSize, s.squareSize, objectPoints[0], s.calibrationPattern);
objectPoints.resize(imagePoints.size(), objectPoints[0]);
//Find intrinsic and extrinsic camera parameters
double rms = calibrateCamera(objectPoints, imagePoints, imageSize, cameraMatrix,
distCoeffs, rvecs, tvecs, s.flag | CV_CALIB_FIX_K4 | CV_CALIB_FIX_K5);
cout << "Re-projection error reported by calibrateCamera: " << rms << endl;
bool ok = checkRange(cameraMatrix) && checkRange(distCoeffs);
totalAvgErr = computeReprojectionErrors(objectPoints, imagePoints,
rvecs, tvecs, cameraMatrix, distCoeffs, reprojErrs);
return ok;
}
// Print camera parameters to the output file
void saveCameraParams(Settings& s, Size& imageSize, Mat& cameraMatrix, Mat& distCoeffs,
const vector<Mat>& rvecs, const vector<Mat>& tvecs,
const vector<float>& reprojErrs, const vector<vector<Point2f> >& imagePoints,
double totalAvgErr)
{
FileStorage fs(s.outputFileName, FileStorage::WRITE);
time_t t;
time(&t);
struct tm *t2 = localtime(&t);
char buf[1024];
strftime(buf, sizeof(buf) - 1, "%c", t2);
fs << "calibration_Time" << buf;
if (!rvecs.empty() || !reprojErrs.empty())
fs << "nrOfFrames" << (int)std::max(rvecs.size(), reprojErrs.size());
fs << "image_Width" << imageSize.width;
fs << "image_Height" << imageSize.height;
fs << "board_Width" << s.boardSize.width;
fs << "board_Height" << s.boardSize.height;
fs << "square_Size" << s.squareSize;
if (s.flag & CV_CALIB_FIX_ASPECT_RATIO)
fs << "FixAspectRatio" << s.aspectRatio;
if (s.flag)
{
sprintf(buf, "flags: %s%s%s%s",
s.flag & CV_CALIB_USE_INTRINSIC_GUESS ? " +use_intrinsic_guess" : "",
s.flag & CV_CALIB_FIX_ASPECT_RATIO ? " +fix_aspectRatio" : "",
s.flag & CV_CALIB_FIX_PRINCIPAL_POINT ? " +fix_principal_point" : "",
s.flag & CV_CALIB_ZERO_TANGENT_DIST ? " +zero_tangent_dist" : "");
cvWriteComment(*fs, buf, 0);
}
fs << "flagValue" << s.flag;
fs << "Camera_Matrix" << cameraMatrix;
fs << "Distortion_Coefficients" << distCoeffs;
fs << "Avg_Reprojection_Error" << totalAvgErr;
if (!reprojErrs.empty())
fs << "Per_View_Reprojection_Errors" << Mat(reprojErrs);
if (!rvecs.empty() && !tvecs.empty())
{
CV_Assert(rvecs[0].type() == tvecs[0].type());
Mat bigmat((int)rvecs.size(), 6, rvecs[0].type());
for (int i = 0; i < (int)rvecs.size(); i++)
{
Mat r = bigmat(Range(i, i + 1), Range(0, 3));
Mat t = bigmat(Range(i, i + 1), Range(3, 6));
CV_Assert(rvecs[i].rows == 3 && rvecs[i].cols == 1);
CV_Assert(tvecs[i].rows == 3 && tvecs[i].cols == 1);
//*.t() is MatExpr (not Mat) so we can use assignment operator
r = rvecs[i].t();
t = tvecs[i].t();
}
cvWriteComment(*fs, "a set of 6-tuples (rotation vector + translation vector) for each view", 0);
fs << "Extrinsic_Parameters" << bigmat;
}
if (!imagePoints.empty())
{
Mat imagePtMat((int)imagePoints.size(), imagePoints[0].size(), CV_32FC2);
for (int i = 0; i < (int)imagePoints.size(); i++)
{
Mat r = imagePtMat.row(i).reshape(2, imagePtMat.cols);
Mat imgpti(imagePoints[i]);
imgpti.copyTo(r);
}
fs << "Image_points" << imagePtMat;
}
}
bool runCalibrationAndSave(Settings& s, Size imageSize, Mat& cameraMatrix, Mat& distCoeffs, vector<vector<Point2f> > imagePoints)
{
vector<Mat> rvecs, tvecs;
vector<float> reprojErrs;
double totalAvgErr = 0;
bool ok = runCalibration(s, imageSize, cameraMatrix, distCoeffs, imagePoints, rvecs, tvecs,
reprojErrs, totalAvgErr);
cout << (ok ? "Calibration succeeded" : "Calibration failed")
<< ". avg re projection error = " << totalAvgErr;
if (ok)
saveCameraParams(s, imageSize, cameraMatrix, distCoeffs, rvecs, tvecs, reprojErrs,
imagePoints, totalAvgErr);
return ok;
}

How to iterate a string using while loop in C++?

number = 100010001111111
for (int i=0; number.length(); i++) {
while number[i] == 1 {
k++;
}
}
I would like to implement a while-loop as a replacement for the for-loop as shown above.
How could I convert this to a while-loop?
Here's a solution for the problem you mentioned in your comment (Problem - 96A)
#include <iostream>
using namespace std;
int main()
{
cout << "Please enter your players situation" << endl;
std::string str;
cin >> str;
std::string::size_type i = 0;
int NumbersofAppearances = 0;
int ConsectiveNumberSequence = 7; //You can change that to whatever sequence you like
bool IsDangerous=false;
while (i < str.size())
{
if(str[i]=='1' )
{
++NumbersofAppearances;
//We need to check if we reached the consecutive number or not and save it on a different bool variable
if(NumbersofAppearances>=ConsectiveNumberSequence)
IsDangerous=true;
}
else
{
NumbersofAppearances=0;
}
++i;
}
//print out the end result
if (IsDangerous)
cout <<"YES , this is dangerous"<< endl;
else
cout <<"No, this is not dangerous"<< endl;
return 0;
}
And here's a link to Coding ground

Read the position Actor in PhysX

I have a question about PhysX SDK 2.8.1
I'm an actor:
NxActorDesc actorDesc;
NxBodyDesc bodyDesc;
NxSphereShapeDesc sphereDesc;
sphereDesc.radius = 1.5f;
actorDesc.shapes.pushBack(&sphereDesc);
actorDesc.body = &bodyDesc;
actorDesc.density = 10;
actorDesc.globalPose.t = NxVec3(0.0f, 25.0f, 0.0f);
NxActor *dynamicActor = gsc->createActor(actorDesc);
I want the console print out the current position of the actor. How to do it? This below doesn't work:
for (int i = 0; i <= 10; i++) {
//Step PhysX simulation
if (gsc)
StepPhysX();
NxMat34 pose = dynamicActor->getGlobalPose();
cout <<pose.t << endl;
}
Specifically depends on my reading the position Y.
std::cout can't take an NxVec3 (which your post.t is).
If you want to print out the global position of your dynamicActor,
you need to print out X, Y, Z components of your NxVec3 variable separately.
NxVec3 trans = dynamicActor->getGlobalPose().t; // or you could use "dynamicActor->getGlobalPosition()"
std::cout << trans.x << ", " << trans.y << ", " << trans.z << std::endl;

Is it possible to encode using the MRLE codec on Video for Windows under Windows 8?

The Problem
I have an old application that provides videos inside .avi containers using the MRLE codec. The code uses the Video for Windows API. This has worked admirably for many years, but I've just discovered that my code does not behave correctly on Windows 8.
On Windows 8, the program creates a .avi file but when it is viewed in, for instance, Windows Media Player, the video plays for the correct duration but the first frame is shown the whole time.
I've made an SSCCE to demonstrate the problem:
#include <Windows.h>
#include <vfw.h>
#include <cstdlib>
#include <iostream>
#pragma comment(lib, "vfw32.lib")
int main()
{
RECT frame = { 0, 0, 120, 100 };
AVIFileInit();
IAVIFile *pFile;
if (AVIFileOpenA(&pFile, "out.avi", OF_CREATE | OF_WRITE, NULL) != 0)
{
std::cout << "AVIFileOpen failed" << std::endl;
return 1;
}
AVISTREAMINFO si = { 0 };
si.fccType = streamtypeVIDEO;
si.fccHandler = mmioFOURCC('M', 'R', 'L', 'E');
si.dwScale = 1;
si.dwRate = 25;
si.dwQuality = (DWORD)-1;
si.rcFrame = frame;
IAVIStream *pStream;
if (AVIFileCreateStream(pFile, &pStream, &si) != 0)
{
std::cout << "AVIFileCreateStream failed" << std::endl;
return 1;
}
AVICOMPRESSOPTIONS co = { 0 };
co.fccType = si.fccType;
co.fccHandler = si.fccHandler;
co.dwQuality = si.dwQuality;
IAVIStream *pCompressedStream;
if (AVIMakeCompressedStream(&pCompressedStream, pStream, &co, NULL) != 0)
{
std::cout << "AVIMakeCompressedStream failed" << std::endl;
return 1;
}
size_t bmiSize = sizeof(BITMAPINFOHEADER) + 256*sizeof(RGBQUAD);
BITMAPINFO *bmi = (BITMAPINFO*)std::malloc(bmiSize);
ZeroMemory(bmi, bmiSize);
bmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi->bmiHeader.biWidth = si.rcFrame.right;
bmi->bmiHeader.biHeight = si.rcFrame.bottom;
bmi->bmiHeader.biPlanes = 1;
bmi->bmiHeader.biBitCount = 8;
bmi->bmiHeader.biCompression = BI_RGB;
bmi->bmiHeader.biSizeImage = bmi->bmiHeader.biWidth*bmi->bmiHeader.biHeight;
bmi->bmiHeader.biClrUsed = 256;
for (int i = 0; i < 256; i++)
{
RGBQUAD col = { i, i, i, 0 };
bmi->bmiColors[i] = col;
}
if (AVIStreamSetFormat(pCompressedStream, 0, bmi, bmiSize) != 0)
{
std::cout << "AVIStreamSetFormat failed" << std::endl;
return 1;
}
unsigned char *bits = new unsigned char[bmi->bmiHeader.biSizeImage];
for (int frame = 0; frame < 256; frame++)
{
std::memset(bits, 255-frame, bmi->bmiHeader.biSizeImage);
if (AVIStreamWrite(pCompressedStream, frame, 1, bits, bmi->bmiHeader.biSizeImage, 0, NULL, NULL) != 0)
{
std::cout << "AVIStreamWrite failed" << std::endl;
return 1;
}
}
if (AVIStreamRelease(pCompressedStream) != 0 || AVIStreamRelease(pStream) != 0)
{
std::cout << "AVIStreamRelease failed" << std::endl;
return 1;
}
if (AVIFileRelease(pFile) != 0)
{
std::cout << "AVIFileRelease failed" << std::endl;
return 1;
}
std::cout << "Succeeded" << std::endl;
return 0;
}
This creates a very simple video. A palette of gray shades is created. And each frame selects a different one of those gray shades. So the desired video transitions from white to black. This happens as expected on Win7 and earlier. But on Win8 the video just contains the first white frame.
It seems to be an issue with the .avi file generation. If I generate a file on Win8 and view on Win7 then the file does not play correctly. If I generate the file on Win7 and view on Win8 then the video displays as desired.
I know that Video for Windows is an ancient legacy API. However, the frames that I am encoding are very amenable to run-length encoding. And the MRLE codec is available by default on all versions of Windows that I support. So there are good reasons why I am reluctant to try to use one of the more modern multimedia APIs until I can be sure that Video for Windows on Win8 with MRLE is a lost cause.
The Question
Is it possible to use Video for Windows on Win8 to create MRLE encoded .avi files? If so how is it done?
It seems likely that this is indeed a bug in Windows 8. Thanks to Roman for suggesting some ideas to work around the problem. I can confirm that performing the RLE encoding manually is easy to do, and works well.
Starting from the code in the question, we need to keep it all, and replace the innards of the for loop that writes the frames. We do still need to create the compressed stream, but we no longer write to it. Instead we write RLE8 encoded data to the raw stream.
unsigned char *bits = new unsigned char[bmi->bmiHeader.biHeight*4 + 2];
for (int frame = 0; frame < 256; frame++)
{
size_t i = 0;
for (size_t y = 0; y < bmi->bmiHeader.biHeight; y++)
{
bits[i++] = bmi->bmiHeader.biWidth;
bits[i++] = 255-frame; // encoded run
bits[i++] = 0;
bits[i++] = 0; // EOL
}
bits[i++] = 0;
bits[i++] = 1; // EOB
if (AVIStreamWrite(pStream, frame, 1, bits, i, 0, NULL, NULL) != 0)
{
std::cout << "AVIStreamWrite failed" << std::endl;
return 1;
}
}
Obviously in a real application, you'd need to write a real RLE8 encoder, but this proves the point.

Why the audio recorder code can work for 8 bit, but cannot work for 16 bit??

I am trying to record the audio at windows, here is my code. it works well for 8 bit, but it cannot work for 16 bit. Can anyone help me?
#include
#include
#include
#pragma comment(lib,"winmm.lib")
using namespace std;
int test(){
HWAVEIN microHandle;
WAVEHDR waveHeader;
MMRESULT result = 0;
WAVEFORMATEX waveformat;
waveformat.wFormatTag = WAVE_FORMAT_PCM;
waveformat.wBitsPerSample=8;
waveformat.nSamplesPerSec=16000;//8000;
waveformat.nAvgBytesPerSec=waveformat.nSamplesPerSec*waveformat.nSamplesPerSec/8;
waveformat.nChannels=1;
waveformat.nBlockAlign=waveformat.nChannels*waveformat.wBitsPerSample/8;
waveformat.cbSize=0;
result = waveInOpen(&microHandle, WAVE_MAPPER, &waveformat, 0L, 0L, CALLBACK_EVENT);
if (result)
{
cout << "Fail step 1" << endl;
cout << result << endl;
Sleep(10000);
return 0;
}
const int BUFSIZE = 16000*4;
char * buf = (char *)malloc(BUFSIZE);
// Set up and prepare header for input
waveHeader.lpData = (LPSTR)buf;
waveHeader.dwBufferLength = BUFSIZE;
waveHeader.dwBytesRecorded=0;
waveHeader.dwUser = 0L;
waveHeader.dwFlags = 0L;
waveHeader.dwLoops = 0L;
waveInPrepareHeader(microHandle, &waveHeader, sizeof(WAVEHDR));
// Insert a wave input buffer
result = waveInAddBuffer(microHandle, &waveHeader, sizeof(WAVEHDR));
if (result)
{
cout << "Fail step 2" << endl;
cout << result << endl;
Sleep(10000);
return 0;
}
result = waveInStart(microHandle);
if (result)
{
cout << "Fail step 3" << endl;
cout << result << endl;
Sleep(10000);
return 0;
}
// Wait until finished recording
do {} while (waveInUnprepareHeader(microHandle, &waveHeader, sizeof(WAVEHDR))==WAVERR_STILLPLAYING);
FILE *fp = fopen("output.pcm","w");
fwrite(buf,1,BUFSIZE,fp);
fclose(fp);
waveInClose(microHandle);
return 0;
}
void main()
{
test();
}
If I set the parameter waveformat.wBitsPerSample = 8, it can record the audio correctly,
but if i set it waveformat.wBitsPerSample = 16, it record the Noise!!!
Can anyone help me?
thanks.
it should bu FILE *fp = fopen("output.pcm","wb"); NOT FILE *fp = fopen("output.pcm","w");

Resources