0

Please have a look at the following opencv code

void ImageWriter::writeImage(Mat image)
{
    number++;
    String name="D:/OpenCV Final Year/Images/intruder";
    name+=number;
    name+=".bmp";

    //imwrite("D:/OpenCV Final Year/Images/intruder.bmp",image);
    imwrite(name,image);
}

Here, all I can say is that imwrite() is not writing anything! There is no errors but no outputs as well. If I use the commented version of the imwrite() it works as expected . But I can't use it because I need to write number of images, so the name change done by number integer variable is important. I believe the issue is with the name string.

However this name is in type of C# and that is because std:string conflicted.

How can I make this dynamic name creation success and make the get the imwrite() to work?

PeakGen
  • 21,894
  • 86
  • 261
  • 463
  • 2
    What do you mean "`std::string` conflicted"? [This question](http://stackoverflow.com/q/1300718/1601291) addresses conversion between the two types. – Aurelius Jul 24 '13 at 18:53
  • @Aurelius: Pardon me for the delay of my reply. For std:string, it generate errors – PeakGen Jul 26 '13 at 18:04
  • What kind of errors? Compile errors? Runtime errors? What do they say? – Aurelius Jul 26 '13 at 18:14
  • @Aurelius: Sorry for the delay again. The error is "error: c2440: 'initializing' : cannot convert from System::String ^ to std::basic_string<_Elem,_Traits,_Ax> " – PeakGen Jul 28 '13 at 17:26

2 Answers2

1

Just thoughts Have you tried:

  1. Use char array? (char[])
  2. StringStream
  3. String Format instead of +=
Sam Sussman
  • 1,005
  • 8
  • 27
1

It doesn't work because you are attempting to pass a managed .NET System::String object to a function that is expecting an std::string. Looking at the documentation here (OpenCV Documents C++ imwrite) it would appear that it is expecting a const string& type.

If you are writing this in C# there isn't a way of being able to 'declare' an std::string object.

I would start by seeing if name.ToCharArray() would work. Although this will produce a managed array it is possible the compiler may work out the required conversion from managed char array to native.

As you are using C++/CLI you need to marshal your managed string to the std format:

#include <string>
using namespace std;
using namespace System;

void MarshalString (String^ s, string& os )
{
   using namespace Runtime::InteropServices;
   const char* chars = 
      (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
   os = chars;
   Marshal::FreeHGlobal(IntPtr((void*)chars));
}

void ImageWriter::writeImage(Mat image)
{
    number++;
    String name="D:/OpenCV Final Year/Images/intruder";
    name+=number;
    name+=".bmp";

    string nativeString;
    MarshalString(name, nativeString);

    imwrite(nativeString, image);
}
Gareth
  • 439
  • 5
  • 12