Welcome, Guest. Please login or register. Did you miss your activation email?

Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Messages - tarikk

Pages: [1]
1
Graphics / Fastest way to change all pixels in a loop
« on: August 25, 2024, 10:52:29 pm »
I am trying to copy Sebastian Lague's Neural Network project using C++.

I have to assign a color to every pixel on the screen based on a bool variable in a loop. I have a function that works but it works so slow (about 15 fps). I need a faster way to go change pixels.

/* iterates every pixel on the screen and assigns a color to is based
*  on the value of net.Classify() method.
*/

void Visualize(sf::RenderWindow& w, sf::Image& im, NeuralNetwork& net, sf::Texture& tx, sf::Sprite& sp)
{
    // This variable is used for optimization.
    // It allows me to calculate 25 times fewer pixels but the image is grainy
    // In optimal, this variable should be euqal to 1
    int prescalar = 5;

    for (int x = 0; x < w.getSize().x; x += prescalar)
        for (int y = 0; y < w.getSize().y; y += prescalar)
        {
            std::vector<float> f = { (float)x,(float)y };
            int result = net.Classify(f); // return true or false
            sf::Color c;
            if (result)
                c = sf::Color(185, 250, 246);
            else
                c = sf::Color(255, 149, 130);

            for(int xx = 0; xx < prescalar; xx++)
                for(int yy = 0; yy < prescalar; yy++)
                    im.setPixel(x + xx, w.getSize().y - y - 1 - yy, c); // y size math used for left bottom corner to be the (0,0)
        }
    tx.loadFromImage(im);
    sp.setTexture(tx, true);
    w.draw(sp);
}
 

My main looks something like this
int main()
{
    sf::RenderWindow window(sf::VideoMode::getDesktopMode(), "Window Title", sf::Style::Fullscreen);

    sf::Image im;
    im.create(window.getSize().x, window.getSize().y, sf::Color::Black);

    sf::Texture tx;
    sf::Sprite sp;

    NeuralNetwork network();

    // some stuff

    while (window.isOpen())
    {
        // some stuff
        Visualize(window, im, network, tx, sp);
        // some other stuff
    }
}
 

I checked the work times of all functions and this one is the by far longest one (60 to 80 milliseconds). What are the faster options to implement this?

Pages: [1]