26 #include "segment-graph.h"
40 static inline float diff(image<float> *r, image<float> *g, image<float> *b,
41 int x1,
int y1,
int x2,
int y2) {
42 return sqrt(square(imRef(r, x1, y1)-imRef(r, x2, y2)) +
43 square(imRef(g, x1, y1)-imRef(g, x2, y2)) +
44 square(imRef(b, x1, y1)-imRef(b, x2, y2)));
58 image<rgb> *segment_image(image<rgb> *im,
float sigma,
float c,
int min_size,
60 int width = im->width();
61 int height = im->height();
63 image<float> *r =
new image<float>(width, height);
64 image<float> *g =
new image<float>(width, height);
65 image<float> *b =
new image<float>(width, height);
68 for (
int y = 0; y < height; y++) {
69 for (
int x = 0; x < width; x++) {
70 imRef(r, x, y) = imRef(im, x, y).r;
71 imRef(g, x, y) = imRef(im, x, y).g;
72 imRef(b, x, y) = imRef(im, x, y).b;
75 image<float> *smooth_r = smooth(r, sigma);
76 image<float> *smooth_g = smooth(g, sigma);
77 image<float> *smooth_b = smooth(b, sigma);
83 edge *edges =
new edge[width*height*4];
85 for (
int y = 0; y < height; y++) {
86 for (
int x = 0; x < width; x++) {
88 edges[num].a = y * width + x;
89 edges[num].b = y * width + (x+1);
90 edges[num].w = diff(smooth_r, smooth_g, smooth_b, x, y, x+1, y);
95 edges[num].a = y * width + x;
96 edges[num].b = (y+1) * width + x;
97 edges[num].w = diff(smooth_r, smooth_g, smooth_b, x, y, x, y+1);
101 if ((x < width-1) && (y < height-1)) {
102 edges[num].a = y * width + x;
103 edges[num].b = (y+1) * width + (x+1);
104 edges[num].w = diff(smooth_r, smooth_g, smooth_b, x, y, x+1, y+1);
108 if ((x < width-1) && (y > 0)) {
109 edges[num].a = y * width + x;
110 edges[num].b = (y-1) * width + (x+1);
111 edges[num].w = diff(smooth_r, smooth_g, smooth_b, x, y, x+1, y-1);
121 universe *u = segment_graph(width*height, num, edges, c);
124 for (
int i = 0; i < num; i++) {
125 int a = u->find(edges[i].a);
126 int b = u->find(edges[i].b);
127 if ((a != b) && ((u->size(a) < min_size) || (u->size(b) < min_size)))
131 *num_ccs = u->num_sets();
133 image<rgb> *output =
new image<rgb>(width, height);
136 rgb *colors =
new rgb[width*height];
137 for (
int i = 0; i < width*height; i++)
138 colors[i] = random_rgb();
140 for (
int y = 0; y < height; y++) {
141 for (
int x = 0; x < width; x++) {
142 int comp = u->find(y * width + x);
143 imRef(output, x, y) = colors[comp];