How do I create a database of SIFT descriptors (of images)?
My intention is to implement a supervisioned training set on Support Vector Machine.
Which kind of images do you need? If you don`t care, you can just download some public computer vision dataset like http://lear.inrialpes.fr/~jegou/data.php#holidays which offers both images and already computed SIFTs from its regions.
Or try other datasets, for instance, from http://www.cvpapers.com/datasets.html
Other possibility is just to download\make lots of photos, detect interest point and describe them with SIFTs. It can be done with OpenCV, VLFeat or other libraries.
OpenCV example.
#include <opencv2/opencv.hpp>
#include <opencv2/nonfree/nonfree.hpp>
#include <fstream>
void WriteSIFTs(std::vector<cv::KeyPoint> &keys, cv::Mat desc, std::ostream &out1)
{
for(int i=0; i < (int) keys.size(); i++)
{
out1 << keys[i].pt.x << " " << keys[i].pt.y << " " << keys[i].size << " " << keys[i].angle << " ";
//If you don`t need information about keypoints (position, size)
//you can comment out the string above
float* descPtr = desc.ptr<float>(i);
for (int j = 0; j < desc.cols; j++)
out1 << *descPtr++ << " ";
out1 << std::endl;
}
}
int main(int argc, const char* argv[])
{
const cv::Mat img1 = cv::imread("graf.png", 0); //Load as grayscale
cv::SiftFeatureDetector detector;
std::vector<cv::KeyPoint> keypoints;
detector.detect(img1, keypoints);
cv::SiftDescriptorExtractor extractor;
cv::Mat descriptors;
extractor.compute(img1, keypoints, descriptors);
std::ofstream file1("SIFTs1.txt");
if (file1.is_open())
WriteSIFTs(keypoints,descriptors,file1);
file1.close();
return 0;
}
Related
I want to use protocol buffer to send and receive the following type using gRPC
std:array<std::complex<int>, 2> bar_array;
Sources used to get idea: 1, 2
What I have done so far
My approach (Intentionally I am omitting here the unnecessary code)
proto file
syntax = "proto3";
package expcmake;
message child_data {
repeated int32 child_data_list = 1;
}
message Address {
child_data child_data_var = 8;
repeated child_data parent_data_list = 9;
}
server.cpp
Here, at first I have made a dummy std:array<std::complex<int>, 2> data. Then, I have filled the child_data_list with the std::complex<int> data. After each filling of real and imaginary part I have pushed them in the parent_data_list. Also, at this moment I have cleared the child_data_list.
Client message name is NameQuery, while Server message name is Address
In Server side both message are passed as pointer
class AddressBookService final : public expcmake::AddressBook::Service {
public:
virtual ::grpc::Status GetAddress(::grpc::ServerContext* context, const ::expcmake::NameQuery* request, ::expcmake::Address* response)
{
// omitting unnecessary lines
// populate bar_array with std::complex<int> data
std::complex<int> z4 = 1. + 2i, z5 = 1. - 2i; // conjugates
bar_array = {z4, z5};
std::cout << "bar array printing whose size: " << bar_array.size() << std::endl;
for(int i = 0; i < bar_array.size(); i++) {
std::cout << bar_array[i] << " ";
}
std::cout << std::endl;
// Use parent_data_list protocol buffer message type to fill with the content of bar_array
for (int i = 0; i < bar_array.size(); i++){
// Use child_data protocol buffer message type to fill with the content of complex int data
response->mutable_child_data_var()->add_child_data_list(real(bar_array[i]));
response->mutable_child_data_var()->add_child_data_list(imag(bar_array[i]));
// Use parent_data_list protocol buffer message type to fill with the content of child_data -> child_data_list data
response->add_parent_data_list() -> child_data_list();
// clear the child_data message. Reason to keep child_data_list new in every iteration otherwise add_child_data_list will append new data (eg: 1,2,1,-2) which is wrong. Expected is (1,2) then (1,-2)
response->mutable_child_data_var()->clear_child_data_list();
}
// This is zero which I have got. Without clearing it is 4 which is also correct I believe as per the concept of protocol buffer message type
std::cout << "response->mutable_child_data_var()->child_data_list_size(): " << response->mutable_child_data_var()->child_data_list_size() << std::endl;
// This is 2 which meets my requirement
std::cout << "response->parent_data_list_size(): " << response->parent_data_list_size() << std::endl;
// omitting unnecessary lines
}
};
client.cpp
int main(int argc, char* argv[])
{
// Setup request
expcmake::NameQuery query;
expcmake::Address result;
// printing the content of child_data -> child_data_list data array/container. There I have seen 1,2,1,-2 if I don't do the clear operation on child_data_list in server side. So, I guess it is correctly got the data
for(int i = 0; i < result.mutable_child_data_var()->child_data_list_size(); i++)
std::cout << "Child Data at index [" << i << "]: " << result.mutable_child_data_var()->child_data_list(i) << std::endl;
// This one making problem
// printing the content of parent_data_list type/container
// for(int i = 0; i < result.parent_data_list_size(); i++){
// std::cout << "Parent Data at index [" << i << "]: " << result.mutable_parent_data_list(i) << std::endl; // This give me the memory address
// Tried others to fetch the data but failed. Eg: result.parent_data_list(i) // failed
//
// }
}
Snippet from the generated pb file
// repeated int32 child_data_list = 1;
int child_data_list_size() const;
private:
int _internal_child_data_list_size() const;
public:
void clear_child_data_list();
private:
::PROTOBUF_NAMESPACE_ID::int32 _internal_child_data_list(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
_internal_child_data_list() const;
void _internal_add_child_data_list(::PROTOBUF_NAMESPACE_ID::int32 value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
_internal_mutable_child_data_list();
public:
::PROTOBUF_NAMESPACE_ID::int32 child_data_list(int index) const;
void set_child_data_list(int index, ::PROTOBUF_NAMESPACE_ID::int32 value);
void add_child_data_list(::PROTOBUF_NAMESPACE_ID::int32 value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
child_data_list() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
mutable_child_data_list();
// .expcmake.child_data child_data_var = 8;
bool has_child_data_var() const;
private:
bool _internal_has_child_data_var() const;
public:
void clear_child_data_var();
const ::expcmake::child_data& child_data_var() const;
PROTOBUF_MUST_USE_RESULT ::expcmake::child_data* release_child_data_var();
::expcmake::child_data* mutable_child_data_var();
void set_allocated_child_data_var(::expcmake::child_data* child_data_var);
private:
const ::expcmake::child_data& _internal_child_data_var() const;
::expcmake::child_data* _internal_mutable_child_data_var();
public:
void unsafe_arena_set_allocated_child_data_var(
::expcmake::child_data* child_data_var);
::expcmake::child_data* unsafe_arena_release_child_data_var();
// repeated .expcmake.child_data parent_data_list = 9;
int parent_data_list_size() const;
private:
int _internal_parent_data_list_size() const;
public:
void clear_parent_data_list();
::expcmake::child_data* mutable_parent_data_list(int index);
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::expcmake::child_data >*
mutable_parent_data_list();
private:
const ::expcmake::child_data& _internal_parent_data_list(int index) const;
::expcmake::child_data* _internal_add_parent_data_list();
public:
const ::expcmake::child_data& parent_data_list(int index) const;
::expcmake::child_data* add_parent_data_list();
const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::expcmake::child_data >&
parent_data_list() const;
I guess
Is the filling of the message field is incorrectly done !! Though the size is not saying that
I am not catching the protobuf syntax(which is generated in the pb file) in right way to fetch the data
Need suggestions(helpful if can provide the syntax too).
The mutable_* prefixed APIs are for mutating (modifying/adding) elements and they return a pointer. The mutable_* and set_* APIs should only be used while filling the data. Once data is filled, you should not be using mutable_* APIs to check sizes. After receiving the response from the server, the client will most probably be consuming it, not mutating. You need to update the client-side accordingly.
Also, you can use a range-based for loop to iterate over child_data_list of child_data_var like this:
const auto child_data_list = result.child_data_var().child_data_list();
for (const auto element : child_data_list)
{
// process element
}
Apart from that, you're using std::array (a fixed-size array) i.e. std:array<std::complex<int>, 2>, alternatively here's another way to model this without repeated which does not represent a fixed-size array.
complex.proto
syntax = "proto3";
package pb;
message Complex {
int32 real = 1;
int32 imag = 2;
}
message Compound {
Complex c1 = 1;
Complex c2 = 2;
}
The message Complex emulates an std::complex type and Compound an std::array with only 2 elements c1 and c2.
With this, you can easily convert the protobuf message to std::complex and vice versa. Once converted to std::complex, you can perform its supported operations as needed.
Compile complex.proto:
protoc --cpp_out=. ./complex.proto
For the C++ API, look for the accessors in the generated complex.pb.h file under public. The official doc Protocol Buffer Basics: C++ also lists the C++ API examples under The Protocol Buffer API section.
Here's a complete C++ example with the above complex.proto:
main.cpp
#include <iostream>
#include <complex>
#include <array>
#include <cstdlib>
#include "complex.pb.h"
namespace my {
using complex = std::complex<int>;
using compound = std::array<std::complex<int>, 2>;
}
int main()
{
const auto my_c1 = my::complex{ 1, 2 };
const auto my_c2 = my::complex{ 2, 4 };
const auto my_compound_1 = my::compound{ my_c1, my_c2 };
std::cout << "my_compound_1 [size: " << my_compound_1.size() << "]\n";
std::cout << "my_c1: " << my_c1 << '\n';
std::cout << "my_c2: " << my_c2 << '\n';
pb::Compound pb_compound;
pb_compound.mutable_c1()->set_real(my_compound_1[0].real());
pb_compound.mutable_c1()->set_imag(my_compound_1[0].imag());
pb_compound.mutable_c2()->set_real(my_compound_1[1].real());
pb_compound.mutable_c2()->set_imag(my_compound_1[1].imag());
std::cout << "\npb_compound:\n";
pb_compound.PrintDebugString();
const auto serialized_compound = pb_compound.SerializeAsString();
// send
// receive
pb::Compound deserialized_compound;
if (!deserialized_compound.ParseFromString(serialized_compound))
{
std::cerr << "[ERROR] Parsing failed!\n";
return EXIT_FAILURE;
}
std::cout << "\n\npb_compound (deserialized):\n";
deserialized_compound.PrintDebugString();
const auto pb_c1 = deserialized_compound.c1();
const auto pb_c2 = deserialized_compound.c2();
const auto my_c3 = my::complex{ pb_c1.real(), pb_c1.imag() };
const auto my_c4 = my::complex{ pb_c2.real(), pb_c2.imag() };
const auto my_compound_2 = my::compound{ my_c3, my_c4 };
std::cout << "my_compound_2 [size: " << my_compound_2.size() << "]\n";
std::cout << "my_c3: " << my_c3 << '\n';
std::cout << "my_c4: " << my_c4 << '\n';
const auto sum = my_c3 + my_c4;
std::cout << "sum: " << sum << '\n';
return EXIT_SUCCESS;
}
Compile with g++:
g++ main.cpp complex.pb.cc -o pb_complex `pkg-config --cflags --libs protobuf`
Run:
$ ./pb_complex
my_compound_1 [size: 2]
my_c1: (1,2)
my_c2: (2,4)
pb_compound:
c1 {
real: 1
imag: 2
}
c2 {
real: 2
imag: 4
}
pb_compound (deserialized):
c1 {
real: 1
imag: 2
}
c2 {
real: 2
imag: 4
}
my_compound_2 [size: 2]
my_c3: (1,2)
my_c4: (2,4)
sum: (3,6)
The way I was accessing the filed parent_data_list was wrong. I am posting the approach which has solved the issue.
A little change in proto file
syntax = "proto3";
package expcmake;
message child_data {
repeated int32 child_data_list = 1 [packed=true];
}
message Address {
repeated child_data parent_data_list = 1;
}
Reason to use packed see this
server.cpp
class AddressBookService final : public expcmake::AddressBook::Service {
public:
virtual ::grpc::Status GetAddress(::grpc::ServerContext* context, const ::expcmake::NameQuery* request, ::expcmake::Address* response){
// omitting unnecessary lines
// populate bar_array with std::complex<int> data
std::complex<int> z4 = 1. + 2i, z5 = 1. - 2i; // conjugates
bar_array = {z4, z5};
// Now goal is to pass this bar_array as a protobuf message
// Use parent_data_list protocol buffer message type to fill with the content of bar_array
for (int i = 0; i < bar_array.size(); i++){
// make a 2D array. Eg: std::array<std::complex<int>>. In each iteration, new sub_content will be added (here sub_content means child_data_list)
response->add_parent_data_list() -> child_data_list();
// Followings are filling the child_data_list with the required data(Real and Imag part of the complex data which is already generated)
response->mutable_parent_data_list(i)->add_child_data_list(real(bar_array[i]));
response->mutable_parent_data_list(i)->add_child_data_list(imag(bar_array[i]));
}
}
return grpc::Status::OK;
};
After the completion of the iteration, A 2D type of message will be generated which is parent_data_list = [[child_data_list], [child_data_list]]. Don't consider it as a real scenario. Just for presentation I am using it.
client.cpp
std::cout <<"Using Mutable" << std::endl;
for(int i = 0; i < result.parent_data_list_size(); i++){
for(int j = 0 ; j<result.mutable_parent_data_list(i)->child_data_list_size(); j++){
std::cout << "Value [" << i << "][" << j << "]: " << result.mutable_parent_data_list(i)->child_data_list(j) << std::endl;
}
}
// Following is same as before. Added as I was in turmoil to understand the properties generated by protobuf. Hope could be helpful for beginners like me
std::cout <<"Without Mutable property" << std::endl;
for(int i = 0; i < result.parent_data_list_size(); i++){
for(int j = 0 ; j < result.parent_data_list(i).child_data_list_size(); j++){
std::cout << "Value [" << i << "][" << j << "]: " << result.parent_data_list(i).child_data_list(j) << std::endl;
}
}
In client side I am accessing the child_data_list with index which is not properly mimic the C++ style. Would be great if I can in one line print the value of parent_data_list[n] data. As far I have studied the generated pb.h file my understanding is that it is not possible as no return function I have not found without index for the repeated field. Or may be I am missing something important again.
I am quite fresh in coding C code, trying to use FFTW from the well-known website http://www.fftw.org/ in my Visual Studio 2019.
I followed the tutorial (https://www.youtube.com/watch?v=geYbCA137PU), but an error appeared: LNK1104 cannot open file 'libfftw3-3.lib'
How should I solve the problem? I have googled it, but looks like most of the solution not quite suitable to mine. Almost the last step! Please!
#include <iostream>
#include <fftw3.h>
using namespace std;
//macros for real and imaginary parts
#define REAL 0
#define IMAG 1
//length of complex array
#define N 8
/*Computes the 1-D fast Fourier transform*/
void fft(fftw_complex* in, fftw_complex* out)
{
// creat a DFT plan
fftw_plan plan = fftw_plan_dft_1d(N, in, out, FFTW_FORWARD, FFTW_ESTIMATE);
// execute the plan
fftw_execute(plan);
// do some cleaning
fftw_destroy_plan(plan);
fftw_cleanup();
}
/*Computes the 1-D inverse fast Fourier transform*/
void ifft(fftw_complex* in, fftw_complex* out)
{
// creat a IDFT plan
fftw_plan plan = fftw_plan_dft_1d(N, in, out, FFTW_BACKWARD, FFTW_ESTIMATE);
// execute the plan
fftw_execute(plan);
// do some cleaning
fftw_destroy_plan(plan);
fftw_cleanup();
// scale the output to obtain the exact inverse
for (int i = 0; i < N; ++i) {
out[i][REAL] /= N;
out[i][IMAG] /= N;
}
}
/*Display complex numbers in the form a +/- bi. */
void displayComplex(fftw_complex* y)
{
for (int i = 0; i < N; ++i)
if (y[i][IMAG] < 0)
cout << y[i][REAL] << " - " << abs(y[i][IMAG]) << "i" << endl;
else
cout << y[i][REAL] << " + " << y[i][IMAG] << "i" << endl;
}
/*Display real part of complex number*/
void displayReal(fftw_complex* y)
{
for (int i = 0; i < N; ++i)
cout << y[i][REAL] << endl;
}
/* Test */
int main()
{
// input array
fftw_complex x[N];
// output array
fftw_complex y[N];
// fill the first of some numbers
for (int i = 0; i < N; ++i) {
x[i][REAL] = i + 1; // i.e.{1 2 3 4 5 6 7 8}
x[i][IMAG] = 0;
}
// compute the FFT of x and store the result in y.
fft(x, y);
// display the result
cout << "FFT =" << endl;
displayComplex(y);
// compute the IFFT of x and store the result in y.
ifft(y, x);
// display the result
cout << "\nIFFT =" << endl;
displayReal(x);
}
#HAL9000 Thanks for your remind, I found out that I have converted the wrong name of .def so I generated a "libfftw3-3l.lib". That's why it couldn't open the file, it has been solved now!
#include iostream
#include cmath
#include fstream
#include cstdlib
#include string
using namespace std;
class Device {//Input and store Device Description and Serial Numbers
protected:
static string serial_number;
static string device_description;
public:
Device() {
serial_number = ("6DCMQ32");
device_description = ("TheDell");
}
Device(string s, string d) {
serial_number = s;
device_description = d;
}
};
string Device::device_description;
string Device::serial_number;
class Test {//Input and store Test Description, recent day, and month;
Calculate the next day
protected:
static string Test_Description;
static int recent_month, recent_day, recent_year, new_month;
static int nmonth, next_month, next_day, next_year, max_day;
public:
Test() {
Test_Description = ("Virtual");
}
static void getMonth() {//Calculates the next/new month
next_month = recent_month + nmonth;
new_month = next_month % 12;
if (next_month >= 12) {
cout << "The next Date: " << new_month << " / ";
}
else {
cout << "The next Date: " << next_month << " / ";
}
}
static void getDay() { //Calculates day of next month
if (new_month == 4 || new_month == 6 || new_month == 9 || new_month == 11) {
max_day = 30;
}
else if (new_month == 2) {
max_day = 29;
}
else {
max_day = 31;
}
if (recent_day > max_day) {
cout << max_day << " / ";
}
else {
cout << recent_day << " / ";
}
}
static void getYear() {// Calculate the year of next month
next_year = recent_year + next_month;
if (next_year >= 12) {
cout << recent_year + (next_month / 12) << endl;
}
else {
cout << next_year << endl;
}
}
static void getDate() {// Collects the output of each element of next date
Test::getMonth(), Test::getDay(), Test::getYear();
}
};
string Test::Test_Description;
int Test::recent_month;
int Test::recent_day;
int Test::recent_year;
int Test::new_month;
int Test::nmonth;
int Test::next_month;
int Test::next_day;
int Test::next_year;
int Test::max_day;
class Lab : public Device, public Test {
protected:
static int n;
public:
friend istream & operator>>(istream & in, Lab & lab) {// Inputs
cout << "Enter Device Desciption and Serial Number: ";
getline(in, device_description);
getline(in, serial_number);
cout << "Enter Test Desciption: ";
getline(in, Test_Description);
cout << "Enter the Number of months: ";
in >> nmonth;
cout << "Enter the Most Recent Date(mm/dd/yyyy): ";
in >> recent_month >> recent_day >> recent_year;
return in;
}
friend ostream & operator<<(ostream & out, Lab & lab) {//Outputs
everything in Device Class
out << Lab::device_description << endl;
out << Lab::serial_number << endl;
out << Lab::Test_Description << endl;
getDate();
return out;
}
static void getN() {
cout << "Enter the number of devices: ";
cin >> n;
}
static void getWrite() {
Lab *obj = new Lab[n];
if (obj == 0) {
cout << "Memory Error";
exit(1);
}
for (int i = 0; i<n; i++) {
cin >> obj[i];
cout << endl;
}
ofstream myfile("Device.txt");
myfile.write((char *)obj, n * sizeof(Lab));
delete[] obj;
}
static void getRead() {
ifstream file2("Device.txt");
Lab *obj2 = new Lab[n];
if (obj2 == 0) {
cout << "Memory Error";
exit(1);
}
file2.read((char *)obj2, n * sizeof(Lab));
for (int i = 0; i < n; i++) {
cout << obj2[i];
cout << endl;
}
delete[] obj2;
}
/*void getSearch(){
}*/
};
int Lab::n;
void main() {
Lab L;
L.getN();
L.getWrite();
L.getRead();
system("pause");
}
The Output I get is TheDell 6DCMQ32, Virtual when I entered my inputs. The date is correct the only problem is the Device Description, Serial Number, and Test Device.
Problem with Operator << in File i/o reading where it outputs the values in the Constructor
Purpose: is to enter the number of months for the next test date of device with input of serial number,
Device Description, Test Description, recent date, and the number of months of two tests. At the end the
program must be searched by having the user to input the serial number and the next date, if these two are
valid everything in the device is listed out.
Short of writing your application, I will do my best to give you some direction.
#include <iostream> // Note the '<' and '>' this is to specify is a language provided include
// More includes with the same issue...
using namespace std; // this is general considered bad=practice see https://stackoverflow.com/a/1452738/8480874 for details
//Input and store Device Description and Serial Numbers
class Device
{ // Notice the white space makes it easier to read...
protected:
//static string serial_number; // declaring this static means _EVERY_ device will have the same serial number
//static string device_description; // same as above
string serialNumber;
string deviceDesc;
public:
Device() : serialNumber("6DCMQ32"), deviceDesc("TheDell")
{
//serial_number = ("6DCMQ32"); // Not the best place for initialization
//device_description = ("TheDell"); // Not the best place for initialization
}
//Device(string s, string d) // you never actually use this
//{
// serial_number = s;
// device_description = d;
//}
};
//string Device::device_description; // This is a sign that you variable will be shared between everyone - not required if you remove the static
//string Device::serial_number; // This is a sign that you variable will be shared between everyone - not required if you remove the static
// This suffers from the same probles as the `class device` above
class Test
{
// Lots of stuff was here just trying to short the answer....
// Mostly has the same culprits mentions for the device
// This is one of the fucntions which gets called when you are trying to "save" the info to a file
static void getMonth(/* ostream & out */) // you need this as a paramater
{
next_month = recent_month + nmonth;
new_month = next_month % 12;
if (next_month >= 12)
{
// This function has no idea is needs to redirect the out put to a file...
// its only outputting to the standard console
cout << "The next Date: " << new_month << " / ";
}
else
{
//cout << "The next Date: " << next_month << " / ";
// using the new parameter in comments
// you can now save to your file
out << /*"The next Date: " <<*/ next_month << " / "; // no I comment out your extra message since you file reading does not look for that
}
}
};
// Again we have the same general misuse of C++ ( please keep learning! hopefully I am point you in the right direction )
class Lab : public Device, public Test
{
protected:
static int n;
public:
friend istream & operator>>(istream & in, Lab & lab)
{
// Inputs
cout << "Enter Device Desciption and Serial Number: ";
getline(in, device_description);
getline(in, serial_number);
cout << "Enter Test Desciption: ";
getline(in, Test_Description);
cout << "Enter the Number of months: ";
in >> nmonth;
cout << "Enter the Most Recent Date(mm/dd/yyyy): ";
in >> recent_month >> recent_day >> recent_year;
return in;
}
friend ostream & operator<<(ostream & out, Lab & lab) {//Outputs
everything in Device Class
out << Lab::device_description << endl;
out << Lab::serial_number << endl;
out << Lab::Test_Description << endl;
// Here you should pass the output pipe
getDate(/* out */);
return out;
}
static void getN() {
cout << "Enter the number of devices: ";
cin >> n;
}
static void getWrite()
{
// there's no real need to be using a pointer or memory allocation
//Lab *obj = new Lab[n];
// you can simply use
Lab obj[n];
//if (obj == 0)
//{
// cout << "Memory Error";
// exit(1);
//}
for (int i = 0; i < n; i++)
{
cin >> obj[i];
cout << endl;
}
ofstream myfile("Device.txt");
//myfile.write((char *)obj, n * sizeof(Lab)); // I've never tried writting an object's memory as a char* to file
// usually I like to generate a human readable output
std::string objBuffer = obj.getSaveBuffer(); // you will need to implement this `getSaveBuffer()` functions
myfile << objBuffer; // This can save lots of different value types for you! see http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/
//delete[] obj; // since there is no more new; we dont need a delete!
}
// The logic of what you read suffers the same general issues as the write.
// Also what/how you read is very far from the save so I can't venture into any solutions
// I'm hoping this will kick start you to figuring it out on your own =)
static void getRead() {
ifstream file2("Device.txt");
Lab *obj2 = new Lab[n];
if (obj2 == 0) {
cout << "Memory Error";
exit(1);
}
file2.read((char *)obj2, n * sizeof(Lab));
for (int i = 0; i < n; i++) {
cout << obj2[i];
cout << endl;
}
delete[] obj2;
}
/*void getSearch(){
}*/
};
int Lab::n;
// A program that runs should always return a numeric result indicating success or failure
//void main() {
int main()
{
Lab L; // Since everything in all your classes is static this didnt really add anything
// you done need an object if the object contains nothing
L.getN();
L.getWrite();
L.getRead();
system("pause"); // this is also bad practice, see https://stackoverflow.com/a/1107717/8480874
// I personally like `getchar()` because it's easy and quick
}
I am looking for a more faster way of dealing with the following C code. I have an image of 640x480 and I want to decimate it by a factor of 2 by removing every other rows and columns in the image. I have attached the code in the following. Is there any better way to optimize the code.
#define INPUT_NUM_ROW 480
#define INPUT_NUM_COL 640
#define OUTPUT_NUM_ROW 240
#define OUTPUT_NUM_COL 320
unsigned char inputBuf[INPUT_NUM_ROW* INPUT_NUM_COL];
unsigned char outputBuf[OUTPUT_NUM_ROW* OUTPUT_NUM_COL];
void imageDecimate(unsigned char *outputImage , unsigned char *inputImage)
{
/* Fill in your code here */
for (int p = 0; p< OUTPUT_NUM_ROW; p++) {
for (int q = 0; q < OUTPUT_NUM_COL; q++) {
outputImage[p*OUTPUT_NUM_COL + q] = inputImage[(p*INPUT_NUM_COL+q)*2];
// cout << "The pixel at " << p*OUTPUT_NUM_COL+q << " is " << outputImage[p*OUTPUT_NUM_COL+q] << endl;
}
}
}
Rather than doing the math every time in the inner loop, you could do this:
int outputIndex;
int inputIndex;
for (int p = 0; p< OUTPUT_NUM_ROW; p++) {
inputIndex = p * INPUT_NUM_COL * 2;
outputIndex = p * OUTPUT_NUM_COL;
for (int q = 0; q < OUTPUT_NUM_COL; q++) {
outputImage[outputIndex] = inputImage[inputIndex];
inputIndex += 2;
outputIndex++;
// cout << "The pixel at " << p*OUTPUT_NUM_COL+q << " is " << outputImage[p*OUTPUT_NUM_COL+q] << endl;
}
}
}
You could do the incrementing inline with the copying assignment too, and you could also only assign inputIndex and outputIndex the first time, but it wouldn't get you as much of a performance boost as moving the calculation out of the inner loop. I assume that bulk copying functions don't have this kind of incrementing flexibility, but if they do and they use hardware acceleration that is available on all of your target platforms, then that would be a better choice.
I am also assuming that array access like this compiles down to the most optimized pointer arithmetic that you could use.
I want to repetitively solve the CG/BicGSTAB using CUSP solver, called from Fortran. To avoid transfers I am passing the Fortran data directly to CUSP. The code compiles but breaks at the run time flagging:
terminate called after throwing an instance of 'thrust::system::system_error'
what(): invalid argument
terminate called recursively
Aborted (core dumped)
Let alone the core of the code, even the print stream is not happening. The code of course is in the preliminary stage, but I wonder what is wrong with it.
extern "C" void bicgstab_(int *device_I, int *device_J, float *device_V, float *device_x, float *device_b, int *n, int *nnz){
int N = *n;
int NNZ = *nnz;
std::cout << N << " " << NNZ << " " << *device_I << std::endl;
for(int i=0; i<N;i++)std::cout << device_I[i] << " "; std::cout << std::endl;
for(int i=0; i<NNZ;i++)std::cout << device_J[i] << " "; std::cout << std::endl;
for(int i=0; i<NNZ;i++)std::cout << device_V[i] << " "; std::cout << std::endl;
for(int i=0; i<N;i++)std::cout << device_x[i] << " "; std::cout << std::endl;
for(int i=0; i<N;i++)std::cout << device_b[i] << " "; std::cout << std::endl;
// *NOTE* raw pointers must be wrapped with thrust::device_ptr!
thrust::device_ptr<int> wrapped_device_I(device_I);
thrust::device_ptr<int> wrapped_device_J(device_J);
thrust::device_ptr<float> wrapped_device_V(device_V);
thrust::device_ptr<float> wrapped_device_x(device_x);
thrust::device_ptr<float> wrapped_device_b(device_b);
// use array1d_view to wrap the individual arrays
typedef typename cusp::array1d_view< thrust::device_ptr<int> > DeviceIndexArrayView;
typedef typename cusp::array1d_view< thrust::device_ptr<float> > DeviceValueArrayView;
std::cout << wrapped_device_I[3];
/*
DeviceIndexArrayView row_indices (wrapped_device_I, wrapped_device_I + (N+1));
DeviceIndexArrayView column_indices(wrapped_device_J, wrapped_device_J + NNZ);
DeviceValueArrayView values (wrapped_device_V, wrapped_device_V + NNZ);
DeviceValueArrayView x (wrapped_device_x, wrapped_device_x + N);
DeviceValueArrayView b (wrapped_device_b, wrapped_device_b + N);
// std::cout << device_x[0] ;
// for(int i=0;i<NNZ;i++)std::cout << column_indices[i] << std::endl;
// combine the three array1d_views into a csr_matrix_view
typedef cusp::csr_matrix_view<DeviceIndexArrayView,
DeviceIndexArrayView,
DeviceValueArrayView> DeviceView;
// construct a csr_matrix_view from the array1d_views
DeviceView A(N, N, NNZ, row_indices, column_indices, values);
// set stopping criteria: // iteration_limit = 100 // relative_tolerance = 1e-5
cusp::verbose_monitor<float> monitor(b, 100, 1e-5);
// solve the linear system A * x = b with the Conjugate Gradient method
// cusp::krylov::bicgstab(A, x, b);*/
}
If this is not feasible, I can move over to another approach,but as I am not sure about the correctness, I am unable to decide. Any help is appreciated.