1

I have to use CImg construct a image and draw a triangle using mid-point algorithm and then color the edges using linear interpolation. I have a hard time understanding the syntax of CImg Library.

All I have right now is the black blank image.

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

using namespace cimg_library;
using namespace std;

int main() {
  //Create an empty image
  CImg<unsigned char> triangle(255, 255, 1, 3, 0);

  //Display and save filtered image
  CImgDisplay disp(triangle); 
  while (!disp.is_closed())
      disp.wait();   
  triangle.save("triangleInterpolation.bmp");  
}

The result should look like this
enter image description here

Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77
William
  • 53
  • 10

1 Answers1

1

Something like this should be good...

#include <iostream>
#include <cstdlib>
#define cimg_display 0
#include "CImg.h"

using namespace cimg_library;
using namespace std;

int main() {
   // Create 256x256 with radial gradient
   CImg<unsigned char> image(256,256,1,3,0);
   cimg_forXYC(image,x,y,c) {image(x,y,0,c) = 255-(unsigned char)hypot((float)(128-x),(float)(128-y)); }

   // Now overlay a partially opaque 2D interpolated filled triangle for fun
   unsigned char cyan[]    = { 0, 255, 255 };
   unsigned char magenta[] = { 255, 0, 255 };
   unsigned char yellow[]  = { 255, 255, 0 };

   const float opacity=0.6;
   image.draw_triangle(
      10,10,       // 1st vertex x,y
      245,10,      // 2nd vertex x,y
      245,245,     // 3rd vertex x,y 
      cyan,        // 1st vertex colour
      magenta,     // 2nd vertex colour
      yellow,      // 3rd vertex colour
      opacity);

   // Save result image as NetPBM PNM - no libraries required
   image.save_pnm("result.pnm");
}

enter image description here

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • It works, thank you. If I dont wanna have a right triangle, I just need to change the vertex of the points? Also, how do I implement the linear interpolation and the mid-point algorithm? Your way is easy and make more sense than the instruction for the assignment I have. But I think I suppose to do step by step for those algorithms. – William Feb 04 '18 at 17:16
  • Yes, just change the vertices and the colours - it should be easy enough. You can implement the formula yourself also. Just look at the same Wikipedia page I linked in my last answer and use the same type of technique as I coded. – Mark Setchell Feb 04 '18 at 17:26