I save a cv::Mat as a CSV file which works fine, but when I go to load it and convert it back into a cv::Mat something is being corrupted. When I print out the contents of the cv::Mat they are different from that of the csv file. And when I show the Mat object I get a wide white window.
cv::imwrite("cameraFrame1.jpg", frame);
outFile.open("cameraFrame1.csv");
outFile << cv::format(frame, "CSV") << std::endl;
outFile.close();
...
CvMLData mlData;
mlData.read_csv("cameraFrame1.csv");
const CvMat* tmp = mlData.get_values();
cv::Mat img(tmp, true);
tmp->CvMat::~CvMat();
std::cout << "img: " << img << std::endl;
cv::namedWindow("img");
cv::imshow("img", img);
cv::waitKey(0);
Edit:
I am not at all attached to this method, if there is a better way to save an image to CSV and then read it in as such I will gladly move to that. The point of this is to save the image as raw data, most likely in a database, which could then be opened again in matlab, python, c++ etc.
I needed to set both the image depth and channels, which is the cv::Mat type in c++, as well as the dimensions
cv::imwrite("cameraFrame1.jpg", frame);
outFile.open("cameraFrame1.csv");
outFile << cv::format(frame, "CSV") << std::endl;
outFile.close();
...
CvMLData mlData;
mlData.read_csv("cameraFrame1.csv");
const CvMat* tmp = mlData.get_values();
cv::Mat img(tmp, true);
// set the image type
img.convertTo(img, CV_8UC3);
// set the image size
cv::resize(img, img, cv::Size(320, 256));
tmp->CvMat::~CvMat();
std::cout << "img: " << img << std::endl;
cv::namedWindow("img");
cv::imshow("img", img);
cv::waitKey(0);
Related
void SceneRecognition::BowRepresentation()
{
Mat dstGray2;
//Folder path is written and file names are taken according to that.
vector <String> fileNames;
String folder("airCond/Train/*.jpg");
glob(folder, fileNames,false);
//File names are checked.
for (auto t : fileNames)
{
cout << t << endl;
}
//Object is opened.
Ptr<SiftFeatureDetector> detector;
//Gray image holder is opened.
Mat dst, dstGray;
//Detector is created.
detector = SiftFeatureDetector::create();
//Keypoint vector is created.
vector<KeyPoint> keypoints;
//Object is opened.
Mat Desp;
Ptr<SiftDescriptorExtractor> extractor;
//Extractor is created.
extractor = SiftDescriptorExtractor::create();
Mat training_descriptors(1, extractor->descriptorSize(), extractor->descriptorType());
// Image matrices are read in a loop.
for (size_t i = 0; i < fileNames.size(); i++)
{
Mat im = imread(fileNames[i]);
//Image is converted to gray.
cvtColor(im, dstGray, COLOR_BGR2GRAY);
detector->detect(dstGray, keypoints);
//Descriptors are extracted.
extractor->compute(dstGray, keypoints, Desp);
training_descriptors.push_back(Desp);
}
cout << training_descriptors.size << endl;
/*Number of clusters are chosen as 1000.*/
//TermCriteria tc(TermCriteria::MAX_ITER + TermCriteria::EPS, 10, 0.001);
//int retries = 1;
//int flags = KMEANS_PP_CENTERS;
BOWKMeansTrainer bowTrainer(100);
bowTrainer.add(training_descriptors);
//Created descriptors are added.
cout << "a" << endl;
//Vocabulary is created by k-means clustering.
Mat vocabulary = bowTrainer.cluster();
}
When I run my code I get an error as followed: OpenCV(4.5.5) Error: Iterations do not converge (kmeans: can't update cluster center (check input for huge or NaN values)) in cv::generateCentersPP, file C:\Users\LENOVO\Desktop\openncvv\opencv-4.5.5\modules\core\src\kmeans.cpp, line 147
I tried different approaches but couldn't come up with an answer. Any suggestions?
One row of an input image
One of the image size is 75*144. Should I change something when I taking the image as input ?
i'm learning CUDA and i came across a course that is helping even though the code is very old and i'm having problems running it i'm trying to understand it, so he reads images using openCV imread which gives a Mat obj i guess but the data is saved as a uchar*
cv::Mat image = cv::imread(filename.c_str(), CV_LOAD_IMAGE_COLOR);
but after i was stuck in converting uchar to uchar4 and i was reading the code from the teacher and he wrote .
cv::Mat image = cv::imread(filename.c_str(), CV_LOAD_IMAGE_COLOR);
if (image.empty()) {
std::cerr << "Couldn't open file: " << filename << std::endl;
exit(1);
}
cv::cvtColor(image, imageInputRGBA, CV_BGR2RGBA);
//allocate memory for the output
imageOutputRGBA.create(image.rows, image.cols, CV_8UC4);
//This shouldn't ever happen given the way the images are created
//at least based upon my limited understanding of OpenCV, but better to check
if (!imageInputRGBA.isContinuous() || !imageOutputRGBA.isContinuous()) {
std::cerr << "Images aren't continuous!! Exiting." << std::endl;
exit(1);
}
*h_inputImageRGBA = (uchar4 *)imageInputRGBA.ptr<unsigned char>(0);
*h_outputImageRGBA = (uchar4 *)imageOutputRGBA.ptr<unsigned char>(0);
are the two last lines the ones where he subtly converts from uchar to uchar4 ...
h_inputImageRGBA
h_outputImageRGBA
are both uchar4**
can somebody help me understand the code
here is the link to the source
function name : Preprocess
I am trying to perform some operations on an image in which i have to save an image to csv file and later load it to display .I'm working on opencv 3 in which the CvMLData doesn't seem to work as shown in this example here. I guess the functionality has changed in 3.2 version.
CvMLData mlData;
mlData.read_csv("cameraFrame1.csv");
const CvMat* tmp = mlData.get_values();
cv::Mat img(tmp, true);
// set the image type
img.convertTo(img, CV_8UC3);
// set the image size
cv::resize(img, img, cv::Size(320, 256));
tmp->CvMat::~CvMat();
std::cout << "img: " << img << std::endl;
cv::namedWindow("img");
cv::imshow("img", img);
cv::waitKey(0);
Yes, the code you have shown is for OpenCV 2, with the machine learning stuffs all being moved in OpenCV 3. It's probably worth having a read over the Transistion Guide
The code and images below show how you can write a matrix out to a csv file, read it back in, resize it and display all three matrix out to windows.
With this code:
#include <fstream>
void examplethree()
{
cv::Mat mat = imread("mypic.png");
imshow("window", mat);
ofstream outputFile("cameraSamples.csv");
outputFile << format(mat, cv::Formatter::FMT_CSV) << endl;
outputFile.close();
cv::Mat img;
cv::Ptr<cv::ml::TrainData> raw_data = cv::ml::TrainData::loadFromCSV("cameraSamples.csv", 0, -2, 0);
cv::Mat data = raw_data->getSamples();
// optional if you have a color image and not just raw data
data.convertTo(img, CV_8UC3);
img = img.reshape(3); //set number of channels
// set the image type
img.convertTo(img, CV_8UC3);
// set the image size
cv::resize(img, img, cv::Size(320, 256));
//std::cout << "img: " << img << std::endl;
cv::namedWindow("img");
cv::imshow("img", img);
cv::imshow("mat", mat);
cv::waitKey(0);
}
i'm trying to get a set of values in a binary image for inverting it.. but i'm having troubles to index the matrix, the first lines of my code are.
std::string path = "img/lena.jpg";
//Our color image
cv::Mat imageMat = cv::imread(path, CV_LOAD_IMAGE_GRAYSCALE);
if(imageMat.empty())
{
std::cerr << "ERROR: Could not read image " << argv[1] << std::endl;
return 1;
}
//Grayscale matrix
cv::Mat grayscaleMat (imageMat.size(), CV_8U);
//Convert BGR to Gray
cv::cvtColor( imageMat, grayscaleMat, CV_BGR2GRAY );
//Binary image
cv::Mat binaryMat(grayscaleMat.size(), grayscaleMat.type());
//Apply thresholding
cv::threshold(grayscaleMat, binaryMat, 100, 255, cv::THRESH_BINARY);
Now i need to work with the values in binaryMat, but i don't know how get it...
1: with opencv's c++ api, you don't need to allocate output/result Mat's. just leave them empty.
//Convert BGR to Gray
cv::Mat grayscaleMat;
cv::cvtColor( imageMat, grayscaleMat, CV_BGR2GRAY );
//Apply thresholding
cv::Mat binaryMat;
cv::threshold(grayscaleMat, binaryMat, 100, 255, cv::THRESH_BINARY);
2: now access the pixels:
uchar p = binaryMat.at<uchar>(y,x); // row,col world !
binaryMat.at<uchar>(5,5) = 17;
I am trying to save an image after I have processed it but unfortunately I am getting an exception. It is running all the lines except the imwrite command (last command on code), and it's throwing this exception:
Unhandled exception at at 0x000007FEFD0D940D in histogram.exe:
Microsoft C++ exception: cv::Exception at memory location 0x00000000001DF720.
How can I fix this error, and what is causing it?
The code I'm using:
int main(int argc, char *argv[])
{
///Loading image to IplImage
//IplImage *img=cvLoadImage(argv[1]);
IplImage *img;
img = cvLoadImage("phidza.JPG",1);
cvShowImage("Ipl",img);
///converting IplImage to cv::Mat
Mat image=cvarrToMat(img);
imshow("Mat",image);
//std::cout<<"size: " << image.size() .height<< " , "
// << image.size().width << std::endl ;
if (image.empty())
{
cout << "Image cannot be loaded..!!" << endl;
return -1;
}
cvtColor(image, image, CV_BGR2GRAY); //change the color image to grayscale image
Mat img_hist_equalized;
equalizeHist(image, img_hist_equalized); //equalize the histogram
//create windows
//namedWindow("Original Image", CV_WINDOW_AUTOSIZE);
namedWindow("output", CV_WINDOW_AUTOSIZE);
//show the image
//imshow("Original Image", image);
imshow("output", img_hist_equalized);
waitKey(0); //wait for key press
imwrite("../output.jpg", img_hist_equalized); // save image
//cvSaveImage("output.jpg", img);
destroyAllWindows(); //destroy all open windows
return 0;
}
This code segment works fine for me, finally the result image got saved.. Binaries might have got corrupted in your case, So better to rebuild the opencv library.