我正在尝试编写一个程序,该程序采用二进制图像并使用顺序标记算法标记每个对象,然后将它们着色为彼此不同的灰色。
我相信我的程序是有区别的,但它并没有为不同的颜色着色。我正在使用union / find算法来组合标签。
任何帮助都会很棒:
#include "Image.h"
#include "Image.cpp"
#include "Pgm.cpp"
#include "DisjSets.h"
#include "DisjSets.cpp"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;
int main(int argc, char **argv){
if(argc != 3){
std::cout << "Use as p2 <input image> <output image name>" << std::endl;
return 0;
}
Image *im;
im = new Image;
if(readImage(im, argv[1]) != 0){
cout << "File " << argv[1] << " could not be opened." << endl;
return 0;
}
int labels[im->getNRows()][im->getNCols()];
int linked[im->getNRows()];
for(int x = 0; x < im->getNRows(); x++){
for(int y = 0; y < im->getNCols(); y++){
labels[x][y] = 0; //fill the labels array
linked[x] = 0;
}
}
int current_label = 1;
DisjSets *disj;
disj = new DisjSets(im->getNRows());
int rows = im->getNRows();
int cols = im->getNCols();
for(int r = 0; r < rows; r++)
for(int c = 0; c < cols; c++){
if(r-1<0 || c-1<0){
r++;
c++;
continue;
}
if(im->getPixel(r,c) == 1){
if(im->getPixel(r-1, c) == 0 && im->getPixel(r, c-1) == 0) {
if(labels[r][c] == 0 && labels[r-1][c] == 0 && labels[r][c-1] == 0){
linked[current_label] = current_label;
labels[r][c] = current_label;
current_label += 1;
}
}else{
if((im->getPixel(r-1, c) == 1) && im->getPixel(r, c-1) == 0){
labels[r][c] = labels[r-1][c];
}
else if((im->getPixel(r-1, c) == 0) && im->getPixel(r, c-1) == 1){
labels[r][c] = labels[r][c-1];
}
else if((im->getPixel(r-1, c) == 1) && im->getPixel(r, c-1) == 1){
if(labels[r-1][c] == labels[r][c-1] && labels[r-1][c] != 0 && labels[r][c-1] != 0){
labels[r][c] = labels[r-1][c];
} else {
if(labels[r][c-1] < labels[r-1][c] && labels[r-1][c] != 0 && labels[r][c-1] != 0){
labels[r][c] = labels[r][c-1];
linked[labels[r][c]] = disj->unionSets(linked[labels[r][c]], labels[r-1][c]);
} else if(labels[r][c-1] > labels[r-1][c] && labels[r-1][c] != 0 && labels[r][c-1] != 0){
labels[r][c] = labels[r-1][c];
linked[labels[r][c]] = disj->unionSets(linked[labels[r][c]], labels[r][c-1]);
}
}
}
}
}
}
for(int r = 0; r < im->getNRows(); r++){
for(int c = 0; c < im->getNCols(); c++){
if(labels[r][c] != labels[r+1][c+1] && labels[r][c] != labels[r+1][c] && labels[r][c+1])
cout << labels[r][c] << " ";
if(im->getPixel(r,c) == 1){
labels[r][c] = disj->find(linked[labels[r][c]]);
if(labels[r][c] < 30){
im->setPixel(r,c,1);
} else if(labels[r][c] > 30)
im->setPixel(r,c,2);
}
}
}
if(writeImage(im, argv[2]) != 0){
cout << "Cannot write to file: " << argv[2] << endl;
return 0;
}
return 0;
}
编辑:好的,事实证明,如果我打印我的标签数组,我的所有标签都是0.有人可以解释为什么会这样吗?
EDIT2:我修复它以便填充标签数组,但我不确定如何进行像素颜色更改。还更新了代码