Interpolating elements of a color matrix on the basis of some given reference elements
<p>This is more or less a follow up question to <a href="http://stackoverflow.com/questions/39485178/two-dimensional-color-ramp-256x256-matrix-interpolated-from-4-corner-colors?noredirect=1#comment66289716_39485178">Two dimensional color ramp (256x256 matrix) interpolated from 4 corner colors</a> that was profoundly answered by jadsq today.</p>

<p>For linear gradients the previous answer works very well. However, if one wants to have better control of the stop colors of the gradient, this method seems not to be very practical. What might help in this situation is to have some reference color points in a matrix (lookup table) which are used to interpolate color values for the empty position in the look-up table. What I mean might be easier read out of the below image.</p>

<p><a href="http://i.stack.imgur.com/AwPYk.png" rel="nofollow"><img src="http://i.stack.imgur.com/AwPYk.png" alt="enter image description here"></a></p>

<p>The whole idea is taken from <a href="http://cartography.oregonstate.edu/pdf/2006_JennyHurni_SwissStyleShading.pdf" rel="nofollow">http://cartography.oregonstate.edu/pdf/2006_JennyHurni_SwissStyleShading.pdf</a> page 4 to 6. I've read through the paper, I understand theoretically what is going on but failing miserably because of my low experience with interpolation methods and to be honest, general math skills. What might also be of interest is, that they use a sigmoid Gaussian bell as interpolation method (page 6). They argue that Gaussian weighting yielded the visually best results and was simple to compute (equation 1, with k=0.0002 for a table of 256 per 256 cells).</p>

<hr>

<p>Edit (better illustrations):</p>

<p><a href="http://i.stack.imgur.com/cQVW1.png" rel="nofollow"><img src="http://i.stack.imgur.com/cQVW1.png" alt="Weighting functions for interpolating colours"></a></p>

<p><a href="http://i.stack.imgur.com/hGXfz.png" rel="nofollow"><img src="http://i.stack.imgur.com/hGXfz.png" alt="Equation 1"></a></p>

<hr>

<p>I have the other parts of their presented methods in place but filling the empty values in the matrix really is a key part and keeps me from continuing. Once again, thank you for your help!</p>

<p>What I have right now:</p>

<pre><code>#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt 

# the matrix with the reference color elements
ref=np.full([7, 7, 3], [255,255,255], dtype=np.uint8)
ref[0][6] = (239,238,185)
ref[1][1] = (120,131,125)
ref[4][6] = (184,191,171)
ref[6][2] = (150,168,158)
ref[6][5] = (166,180,166)

# s = ref.shape
#
# from scipy.ndimage.interpolation import zoom
# zooming as in http://stackoverflow.com/a/39485650/1230358 doesn't seem to work here anymore, because we have no corner point as reference but randomly distributed points within the matrix. As far as I know ...
# zoomed=zoom(ref,(256/s[0],256/s[1],1),order=1)

plt.subplot(211)
plt.imshow(ref,interpolation='nearest')
# plt.subplot(212)
# plt.imshow(zoomed,interpolation='nearest')
plt.show()
</code></pre>

<p>First some questions to better clarify your problem:</p>

<ul>
<li>what kind of interpolation you want: linear/cubic/other ?</li>
<li>What are the points constrains?  for example will there be alway just single region encapsulated by these control points or there could be also points inside? </li>
</ul>

<p>For the simple linear interpolation and arbitrary (but at least 3 points not on a single line) I would try this:</p>

<ol>
<li><p><strong>Triangulate control points area</strong></p>

<p>To non overlapping triangles covering whole defined area.</p></li>
<li><p><strong>render triangles</strong></p>

<p>So just rasterize see <a href="http://stackoverflow.com/a/39062479/2521214">Algorithm to fill triangle</a> and all the sublinks. You should interpolate also the <code>R,G,B</code> along with the coordinates.</p></li>
<li><p><strong>Create a 2 copies of gradient and extrapolate one with H and second with V lines</strong></p>

<p>So scan all the H-horizontal lines of the gradient and if found 2 known pixels far enough from each other (for example quarter or half of gradient size) then extrapolate the whole line unknown colors. So if found known endpoints (Red) are <code>(x0,y,r0,g0,b0),(x1,y,r1,g1,b1)</code> then set all unknown colors in the same line as:</p>

<pre><code>r = r0+(r1-r0)*(x-x0)/(x1-x0)
g = g0+(g1-g0)*(x-x0)/(x1-x0)
b = b0+(b1-b0)*(x-x0)/(x1-x0)
</code></pre>

<p>Similarly do the same in the copy of gradient for V-vertical lines now. So the points are now (x,y0,r0,g0,b0),(x,y1,r1,g1,b1)` and extrapolation:</p>

<pre><code>r = r0+(r1-r0)*(y-y0)/(y1-y0)
g = g0+(g1-g0)*(y-y0)/(y1-y0)
b = b0+(b1-b0)*(y-y0)/(y1-y0)
</code></pre>

<p>After this compare both copies and if unknown point is computed in both set it as average of both colors in the target gradient image. Loop this whole process (<strong>#3</strong>) until no new gradient pixel is added.</p></li>
<li><p><strong>use single extrapolated color for the rest</strong></p>

<p>depending on how you define the control points some areas will have only 1 extrapolated color (either from H or V lines but not both) so use only the single computed color for those (after <strong>#3</strong> is done).</p></li>
</ol>

<p>Here an example of what I mean by all this:</p>

<p><a href="http://i.stack.imgur.com/l6zBg.png" rel="nofollow"><img src="http://i.stack.imgur.com/l6zBg.png" alt="overview"></a></p>

<p>If you want something simple instead (but not exact) then you can bleed the known control points colors (with smooth filters) to neighboring pixels until the whole gradient is filled and saturated.</p>

<ol>
<li><strong>fill unknown gradient pixels with predefined color meaning not computed</strong></li>
<li><p><strong>set each pixel to average of its computed neighbors</strong></p>

<p>you may do this in separate image to avoid shifting.</p></li>
<li><p><strong>set control points back to original color</strong></p></li>
<li><p><strong>loop #2 until area filled/saturated/or predefined number of iterations</strong></p></li>
</ol>

<p><strong>[Edit1] second solution</strong></p>

<p>Ok I put it together in <strong>C++</strong> with your points/colors and gradient size here is how it looks (I bleed 100 times with 4-neighbors bleeding without weights):</p>

<p><a href="http://i.stack.imgur.com/lYYyu.png" rel="nofollow"><img src="http://i.stack.imgur.com/lYYyu.png" alt="bleeding"></a></p>

<p>The image on the left is input matrix where I encoded into alpha channel (highest 8 bits) if the pixel is reference point, computed or yet undefined. The image on the right is after applying the bleeding 100 times. The bleed is simple just take any non reference point and recompute it as average of all usable pixels around and itself (ignoring any undefined colors). </p>

<p>Here the <strong>C++</strong> code you can ignore the <strong>GDI</strong> stuff for rendering (beware my gradient map has <code>x</code> coordinate first you got <code>y</code> !)</p>

<pre class="lang-cpp prettyprint-override"><code>//---------------------------------------------------------------------------
const int mxs=7,mys=7,msz=16;   // gradient resolution x,y and square size for render
DWORD map[mxs][mys];            // gradient matrix ... undefined color is &gt;= 0xFF000000
// 0x00?????? - reference color
// 0xFF?????? - uncomputed color
// 0xFE?????? - bleeded color
//---------------------------------------------------------------------------
void map_clear()    // set all pixels as uncomputed (white with alpha=255)
    {
    int x,y;
    for (x=0;x&lt;mxs;x++)
     for (y=0;y&lt;mys;y++)
      map[x][y]=0xFFFFFFFF;
    }
void map_bleed()    // bleed computed colors
    {
    int x,y,r,g,b,n;
    DWORD tmp[mxs][mys],c;
    for (x=0;x&lt;mxs;x++)
     for (y=0;y&lt;mys;y++)
        {
        c=map[x][y];
        n=0; r=0; g=0; b=0; if (DWORD(c&amp;0xFF000000)==0) { tmp[x][y]=c; continue; }      if (DWORD(c&amp;0xFF000000)!=0xFF000000) { r+=c&amp;255; g+=(c&gt;&gt;8)&amp;255; b+=(c&gt;&gt;16)&amp;255; n++; }
        x++;      if ((x&gt;=0)&amp;&amp;(x&lt;mxs)&amp;&amp;(y&gt;=0)&amp;&amp;(y&lt;mys)) c=map[x][y]; else c=0xFF000000; if (DWORD(c&amp;0xFF000000)!=0xFF000000) { r+=c&amp;255; g+=(c&gt;&gt;8)&amp;255; b+=(c&gt;&gt;16)&amp;255; n++; }
        x--; y--; if ((x&gt;=0)&amp;&amp;(x&lt;mxs)&amp;&amp;(y&gt;=0)&amp;&amp;(y&lt;mys)) c=map[x][y]; else c=0xFF000000; if (DWORD(c&amp;0xFF000000)!=0xFF000000) { r+=c&amp;255; g+=(c&gt;&gt;8)&amp;255; b+=(c&gt;&gt;16)&amp;255; n++; }
        x--; y++; if ((x&gt;=0)&amp;&amp;(x&lt;mxs)&amp;&amp;(y&gt;=0)&amp;&amp;(y&lt;mys)) c=map[x][y]; else c=0xFF000000; if (DWORD(c&amp;0xFF000000)!=0xFF000000) { r+=c&amp;255; g+=(c&gt;&gt;8)&amp;255; b+=(c&gt;&gt;16)&amp;255; n++; }
        x++; y++; if ((x&gt;=0)&amp;&amp;(x&lt;mxs)&amp;&amp;(y&gt;=0)&amp;&amp;(y&lt;mys)) c=map[x][y]; else c=0xFF000000; if (DWORD(c&amp;0xFF000000)!=0xFF000000) { r+=c&amp;255; g+=(c&gt;&gt;8)&amp;255; b+=(c&gt;&gt;16)&amp;255; n++; }
        y--;      if (!n) { tmp[x][y]=0xFFFFFFFF; continue; }
        c=((r/n)|((g/n)&lt;&lt;8)|((b/n)&lt;&lt;16))&amp;0x00FFFFFF;
        tmp[x][y]=c;
        }
    // copy tmp back to map
    for (x=0;x&lt;mxs;x++)
     for (y=0;y&lt;mys;y++)
      map[x][y]=tmp[x][y];
    }
void map_draw(TCanvas *can,int x0,int y0)   // just renders actual gradient map onto canvas (can ignore this)
    {
    int x,y,xx,yy;
    for (x=0,xx=x0;x&lt;mxs;x++,xx+=msz)
     for (y=0,yy=y0;y&lt;mys;y++,yy+=msz)
        {
        can-&gt;Pen-&gt;Color=clBlack;
        can-&gt;Brush-&gt;Color=map[x][y]&amp;0x00FFFFFF;
        can-&gt;Rectangle(xx,yy,xx+msz,yy+msz);
        }
    }
//---------------------------------------------------------------------------
</code></pre>

<p>And here the usage (your example):</p>

<pre class="lang-cpp prettyprint-override"><code>// clear backbuffer
bmp-&gt;Canvas-&gt;Brush-&gt;Color=clBlack; 
bmp-&gt;Canvas-&gt;FillRect(TRect(0,0,xs,ys));

// init your gradient with reference points
map_clear();
//  x  y       R     G        B
map[6][0] = (239)|(238&lt;&lt;8)|(185&lt;&lt;16);
map[1][1] = (120)|(131&lt;&lt;8)|(125&lt;&lt;16);
map[6][4] = (184)|(191&lt;&lt;8)|(171&lt;&lt;16);
map[2][6] = (150)|(168&lt;&lt;8)|(158&lt;&lt;16);
map[5][6] = (166)|(180&lt;&lt;8)|(166&lt;&lt;16);
map_draw(bmp-&gt;Canvas,msz,msz); // render result (left)
// bleed
for (int i=0;i&lt;100;i++) map_bleed();
map_draw(bmp-&gt;Canvas,(mxs+2)*msz,msz); // render result (right)

// refresh window with backbufer (anti-flickering)
Main-&gt;Canvas-&gt;Draw(0,0,bmp);
</code></pre>

<p>Again you can ignore all the rendering stuff. The number of bleeds should be 2x bigger then pixels in diagonal so bleeding covers all the pixels. The more iterations the more saturated result I try <code>100</code> just for example and the result looks good .. so I did not play with it anymore...</p>

<p><strong>[Edit2] and here the algorithm for the second approach</strong></p>

<ol>
<li><p><strong>add flags to interpolated matrix</strong></p>

<p>You need to know if the pixel is <code>reference,undefined</code> or <code>interpolated</code>. You can encode this to alpha channel, or use mask (separate 2D matrix).</p></li>
<li><p><strong>bleed/smooth matrix</strong></p>

<p>basically for each non <code>reference</code> pixel compute its new value as average of all non <code>undefined</code> pixels around (4/8 neighbors) and at its position. Do not use <code>undefined</code> pixels and store the computed value to temporary matrix (not messing up next pixels otherwise the bleeding/smoothing would shift the pixels usually diagonally). This way undefined pixels areas will shrink by 1 pixel. After whole matrix is done copy the content of temporary matrix to the original one (or swap pointers).</p></li>
<li><p><strong>loop #2 until result is saturated or specific count of iterations</strong></p>

<p>Number of counts should be at leas 2x bigger then the number of diagonal pixels to propagate reference pixel into whole matrix. The saturation check can be done in <strong>#2</strong> while copying the temp array into original one (can do abs difference between frames and if zero or near it stop).</p></li>
</ol>

python numpy image-processing matrix scipy