1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
|
// ImageComponents
#include <iostream>
#include "Position.h"
#include "ArrayQueue.h"
using namespace std;
void labelComponents(int size, int **pixel);
void outputImage(int size, int **pixel);
int main(){
int ** pixel;
int size = 0;
bool comp = 0;
cout << "Enter image size: ";
cin >> size;
pixel = new int *[size + 2];
for (int i = 1; i <= size; i++)
pixel[i] = new int[size + 2];
cout << "Enter the pixel array in row-major order: ";
for (int i = 1; i <= size; i++)
for (int j = 1; j <= size; j++){
cin >> comp;
pixel[i][j] = comp;
}
labelComponents(size, pixel);
outputImage(size, pixel);
return (0);
}
void labelComponents(int size, int **pixel){
// initialize offsets
Position * offset = new Position[4];
offset[0] = Position(0, 1); // right
offset[1] = Position(1, 0); // down
offset[2] = Position(0, -1); // left
offset[3] = Position(-1, 0); // up
// initialize wall of 0 pixels
for (int i = 0; i <= size + 1; i++)
{
pixel[0][i] = pixel[size + 1][i] = 0; // bottom and top
pixel[i][0] = pixel[i][size + 1] = 0; // left and right
}
int numNbr = 4; // neighbors of a pixel position
ArrayQueue<int> * Q = new ArrayQueue<int>();
Position * nbr = new Position(0, 0);
int id = 1; // component id
// scan all pixels labeling components
for (int r = 1; r <= size; r++) // row r of image
for (int c = 1; c <= size; c++) // column c of image
{
if (pixel[r][c] == 1)
{// new component
pixel[r][c] = ++id; // get next id
Position * here = new Position(r, c);
//do
//{// find rest of component
// for (int i = 0; i < numNbr; i++)
// {// check all neighbors of here
// nbr.getRow() = here.getRow() + offset[i].getRow();
// nbr.getCol() = here.getCol() + offset[i].getCol();
// if (pixel[nbr.getRow()][nbr.getCol()] == 1)
// {// pixel is part of current component
// pixel[nbr.getRow()][nbr.getCol()] = id;
// Q.enqueue(new Position(nbr.getRow(), nbr.getCol()));
// }
// }
// // any unexplored pixels in component?
// here = (Position)Q.dequeue(); // a component pixel
//} while (here != NULL);
} // end of if, for c, and for r
}
} // end of labelComponents
void outputImage(int size, int **pixel){
cout << "The labeled image is: ";
for (int i = 1; i <= size; i++){
cout << endl;
for (int j = 1; j <= size; j++)
cout << (pixel[i][j] + " ");
}
} // end of outputImage
|