OpenCV C++, Define a background model - c++

I am busy converting and interpreting software used in previous years of my final year project.
I would just like to check if it is possible to define a background model in a header file, as i am currently getting an error.
class CWaterFill
{
public:
void Initialise();
Mat ContourFilter(Mat Img, int minSize);
Mat superminImg;
protected:
BackgroundSubtractorMOG2 m_bg_model;//Define the background model.
};
It is then used in the .cpp file in the following function:
void CWaterFill::GMM2(Mat InputImg, int nFrame, double learnRate)
{
m_bg_model(InputImg, m_fgmask, learnRate);//m_fgmask outlook is
}

Use a pointer to an abstract BackgroundSubtractor object:
...
protected:
cv::Ptr<BackgroundSubtractor> m_bg_model;//Define the background model.
And then create the concrete type, e.g.:
m_bg_model = createBackgroundSubtractorMOG2(20, 16, true);

Related

C delegate to C++

I have a small problem using a library that gets images from a CMOS camera.
The library permits to use a stream functionality and I have three access point to set (three delegates) for when I get an image, when an image is dropped and when there is an error.
typedef void(* StreamCallbackPtr)( IMAGE *image );
typedef void(* StreamErrorCallbackPtr)();
typedef void(* StreamFrameDroppedCallbackPtr)();
int Stream_Start( DEVICE device, IMAGEFORMAT format, StreamCallbackPtr stream_callback, StreamFrameDroppedCallbackPtr f_dropped_callback, StreamErrorCallbackPtr error_callback );
I enter a StreamCallbackPtr as soon as an image is ready on the camera, but keep in mind that I do not have any ways of changing the library code.
And here is the question: How do I plug my own delegate in C++ ?
Lets say I use this stream functionality inside a class, I know that I have at least two options; the wrapper, and global variables. The first one seems compromised since I cannot pass anything else than an IMAGE, and I want to avoid using global variables (it would be static members in this case).
Any ideas ?
You could use a static member function as the StreamCallbackPtr which then can access a private static reference or list of references to the C++ delegates which wish to receive the message.
That way you have hidden most of the details as private to the class.
The code below is pseudo-C++ (I haven't checked it properly) but it should give you the idea of what I am suggesting.
class Delegate
{
protected:
void Callback( IMAGE *image ) = 0;
void Error() = 0;
void FrameDropped() = 0;
public:
static void SetDelegate(Delegate* d) { delegateInstance = d; }
static void StaticCallback( IMAGE *image)
{
// Invoke the delegate instance
if (delegateInstance != nullptr) delegateInstance->Callback();
}
// Same for the others...
private:
static Delegate* delegateInstance = nullptr;
};
class MyClass : public Delegate
{
protected:
void Callback( IMAGE *image )
{
// Now the callback is in a delegate instance
}
};
int main(void)
{
MyClass mc;
Delegate::SetDelegate(&mc);
StreamCallbackPtr scp = &Delegate::StaticCallback;
// Register the other static callbacks...
return 0;
}

Child classes that share Parent class member

I have an awkward question. I think it's impossible but I need to know for sure. It's a bit of an odd request, but I need my child classes to share the SAME Pixels vector from the parent class.
Basically, I want to create an instance of Image class. That Image class will hold Pixels for both Bitmap and Png Class so that if I need to convert from Bitmap To PNG and Vice-versa, they use the same vector rather than me creating both Bitmap and PNG classes.
class Image
{
private:
std::vector<RGB> Pixels;
};
class Bitmap : Image
{
public:
Bitmap() : Image() {};
};
class Png : Image
{
public:
Png() : Image() {};
};
Such that when I do:
int main()
{
Image Img();
Img.GetBitmapPixels(); //This
Img.GetPngPixels(); //And this, return the same Pixels Vector.
Bitmap Foo = Img.ToPng();
Png Moo = Img.ToBitmap();
//Such that both Foo and Moo have the exact same underlying Pixels Vector.
}
Currently my classes look like:
class Bitmap
{
private:
std::vector<RGB> Pixels;
public:
Bitmap();
std::vector<RGB> GetPixels() {return Pixels;}
void SetPixels(std::vector<RGB> Pixels) {this->Pixels = Pixels;}
};
class Png
{
private:
std::vector<RGB> Pixels;
public:
Png();
std::vector<RGB> GetPixels() {return Pixels;}
void SetPixels(std::vector<RGB> Pixels) {this->Pixels = Pixels;}
};
And to convert from one to the other, I have to do:
int main()
{
Bitmap Bmp();
Png PNG();
PNG.SetPixels(BMP.GetPixels); //BMP has to COPY PNG's Pixels and vice-versa..
}
It's kind of a stupid question. I just don't want to copy pixels. I just want to be able to convert between the two classes without any copying as both classes hold an std::vector Pixels member and the data is aligned the same.
I guess I'm trying to be able to do: PNG.SaveAsBitmap(...); Or BMP.SaveAsPNG(...); without creating a new instance of the other.
How can I avoid copying/creating and making a new instance of the other class I'm converting to? Can I have classes that inherit from eachother?
I may be oversimplyfying this. How are you loading your data? If it is the same for each image type could you have a load in the image class and just overload the Translation functions. I am not an expert on image data but could you do something similiar to:
public Image
{
private Pixels data;
public void GetPixels();
public virtual Pixels ToFormat(FormatEnum format);
}
public Bitmap:Image
{
public override Pixels ToFormat(FormatEnum format)
{
switch(format){
case FormatEnum.Bitmap:return data;break;
case FormatEnum.Png:return doSomethingElse();break;
}
}
}
int main()
{
Image Img();
Img.GetPixels();
Bitmap Foo = Img.ToFormat(Format.BitMap);
Png Moo = Img.ToFormat(Format.Png);
}
Since they share a parent as a common factor, you can elect to use pointers (this is considered a shallow copy), but this is usually not wise a deep copy is usually better. Perhaps you can create two functions one to create a shallow copy and one for a deep copy. Since a Bitmap and a Png are separate entities (they are siblings). Perhaps you should allow BMP to be the parent of png?
You may also elect to decouple the encoding altogether for saving purposes and just deal with the raw image data.

How to pass an Image in SFML C++

I am trying to make a simple function or class that selects an image and returns it or passes it in some way to a different class. Is it as simple as knowing what type the Image is considered? or do I need to do something else? I am running Code::Blocks 10.05 with GNU GCC compiler on a windows 8 computer. Any help is appreciated.
Thanks to Aesthete, I made some progress. Now I have this:
class Background{
sf::Image BGI;
sf::Sprite BG;
Image& img;
public:
void rimage(std::string name){
sf::Image extra;
extra.LoadFromFile(name);
img = extra;
}
void init(std::string name){
BGI = img
BG.SetPosition(0.f,0.f);
BG.SetImage(BGI);
}
};
But when I run it, I get this:
...4 error: ISO C++ forbids declaration of 'Image" with no type
Also,
...10 error: 'img' is defined in this scope
I have included the libraries that I need to run SFML, I just left it out to keep things clean, I adjusted the lines the errors above occurred on to make it easier to follow.
Isn't img now sort of a global variable within Background?
and I thought Image& was the type of img... What needs to change here?
You don't need a load method, nor any extra Image objects. You can do all this processing in the constructor.
class Background{
private:
// You only need an image and a background, if that.
sf::Image BGI;
sf::Sprite BG;
public:
// Use a constructor.
Background(std::string name)
{
SetBackground(name, Vector2f(0.f, 0.f));
}
void SetBackground(std::string name, sf::Vector2f pos)
{
BGI.LoadFromFile(name);
BG.SetImage(BGI);
BG.SetPosition(pos);
}
};
// Constructor loads image, sets image to sprite, and set sprite position.
Background bg("MyBackground.png");
// You can change the background image an position like so.
bg.SetBackgrond("newImage.png", Vector2f(10.f, 20.f));

Design suggestions for an Image class hierarchy

I need some design suggestions for an Image class hierarchy.
Currently, I have 2 types of images (one is a standard image, the second doesn't contain standard image data).
Sometimes I want the object to allocate the memory for the image data, and other times I just want it to point to it.
The problem arises when I want to give TypeA images specific functionality.
If TypeA images inherit from Image, I will have to duplicate the functionality of the Allocated vs. non-Allocated Image.
I'm sure there is a better way to do this, I remember some elegant solutions with mixins during university, but can't find a way to use that here.
My current design looks like:
class Image
{
public:
Image(int width, int height, int bpp);
virtual ~Image() {};
// getters
template <typename T>
T* ptr() { return reinterpret_cast<T*>(m_imageData); } // T depends on bpp
protected:
// metadata
char* m_imageData;
};
class AllocImage : public Image
{
public:
AllocImage(int width, int height, int bpp, DataType dataType) :
Image(width, height, bpp, dataType)
{
m_imageData = new char[m_dataSize];
}
~AllocImage()
{
delete m_imageData;
}
};
class ImageHolder : public Image
{
public:
ImageHolder(int width, int height, int bpp, DataType m_dataType);
void setPtr(const void* ptr);
};
class AllocatedImageTypeA : public AllocImage
{
public:
// Type A specific methods
};
class NonAllocatedImageTypeA : public ImageHolder
{
public:
// duplicated Type A specific methods
};
If all the differences are constrained to how the image is held (allocated or not), you could use the policy model.
The short explanation is that you would pass a policy object to the image, where the policy describes whether you need to deallocate the image or not, how to access it, etc., basically anything that relates to the differences that arise from how the image data is held (allocated vs. pointed). Then all your access to the image will be through the policy.
For example, instead of writing
delete image;
You would write:
policy.del(image);
Where policy.del can be a delegate to delete or a no-op, depending on the actual type of the policy (that is in line with what the image requires)
Why so many types? If the difference is only in allocation, then simply create multiple constructors, one which takes a pointer to a pre-allocated data holder, one that doesn't and does the allocation internally. You could also use dependency injection to get the variations in behaviour / functionality.
I had a similar case.
Let's make something clear. Your class hierarchy its not based if an image is allocated or not, but, each class will have some features.
You may want to have a very specialized class that allocates images, another that references, and, warp that class with another of the same hierarchy, with similar features.
The following example, explains the idea of wraping one class, with another class,
from the same inheritance, that seems to apply to your questio.
Disclaimer: Please ignore, some minor bugs or non relevant syntax errors:
// generic base class for my image library:
/* abstract */ class GenericImage
{
public:
int width;
int height;
public:
/* constructor */ GenericImage() ;
/* destructor */ ~GenericImage() ;
/* constructor */ GenericImage(int newwidth, int newheight);
}; // class GenericImage
// in charge of allocating or deallocating an image
class AllocatedImage: GenericImage
{
public:
/* constructor */ AllocatedImage() ;
/* destructor */ ~AllocatedImage() ;
/* constructor */ AllocatedImage(int newwidth, int newheight);
/* constructor */ AllocatedImage(char* filename);
}; // class AllocatedImage
// access an image, but doesn't allocate or deallocate
class ContainedImage: GenericImage
{
public:
/* constructor */ ContainedImage() ;
/* destructor */ ~ContainedImage() ;
/* constructor */ ContainedImage(int newwidth, int newheight);
}; // class AllocatedImage
// real working class, will allocate other objects,
// of same hierarchy
class WrapperImage: GenericImage
{
public:
GenericImage* RealImage;
public:
/* constructor */ GenericImage() ;
/* destructor */ ~GenericImage() ;
void AllocateImage(AllocatedImage* newimage);
void HoldImage(ContainedImage* newimage);
}; // class AllocatedImage
Suggestions:
Its good idea, to have a constructor without parameters, specially if you are designing a class hierarchy, instead of a single class.
I know its a quick example, but, you may want to move all code to body file.
Cheers.

Accessing an object from a different class - Design

I have three classes, TImageProcessingEngine, TImage and TProcessing
TImageProcessingEngine is the one which i am using to expose all my methods to the world.
TImage is the one i plan to use generic image read and image write functions.
TProcessing contains methods that will perform imaging operations.
class TImageProcessingEngine
{
public:
TImage* mpImageProcessingEngine;
};
class TImage
{
public:
int ReadImage();
int WriteImage();
private:
//a two dimensional array holding the pixel values
tImageMatrix* mpImageMatrix;
};
class TProcessing
{
public:
int ConvertToBinary();
int ConvertToGrayScale();
};
My question is how do i access the object mpImageMatrix in class TProcessing? So that my calling application can use the following
TImageProcessingEngine* vEngine = new TImageProcessingEngine;
//Converts an input gray scsale image to binary image
vEngine->ReadImage().ConvertToBinary();
//Write the converted image to disk
vEngine->WriteImage();
delete vEngine;
vEngine = NULL;
//During this whole processing internally,
//the image is read in to `mpImageMatrix`
//and will also be holding the binarised image data,
//till writing the image to disk.
Or Do you recommend any other approach to my class design?
I would certainly recommend a different implementation, but let's check the design first.
I don't really understand the added value of TImageProcessingEngine, it doesn't bring any functionality.
My advice would be quite simple in fact:
Image class, to hold the values
Processing class (interface), to apply operations
Encoder and Decoder classes (interfaces), to read and write to different formats
It does make sense for the Processing class to have access to the images internal only if you can get efficiency from it (which is likely), in this case you can simply makes Processing friend and having it unpack the values for its derived
class Image
{
public:
Image();
void Accept(Processing& p);
void Encode(Encoder& e) const; // Image is not modified by encoding
void Decode(Decoder& d); // This actually resets the image content
private:
friend class Processing;
size_t mHeight;
size_t mWidth;
std::vector<Pixel> mPixels; // 2D array of Pixels
};
class Processing
{
public:
void apply(Image& image)
{
this->applyImpl(image.mHeight, image.mWidth, image.mPixels);
}
private:
virtual void applyImpl(size_t h, size_t w, std::vector<Pixel>& pixels) = 0;
};
Encoder and Decoder follow the same principle.
Note how I never needed an explicit pointer, and the guaranteed correctness that results from it.
First off, based on your provided code there are no ReadImage() & WriteImage() functions in the TImageProcessingEngine class, so the later code where you use such functionality is flawed.
As for the solution, you can make a getter function for the tImageMatrix pointer like this:
tImageMatrix* GetImageMatrix() { return mpImageMatrix; }
Then just pass that pointer (or a pointer to the whole TImage instance) to the TProcessing function you want to call.
Why you want to have a separate TProcessing process, when it specifically has functions just accessing mpImageMatrix;
In OOP, you have to bind the data members and it's operations..
So, IMO, remove your TProcessing class and have both the functions within TImage..
Your TImage will be like,
class TImage
{
public:
int ReadImage();
int WriteImage();
int ConvertToBinary();
int ConvertToGrayScale();
private:
//a two dimensional array holding the pixel values
tImageMatrix* mpImageMatrix;
};
You could create an accessor TImage class:
byte * pixelAt(unsigned x, unsigned y);