Counting Gems on the Ground
C (gcc), 303 305 326 bytes



All optimizations need to be turned off and only work on 32-bit GCC.

#define r(z,k)for(z=0;z&lt;k;z++)
#define c s[i][j]
x,y,o,p,t,i,j;char**s;h(i,j){!((i&lt;0)+(j&lt;0)+i/x+j/y+c-32)?h(i+1,j),h(i-1,j),h(i,j+1),h(i,j-1),c=0:0;}f(w,e,u,v,a,g)char**a,**g;x=w,y=e,s=a;r(o,x)h(o,0),h(o,y-1);r(p,y)h(0,p),h(x-1,p);w=0;r(o,u-x+1)r(p,v-y+1){t=1;r(i,x)r(j,y)t*=!(c*(c-g[i+o][j+p]));w+=t;}}


The code uses floodfill to replace surrounding spaces with \0 and looks for matches while ignoring \0.

ungolfed and macros calculated (some letters are different from the golfed version, but logic stays the same):

int x, y, o, p, c, d, t;
char **s, **g;
h(int i, int j) {                             // Floodfill function
    if(i&lt;0 || j&lt;0) return;                    // Boundary detection
    if(i&gt;=x || j&gt;=y) return;
    if(s[i][j] != ' ') return;                // Character detection

    s[i][j] = 0;                              // Replace it with \0
    h(i+1, j);
    h(i-1, j)
    h(i  , j+1);
    h(i  , j-1);
}
f(
    int w,    //1st dimension of S
    int e,    //2nd dimension of S
    int u,    //1st dimension of G
    int v     //2nd dimension of G
    char** i, //Input S
    char** j, //Input G
    );
{
    x=w,y=e,s=i,g=j;
    for(o=0; o&lt;x; o++)                        // Replace all surrounding spaces using floodfill
    {
        h(o, 0);                               
        h(o, y-1);
    }
    for(p=0; p&lt;y; p++)
    {
        h(0,   p);
        h(x-1, p);
    }
    w = 0;
    for(o=0; o&lt;=u-x; o++)                     // Main O(w*e*u*v) matching process
        for(p=0; p&lt;=v-y; p++) {
            t=1;
            for(c=0; c&lt;x; c++)
                for(d=0; d&lt;y; d++)
                if(s[c][d]*(s[c][d]-g[c+o][d+p]))
                    t=0;
            w+=t;
        }
}