Here's My Solution.
Written in C#.
The algorithm is a bit creative. And covers all the glitches that might occur during calculations...
For better readability, make sure to copy the code to Visual Studio (C# - Console Application)
using System;
using System.Collections.Generic;
using System.Text;
namespace Pixel
{
class Program
{
static int nmb1 = 0;
static int nmb0 = 0;
public static int[,] matrix = new int[10, 5]
{
{ 1, 1, 0, 1, 0 },
{ 0, 0, 0, 1, 0 },
{ 1, 1, 1, 0, 0 },
{ 0, 1, 0, 1, 0 },
{ 0, 0, 1, 0, 0 },
{ 1, 0, 0, 1, 1 },
{ 0, 0, 0, 1, 1 },
{ 1, 0, 1, 1, 1 },
{ 0, 1, 1, 1, 1 },
{ 1, 0, 0, 0, 0 },
};
public static int[,] matrix2 = new int[12, 7];
static void Main(string[] args)
{
#region // Create a 2nd Matrix [Matrix2] containing Matrix1 but with all Borders set to 0.
for (int i = 1; i < 11; i++)
{
for (int j = 1; j < 6; j++)
{
matrix2[i, j] = matrix[i - 1, j - 1];
}
}
#endregion
#region // Delete All 1's with THREE 0-Neighbours...
for (int i = 1; i < 11; i++)
{
for (int j = 1; j < 6; j++)
{
if (matrix2[i, j] == 1)
{
if (((matrix2[i - 1, j] == 1) && (matrix2[i + 1, j] == 0) && (matrix2[i, j - 1] == 0) && (matrix2[i, j + 1] == 0)) ||
((matrix2[i - 1, j] == 0) && (matrix2[i + 1, j] == 1) && (matrix2[i, j - 1] == 0) && (matrix2[i, j + 1] == 0)) ||
((matrix2[i - 1, j] == 0) && (matrix2[i + 1, j] == 0) && (matrix2[i, j - 1] == 1) && (matrix2[i, j + 1] == 0)) ||
((matrix2[i - 1, j] == 0) && (matrix2[i + 1, j] == 0) && (matrix2[i, j - 1] == 0) && (matrix2[i, j + 1] == 1)))
{
// Replace old Lone 1's with Zeros...
matrix2[i, j] = 0;
}
}
}
}
#endregion
#region // Delete all 1's with ONE or MORE 0-Neighbours...
for (int i = 1; i < 11; i++)
{
for (int j = 1; j < 6; j++)
{
if (matrix2[i, j] == 1)
{
if ((matrix2[i - 1, j] == 1) || (matrix2[i + 1, j] == 1) || (matrix2[i, j - 1] == 1) || (matrix2[i, j + 1] == 1))
matrix2[i, j] = 0;
}
}
}
#endregion
#region // Count All Remaining 1's in the Matrix...
for (int i = 0; i < 12; i++)
{
for (int j = 0; j < 7; j++)
{
if (matrix2[i, j] == 1)
nmb1++;
else
nmb0++;
}
}
#endregion
for (int i = 1; i < 12; i++)
{
for (int j = 1; j < 6; j++)
{
Console.Write(matrix2[i, j].ToString() + " ");
}
Console.Write("\n");
}
Console.Write("The Number Of Objects is: {0}", nmb1);
Console.ReadKey();
}
}
}
1 - Code can be edited to programmatically create the Matrix (Reading from image)
2 - I'm writing a C# Windows Form to read images and create the corresponding Color Matrix from it. (1's being all white pixels - 0's being all other pixels).
3 - The code might look BIG, but in fact it's not at all. Spacing is what makes it that big. I shrunk it to 1/3 of it's original size. But lost it's readability.