Suraksha Ajith
Suraksha Ajith

Reputation: 892

how to convert SFML image to OpenCV mat in C++?

Below code is used to convert an OpenCV Mat image into SFML image. How to convert SFML image back to Mat image?

    cv::Mat frameBGR, frameBGRA;
    sf::Image image;
    cv::cvtColor(frameBGR, frameRGBA, cv::COLOR_BGR2RGBA);
    image.create(frameRGBA.cols, frameRGBA.rows, frameRGBA.ptr());

If texture or sprite can't be converted to OpenCV Mat,then is it possible to convert sf::Image to OpenGL and convert it back to cv::Mat

    sf::Texture texture;
    sf::Event event;
    sf::Sprite sprite;
    texture.loadFromImage(image);
    sprite.setTexture(texture);

Update: I referred this post, but still was not able to convert.

    void* buffer = ℑ 
    cv::Mat image_mat = cv::Mat(cvSize(500, 500),CV_8UC4, buffer, cv::Mat::AUTO_STEP);  
    cvtColor(image_mat, converted,CV_RGBA2BGR);

It crashes at below line of code (when i display image )

imshow("img", converted);

Upvotes: 3

Views: 671

Answers (1)

al-eax
al-eax

Reputation: 732

This code worked for me:

cv::Mat sfml2opencv(const sf::Image& img){
    //get size from image
    cv::Size size(img.getSize().x, img.getSize().y);
    //create a mat on image memory
    cv::Mat mat(size,CV_8UC4, (void*)img.getPixelsPtr(), cv::Mat::AUTO_STEP);
    //make SFML RGBA to OpenCV BGRA
    cv::cvtColor(mat, mat, cv::COLOR_RGBA2BGRA);
    //clone mat to avoid memory editing on image memory
    return mat.clone();
}

Your code crashes because you try to create the cv::Mat on the memory of the sf::Image object, instead of the memory of the pixels.

Upvotes: 2

Related Questions