Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

c++ - Linux draw pixel buffer

The problem is simple enough, i have a code that generates a pixel buffer. Now i need to present this pixel buffer instead of saving image and then analyzing it after.

What would be the solution to:

  1. Open window
  2. Replace all pixels in this window with my pixels RGB888

So far suggestion were: To use opengl, create a vertex buffer for a rect covering a window, and use pixel shader to draw your pixels. Which clearly is not the best way to swap pixel buffers in window.

Platform: Ubuntu 18

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use CImg which is a small, fast, modern C++ library. It is "header only" so no complicated linking or dependencies.

// http://cimg.eu/reference/group__cimg__tutorial.html

#include <iostream>
#include <string>
#include "CImg.h"

using namespace cimg_library;

int main(int argc,char **argv) {

   const unsigned char white[] = { 255,255,255 };
   const int width  = 320;
   const int height = 240;
   // Create 3-channel RGB image
   CImg<> img(width,height,1,3);

   // Create main window
   CImgDisplay main_window(img,"Random Data",0);
   int frame = 0;

   while (!main_window.is_closed()) {
     // Fill image with random noise
     img.rand(0,255);
     // Draw in frame counter
     std::string text = "Frame: " + std::to_string(frame);
     img.draw_text(10,10,text.c_str(),white,0,1,32);
     main_window.display(img);
     frame++;
     std::cout << "Frame: " << frame << std::endl;
   }
}

Here it is in action - the quality is not best because random data is poorly compressible and Stack Overflow has a 2MB image limit. It is good in real-life.

enter image description here

Note that as I am using X11 underneath here, the compilation command must define cimg_display so will look something like:

g++ -Dcimg_display=1 -std=c++11 -I /opt/X11/include -L /opt/X11/lib -lx11 ...

Note also that I am using img.rand() to fill the image with data, you will want to get img.data() which is a pointer to the pixel buffer and then memcpy() your image data into the buffer at that address.

Note that I also did some stuff with writing to the framebuffer directly in another answer. That was in Python but it is easily adapted.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...