Move ARBITRARY_WEDGE tool from experimental

Original name was SEGMENT_BASED_PARTITIONING.

Change-Id: I22d0f89d1c27cd260c391c06146723d1b332aa4d
diff --git a/av1/av1.cmake b/av1/av1.cmake
index 8ac00f3..010c019 100644
--- a/av1/av1.cmake
+++ b/av1/av1.cmake
@@ -262,6 +262,11 @@
               "${AOM_ROOT}/av1/encoder/optical_flow.h")
 endif()
 
+if(CONFIG_ARBITRARY_WEDGE)
+  list(APPEND AOM_AV1_ENCODER_SOURCES "${AOM_ROOT}/av1/encoder/segment_patch.cc"
+              "${AOM_ROOT}/av1/encoder/segment_patch.h")
+endif()
+
 list(APPEND AOM_AV1_COMMON_INTRIN_SSE2
             "${AOM_ROOT}/av1/common/cdef_block_sse2.c"
             "${AOM_ROOT}/av1/common/x86/cfl_sse2.c"
diff --git a/av1/common/reconinter.c b/av1/common/reconinter.c
index 98e64c1..93b737d 100644
--- a/av1/common/reconinter.c
+++ b/av1/common/reconinter.c
@@ -288,10 +288,10 @@
     wedge_masks[BLOCK_32X32] },
   { 0, NULL, NULL, NULL },
   { 0, NULL, NULL, NULL },
+  { CONFIG_ARBITRARY_WEDGE, NULL, NULL, NULL },
   { 0, NULL, NULL, NULL },
   { 0, NULL, NULL, NULL },
-  { 0, NULL, NULL, NULL },
-  { 0, NULL, NULL, NULL },
+  { CONFIG_ARBITRARY_WEDGE, NULL, NULL, NULL },
   { 0, NULL, NULL, NULL },
   { 0, NULL, NULL, NULL },
   { MAX_WEDGE_TYPES, wedge_codebook_16_hgtw, wedge_signflip_lookup[BLOCK_8X32],
@@ -328,6 +328,12 @@
   (void)sb_type;
   switch (comp_data->type) {
     case COMPOUND_WEDGE:
+#if CONFIG_ARBITRARY_WEDGE
+      if (av1_wedge_params_lookup[sb_type].codebook == NULL) {
+        // We are using an arbitrary mask, stored earlier.
+        return comp_data->seg_mask;
+      }
+#endif  // CONFIG_ARBITRARY_WEDGE
       return av1_get_contiguous_soft_mask(comp_data->wedge_index,
                                           comp_data->wedge_sign, sb_type);
     case COMPOUND_DIFFWTD: return comp_data->seg_mask;
@@ -533,6 +539,9 @@
     const wedge_params_type *wedge_params = &av1_wedge_params_lookup[bsize];
     const int wtypes = wedge_params->wedge_types;
     if (wtypes == 0) continue;
+#if CONFIG_ARBITRARY_WEDGE
+    if (wedge_params->codebook == NULL) continue;
+#endif  // CONFIG_ARBITRARY_WEDGE
     const uint8_t *mask;
     const int bw = block_size_wide[bsize];
     const int bh = block_size_high[bsize];
diff --git a/av1/encoder/compound_type.c b/av1/encoder/compound_type.c
index 5438d96..76eb4e1 100644
--- a/av1/encoder/compound_type.c
+++ b/av1/encoder/compound_type.c
@@ -16,6 +16,9 @@
 #include "av1/encoder/motion_search_facade.h"
 #include "av1/encoder/rdopt_utils.h"
 #include "av1/encoder/reconinter_enc.h"
+#if CONFIG_ARBITRARY_WEDGE
+#include "av1/encoder/segment_patch.h"
+#endif  // CONFIG_ARBITRARY_WEDGE
 #include "av1/encoder/tx_search.h"
 
 typedef int64_t (*pick_interinter_mask_type)(
@@ -300,6 +303,70 @@
                 x->mode_costs.wedge_idx_cost[bsize][*best_wedge_index], 0);
 }
 
+#if CONFIG_ARBITRARY_WEDGE
+// Create an arbitrary binary mask using spacial segmentation of this block.
+// This is used for larger blocks, where we don't have pre-defined wedges.
+static int64_t pick_arbitrary_wedge(const AV1_COMP *const cpi,
+                                    MACROBLOCK *const x, const BLOCK_SIZE bsize,
+                                    const int16_t *const residual1,
+                                    const int16_t *const diff10,
+                                    uint8_t *seg_mask, uint64_t *best_sse) {
+  const int bw = block_size_wide[bsize];
+  const int bh = block_size_high[bsize];
+  const int N = bw * bh;
+  *best_sse = UINT64_MAX;
+
+#if DUMP_SEGMENT_MASKS
+  av1_dump_raw_y_plane(x->plane[0].src.buf, bw, bh, x->plane[0].src.stride,
+                       "/tmp/1.source.yuv");
+#endif  // DUMP_SEGMENT_MASKS
+
+  // Get segment mask from helper library.
+  Av1SegmentParams params;
+  av1_get_default_segment_params(&params);
+  params.k = 5000;  // TODO(urvang): Temporary hack to get 2 components.
+  int num_components = -1;
+  av1_get_segments(x->plane[0].src.buf, bw, bh, x->plane[0].src.stride, &params,
+                   seg_mask, &num_components);
+
+  if (num_components >= 2) {
+    // TODO(urvang): Convert more than 2 components to 2 components.
+    if (num_components == 2) {
+      // Convert binary mask with values {0, 1} to one with values {0, 64}.
+      av1_extend_binary_mask_range(seg_mask, bw, bh);
+#if DUMP_SEGMENT_MASKS
+      av1_dump_raw_y_plane(seg_mask, bw, bh, bw, "/tmp/2.binary_mask.yuv");
+#endif  // DUMP_SEGMENT_MASKS
+
+      // Get a smooth mask from the binary mask.
+      av1_apply_box_blur(seg_mask, bw, bh);
+#if DUMP_SEGMENT_MASKS
+      av1_dump_raw_y_plane(seg_mask, bw, bh, bw, "/tmp/3.smooth_mask.yuv");
+#endif  // DUMP_SEGMENT_MASKS
+
+      // Get RDCost
+      *best_sse =
+          av1_wedge_sse_from_residuals(residual1, diff10, seg_mask, N);
+      const MACROBLOCKD *const xd = &x->e_mbd;
+      const int hbd = is_cur_buf_hbd(xd);
+      const int bd_round = hbd ? (xd->bd - 8) * 2 : 0;
+      *best_sse =  ROUND_POWER_OF_TWO(*best_sse, bd_round);
+
+      int rate;
+      int64_t dist;
+      model_rd_sse_fn[MODELRD_TYPE_MASKED_COMPOUND](cpi, x, bsize, 0, *best_sse, N,
+                                                    &rate, &dist);
+      // TODO(urvang): Add cost of signaling wedge itself to 'rate'.
+      const int64_t rd = RDCOST(x->rdmult, rate, dist);
+      // TODO(urvang): Subtrack rate of signaling wedge (like pick_wedge)?
+      return rd;
+    }
+    return INT64_MAX;
+  }
+  return INT64_MAX;
+}
+#endif  // CONFIG_ARBITRARY_WEDGE
+
 static int64_t pick_interinter_wedge(
     const AV1_COMP *const cpi, MACROBLOCK *const x, const BLOCK_SIZE bsize,
     const uint8_t *const p0, const uint8_t *const p1,
@@ -316,6 +383,18 @@
   assert(is_interinter_compound_used(COMPOUND_WEDGE, bsize));
   assert(cpi->common.seq_params.enable_masked_compound);
 
+#if CONFIG_ARBITRARY_WEDGE
+  if (av1_wedge_params_lookup[bsize].codebook == NULL) {
+    // TODO(urvang): Reuse seg_mask or have a different wedge_mask array?
+    mbmi->interinter_comp.seg_mask = xd->seg_mask;
+    rd = pick_arbitrary_wedge(cpi, x, bsize, residual1, diff10,
+                              mbmi->interinter_comp.seg_mask, best_sse);
+    mbmi->interinter_comp.wedge_sign = 0;
+    mbmi->interinter_comp.wedge_index = -1;
+    return rd;
+  }
+#endif  // CONFIG_ARBITRARY_WEDGE
+
   if (cpi->sf.inter_sf.fast_wedge_sign_estimate) {
     wedge_sign = estimate_wedge_sign(cpi, x, bsize, p0, bw, p1, bw);
     rd = pick_wedge_fixed_sign(cpi, x, bsize, residual1, diff10, wedge_sign,
@@ -1046,12 +1125,25 @@
   const COMPOUND_TYPE compound_type = mbmi->interinter_comp.type;
   // This function will be called only for COMPOUND_WEDGE and COMPOUND_DIFFWTD
   if (compound_type == COMPOUND_WEDGE) {
-    return av1_is_wedge_used(mbmi->sb_type)
-               ? av1_cost_literal(1) +
+    if (!av1_is_wedge_used(mbmi->sb_type)) return 0;
+#if CONFIG_ARBITRARY_WEDGE
+    if (av1_wedge_params_lookup[mbmi->sb_type].codebook == NULL) {
+      // We are using an arbitrary mask, so need to run RLE to compute rate.
+      const int bw = block_size_wide[mbmi->sb_type];
+      const int bh = block_size_high[mbmi->sb_type];
+      // For input of length n, max length of run-length encoded string is
+      // 3*n, as storing each length takes 2 bytes.
+      uint8_t rle_buf[3 * MAX_SB_SQUARE];
+      int rle_size = 0;
+      av1_run_length_encode(mbmi->interinter_comp.seg_mask, bw, bh, bw, rle_buf,
+                            &rle_size);
+      return rle_size;
+    }
+#endif  // CONFIG_ARBITRARY_WEDGE
+    return av1_cost_literal(1) +
                      mode_costs
                          ->wedge_idx_cost[mbmi->sb_type]
-                                         [mbmi->interinter_comp.wedge_index]
-               : 0;
+                                         [mbmi->interinter_comp.wedge_index];
   } else {
     assert(compound_type == COMPOUND_DIFFWTD);
     return av1_cost_literal(1);
@@ -1123,8 +1215,13 @@
   uint64_t cur_sse = UINT64_MAX;
   best_rd_cur = pick_interinter_mask[compound_type - COMPOUND_WEDGE](
       cpi, x, bsize, *preds0, *preds1, residual1, diff10, &cur_sse);
+  if (best_rd_cur == INT64_MAX) {
+    *comp_model_rd_cur = INT64_MAX;
+    return INT64_MAX;
+  }
   *rs2 += get_interinter_compound_mask_rate(&x->mode_costs, mbmi);
   best_rd_cur += RDCOST(x->rdmult, *rs2 + rate_mv, 0);
+
   assert(cur_sse != UINT64_MAX);
   int64_t skip_rd_cur = RDCOST(x->rdmult, *rs2 + rate_mv, (cur_sse << 4));
 
diff --git a/av1/encoder/segment_patch.cc b/av1/encoder/segment_patch.cc
new file mode 100644
index 0000000..7080d50
--- /dev/null
+++ b/av1/encoder/segment_patch.cc
@@ -0,0 +1,205 @@
+#include <assert.h>
+#include <unordered_map>
+
+#include "aom_mem/aom_mem.h"
+#include "av1/common/enums.h"
+#include "av1/encoder/segment_patch.h"
+#include "third_party/segment/segment-image.h"
+
+using std::unordered_map;
+
+extern "C" void av1_get_default_segment_params(Av1SegmentParams *params) {
+  params->sigma = 0.5;
+  params->k = 500;
+  params->min_size = 50;
+}
+
+// Convert Y image to RGB image by copying Y channel to all 3 RGB channels.
+static image<rgb> *y_to_rgb(const uint8_t *const input, int width, int height,
+                            int stride) {
+  image<rgb> *output = new image<rgb>(width, height, false);
+
+  for (int j = 0; j < height; j++) {
+    for (int i = 0; i < width; i++) {
+      const int y_channel = input[j * stride + i];
+      imRef(output, i, j).r = y_channel;
+      imRef(output, i, j).g = y_channel;
+      imRef(output, i, j).b = y_channel;
+    }
+  }
+  return output;
+}
+
+// Convert RGB image to an image with segment indices, by picking a segment
+// number for each unique RGB color.
+void rgb_to_segment_index(const image<rgb> *input, uint8_t *const output) {
+  const int width = input->width();
+  const int height = input->height();
+  const int stride = width;
+  // Hash-map for RGB color to an index.
+  unordered_map<uint32_t, uint8_t> color_to_idx;
+  int next_idx = 0;
+  for (int j = 0; j < height; j++) {
+    for (int i = 0; i < width; i++) {
+      const unsigned int r_channel = imRef(input, i, j).r;
+      const unsigned int g_channel = imRef(input, i, j).g;
+      const unsigned int b_channel = imRef(input, i, j).b;
+      const uint32_t color = (r_channel << 16) + (g_channel << 8) + b_channel;
+      if (!color_to_idx.count(color)) {
+        // TODO(urvang): Return error if this happens?
+        assert(next_idx < 256);
+        color_to_idx[color] = next_idx;
+        ++next_idx;
+      }
+      output[j * stride + i] = color_to_idx[color];
+    }
+  }
+}
+
+extern "C" void av1_get_segments(const uint8_t *input, int width, int height,
+                                 int stride, const Av1SegmentParams *seg_params,
+                                 uint8_t *output, int *num_components) {
+  image<rgb> *input_rgb = y_to_rgb(input, width, height, stride);
+  image<rgb> *output_rgb =
+      segment_image(input_rgb, seg_params->sigma, seg_params->k,
+                    seg_params->min_size, num_components);
+  rgb_to_segment_index(output_rgb, output);
+}
+
+// Amend mask with values {0,1} to one with values {0,64}.
+extern "C" void av1_extend_binary_mask_range(uint8_t *const mask, int w,
+                                             int h) {
+  for (int r = 0; r < h; ++r) {
+    for (int c = 0; c < w; ++c) {
+      const int idx = r * w + c;
+      if (mask[idx] == 1) mask[idx] = 64;
+    }
+  }
+}
+
+#define BLUR_KERNEL 7  // Box blur kernel size
+#define BLUR_HALF_KERNEL ((BLUR_KERNEL - 1) / 2)
+#define BLUR_BORDER BLUR_HALF_KERNEL  // Padding needed in each direction.
+extern "C" void av1_apply_box_blur(uint8_t *const mask, int w, int h) {
+  // Pad as needed in each of the 4 directions.
+  const int padded_w = (w + BLUR_BORDER * 2);
+  const int padded_h = (h + BLUR_BORDER * 2);
+  uint8_t *const input_mem =
+      (uint8_t *)aom_malloc(padded_w * padded_h * sizeof(*input_mem));
+  uint8_t *const input = input_mem + padded_w * BLUR_BORDER;
+  for (int r = 0; r < h; ++r) {
+    const uint8_t *const src = mask + r * w;
+    uint8_t *const dst = input + r * padded_w + BLUR_BORDER;
+    memcpy(dst, src, w * sizeof(*mask));
+    for (int c = -BLUR_BORDER; c < 0; ++c) {
+      dst[c] = dst[0];
+    }
+    for (int c = w; c < w + BLUR_BORDER; ++c) {
+      dst[c] = dst[w - 1];
+    }
+  }
+  for (int r = -BLUR_BORDER; r < 0; ++r) {
+    memcpy(&input[r * padded_w], input, padded_w * sizeof(*input));
+  }
+  for (int r = h; r < h + BLUR_BORDER; ++r) {
+    memcpy(&input[r * padded_w], &input[(h - 1) * padded_w],
+           padded_w * sizeof(*input));
+  }
+
+  // 1D filter in horizontal direction.
+  double *const temp_mem =
+      (double *)aom_malloc(w * padded_h * sizeof(*temp_mem));
+  double *const temp = temp_mem + w * BLUR_BORDER;
+  for (int r = -BLUR_BORDER; r < h + BLUR_BORDER; ++r) {
+    const uint8_t *const src = input + r * padded_w + BLUR_BORDER;
+    double *const dst = temp + r * w;
+    // Simple average computation for 0th column.
+    double sum = 0;
+    for (int c = -BLUR_HALF_KERNEL; c <= BLUR_HALF_KERNEL; ++c) {
+      sum += src[c];
+    }
+    dst[0] = sum / BLUR_KERNEL;
+    // Intelligent average computation for rest of the columns.
+    for (int c = 1; c < w; ++c) {
+      sum -= src[c - BLUR_HALF_KERNEL - 1];
+      sum += src[c + BLUR_HALF_KERNEL];
+      dst[c] = sum / BLUR_KERNEL;
+    }
+  }
+  aom_free(input_mem);
+
+  // 1D filter in vertical direction.
+  for (int c = 0; c < w; ++c) {
+    const double *const src = temp + c;
+    uint8_t *const dst = mask + c;
+    // Simple average computation for 0th row.
+    double sum = 0;
+    for (int r = -BLUR_HALF_KERNEL; r <= BLUR_HALF_KERNEL; ++r) {
+      sum += src[r * w];
+    }
+    dst[0] = (uint8_t)round(sum / BLUR_KERNEL);
+    // Intelligent average computation for rest of the rows.
+    for (int r = 1; r < h; ++r) {
+      sum -= src[(r - BLUR_HALF_KERNEL - 1) * w];
+      sum += src[(r + BLUR_HALF_KERNEL) * w];
+      dst[r * w] = (uint8_t)round(sum / BLUR_KERNEL);
+    }
+  }
+  aom_free(temp_mem);
+}
+#undef BLUR_KERNEL
+#undef BLUR_HALF_KERNEL
+#undef BLUR_BORDER
+
+static void write_run_length(int run_len, uint8_t *out, int *out_idx) {
+  assert(run_len > 0);
+  assert(run_len <= MAX_SB_SQUARE);
+  const int range = UINT8_MAX + 1;
+  const int run_len_msb = run_len / range;
+  assert(run_len_msb < range);  // Because run_len <= MAX_SB_SQUARE.
+  out[(*out_idx)++] = (uint8_t)run_len_msb;
+  const int run_len_lsb = run_len % range;
+  assert(run_len_msb < range);
+  out[(*out_idx)++] = (uint8_t)run_len_lsb;
+}
+
+void av1_run_length_encode(const uint8_t *const img, int width, int height,
+                           int stride, uint8_t *out, int *out_size) {
+  int out_idx = 0;
+  uint8_t prev_val = img[0];
+  int run_len = 1;
+
+  for (int r = 0; r < height; ++r) {
+    for (int c = (r == 0) ? 1 : 0; c < width; ++c) {
+      const uint8_t curr_val = img[r * stride + c];
+      if (curr_val == prev_val) {
+        ++run_len;
+      } else {
+        out[out_idx++] = prev_val;
+        write_run_length(run_len, out, &out_idx);
+        run_len = 1;
+        prev_val = curr_val;
+      }
+    }
+  }
+  out[out_idx++] = prev_val;
+  write_run_length(run_len, out, &out_idx);
+  *out_size = out_idx;
+}
+
+#if DUMP_SEGMENT_MASKS
+extern "C" void av1_dump_raw_y_plane(const uint8_t *y, int width, int height,
+                                     int stride, const char *filename) {
+  FILE *f_out = fopen(filename, "wb");
+  if (f_out == NULL) {
+    fprintf(stderr, "Unable to open file %s to write.\n", filename);
+    return;
+  }
+
+  for (int r = 0; r < height; ++r) {
+    fwrite(&y[r * stride], sizeof(*y), width, f_out);
+  }
+
+  fclose(f_out);
+}
+#endif  // DUMP_SEGMENT_MASKS
diff --git a/av1/encoder/segment_patch.h b/av1/encoder/segment_patch.h
new file mode 100644
index 0000000..41fde1a
--- /dev/null
+++ b/av1/encoder/segment_patch.h
@@ -0,0 +1,77 @@
+#ifndef AOM_AV1_ENCODER_SEGMENT_PATCH_H
+#define AOM_AV1_ENCODER_SEGMENT_PATCH_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "aom/aom_integer.h"
+
+// Struct for parameters related to segmentation.
+typedef struct {
+  float sigma;   //  Parameter used for gaussian smoothing of input image.
+  float k;       //  Threshold: larger values result in larger components.
+  int min_size;  // Minimum component size enforced by post-processing.
+} Av1SegmentParams;
+
+// Get reasonable defaults for segmentation parameters.
+void av1_get_default_segment_params(Av1SegmentParams *params);
+
+// Get image segments.
+// Inputs:
+// - input: input image (Y plane)
+// - width: input image width
+// - height: input image height
+// - stride: input image stride
+// - seg_params: segmentation parameters
+// Outputs:
+// - output: segmented output image (Y plane)
+// - num_components: Number of connected components (segments) in the output.
+// Note: Assumes output array is already allocated with size = width * height.
+void av1_get_segments(const uint8_t *input, int width, int height, int stride,
+                      const Av1SegmentParams *seg_params, uint8_t *output,
+                      int *num_components);
+
+// Amend mask with values {0,1} to one with values {0,64}.
+// Input/output:
+// - mask: Binary mask that is modified in-place.
+// Inputs:
+// - w: mask width and also stride
+// - h: mask height
+void av1_extend_binary_mask_range(uint8_t *const mask, int w, int h);
+
+// Applies box blur on 'mask' using an averaging filter.
+// Input/output:
+// - mask: Binary mask with extended range that is modified in-place.
+// Inputs:
+// - w: mask width and also stride
+// - h: mask height
+void av1_apply_box_blur(uint8_t *const mask, int w, int h);
+
+// Run-length encodes 'img'.
+// Inputs:
+// - img: image to be encoded
+// - width: image width
+// - height: image height
+// - stride: image stride
+// Outputs:
+// - out: run-length encoded image. Assumed to be already allocated.
+// - out_size: length of 'out'
+void av1_run_length_encode(const uint8_t *const img, int width, int height,
+                           int stride, uint8_t *out, int *out_size);
+
+#define DUMP_SEGMENT_MASKS 0
+
+#if DUMP_SEGMENT_MASKS
+// Dump raw Y plane to a YUV file.
+// Can be viewed as follows, for example:
+// ffplay -f rawvideo -pixel_format gray -video_size wxh -i <filename>
+void av1_dump_raw_y_plane(const uint8_t *y, int width, int height, int stride,
+                          const char *filename);
+#endif  // DUMP_SEGMENT_MASKS
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  // AOM_AV1_ENCODER_SEGMENT_PATCH_H
diff --git a/build/cmake/aom_config_defaults.cmake b/build/cmake/aom_config_defaults.cmake
index 736205d..b771edb 100644
--- a/build/cmake/aom_config_defaults.cmake
+++ b/build/cmake/aom_config_defaults.cmake
@@ -137,6 +137,8 @@
                    "AV2 experiment flag to remove dist_wtd_comp tool.")
 set_aom_config_var(CONFIG_REMOVE_DUAL_FILTER 1
                    "AV2 experiment flag to remove dual filter.")
+set_aom_config_var(CONFIG_ARBITRARY_WEDGE 0 NUMBER
+                   "AV2 segment based partitioning experiment flag")
 
 #
 # Variables in this section control optional features of the build system.
diff --git a/test/segment_patch_test.cc b/test/segment_patch_test.cc
new file mode 100644
index 0000000..7d7b540
--- /dev/null
+++ b/test/segment_patch_test.cc
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2019, Alliance for Open Media. All rights reserved
+ *
+ * This source code is subject to the terms of the BSD 2 Clause License and
+ * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
+ * was not distributed with this source code in the LICENSE file, you can
+ * obtain it at www.aomedia.org/license/software. If the Alliance for Open
+ * Media Patent License 1.0 was not distributed with this source code in the
+ * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
+ */
+
+#include "av1/encoder/segment_patch.h"
+#include "third_party/googletest/src/googletest/include/gtest/gtest.h"
+#include "test/codec_factory.h"
+#include "test/i420_video_source.h"
+
+namespace {
+
+const int kNumFrames = 10;
+
+}  // namespace
+
+// Test av1_get_segments() API.
+TEST(SegmentPatchTest, get_segments) {
+  libaom_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288, 1,
+                                     30, 0, kNumFrames);
+  Av1SegmentParams params;
+  av1_get_default_segment_params(&params);
+  std::unique_ptr<uint8_t> output;
+
+  ASSERT_NO_FATAL_FAILURE(video.Begin());
+  for (int i = 0; i < kNumFrames; ++i) {
+    const aom_image_t *frame = video.img();
+    ASSERT_TRUE(frame != nullptr)
+        << "Could not read frame# " << i << " from source video";
+    if (i == 0) {
+      // Allocate output buffer.
+      output.reset(new uint8_t[frame->w * frame->h]);
+    }
+    int num_components = -1;
+    av1_get_segments(frame->planes[0], frame->w, frame->h, frame->stride[0],
+                     &params, output.get(), &num_components);
+    ASSERT_GT(num_components, 0);
+    printf("Segmented frame# %d: num_components = %d\n", i, num_components);
+    video.Next();
+  }
+}
diff --git a/test/test.cmake b/test/test.cmake
index 4df1efd..28d7048 100644
--- a/test/test.cmake
+++ b/test/test.cmake
@@ -230,6 +230,11 @@
               "${AOM_ROOT}/test/warp_filter_test_util.h"
               "${AOM_ROOT}/test/webmenc_test.cc")
 
+  if(CONFIG_ARBITRARY_WEDGE)
+    list(APPEND AOM_UNIT_TEST_ENCODER_SOURCES
+                "${AOM_ROOT}/test/segment_patch_test.cc")
+  endif()
+
   if((HAVE_SSE4_1 OR HAVE_NEON))
     list(APPEND AOM_UNIT_TEST_ENCODER_SOURCES
                 "${AOM_ROOT}/test/av1_highbd_iht_test.cc")
diff --git a/third_party/segment/COPYING b/third_party/segment/COPYING
new file mode 100644
index 0000000..d511905
--- /dev/null
+++ b/third_party/segment/COPYING
@@ -0,0 +1,339 @@
+		    GNU GENERAL PUBLIC LICENSE
+		       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+			    Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+		    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+			    NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+		     END OF TERMS AND CONDITIONS
+
+	    How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License along
+    with this program; if not, write to the Free Software Foundation, Inc.,
+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
diff --git a/third_party/segment/README.libaom b/third_party/segment/README.libaom
new file mode 100644
index 0000000..1fba62d
--- /dev/null
+++ b/third_party/segment/README.libaom
@@ -0,0 +1,34 @@
+
+Implementation of the segmentation algorithm described in:
+
+Efficient Graph-Based Image Segmentation
+Pedro F. Felzenszwalb and Daniel P. Huttenlocher
+International Journal of Computer Vision, 59(2) September 2004.
+
+The program takes a color image (PPM format) and produces a segmentation
+with a random color assigned to each region.
+
+1) Type "make" to compile "segment".
+
+2) Run "segment sigma k min input output".
+
+The parameters are: (see the paper for details)
+
+sigma: Used to smooth the input image before segmenting it.
+k: Value for the threshold function.
+min: Minimum component size enforced by post-processing.
+input: Input image.
+output: Output image.
+
+Typical parameters are sigma = 0.5, k = 500, min = 20.
+Larger values for k result in larger components in the result.
+
+******
+
+Local Modifications:
+- Removed Makefile, cpp binary, pnmfile.h
+- Removed unused function
+- Removed unused variables
+- Corrected include statements
+- Fixed float conversion warnings
+- Fixed style warnings
diff --git a/third_party/segment/convolve.h b/third_party/segment/convolve.h
new file mode 100644
index 0000000..71ed0dd
--- /dev/null
+++ b/third_party/segment/convolve.h
@@ -0,0 +1,48 @@
+/*
+Copyright (C) 2006 Pedro Felzenszwalb
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+*/
+
+/* convolution */
+
+#ifndef CONVOLVE_H
+#define CONVOLVE_H
+
+#include <vector>
+#include <algorithm>
+#include <cmath>
+#include "third_party/segment/image.h"
+
+/* convolve src with mask.  dst is flipped! */
+static void convolve_even(image<float> *src, image<float> *dst,
+                          const std::vector<float> &mask) {
+  int width = src->width();
+  int height = src->height();
+  int len = mask.size();
+
+  for (int y = 0; y < height; y++) {
+    for (int x = 0; x < width; x++) {
+      float sum = mask[0] * imRef(src, x, y);
+      for (int i = 1; i < len; i++) {
+        sum += mask[i] * (imRef(src, std::max(x - i, 0), y) +
+                          imRef(src, std::min(x + i, width - 1), y));
+      }
+      imRef(dst, y, x) = sum;
+    }
+  }
+}
+
+#endif
diff --git a/third_party/segment/disjoint-set.h b/third_party/segment/disjoint-set.h
new file mode 100644
index 0000000..5cc4761
--- /dev/null
+++ b/third_party/segment/disjoint-set.h
@@ -0,0 +1,75 @@
+/*
+Copyright (C) 2006 Pedro Felzenszwalb
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+*/
+
+#ifndef DISJOINT_SET
+#define DISJOINT_SET
+
+// disjoint-set forests using union-by-rank and path compression (sort of).
+
+typedef struct {
+  int rank;
+  int p;
+  int size;
+} uni_elt;
+
+class universe {
+ public:
+  explicit universe(int elements);
+  ~universe();
+  int find(int x);
+  void join(int x, int y);
+  int size(int x) const { return elts[x].size; }
+  int num_sets() const { return num; }
+
+ private:
+  uni_elt *elts;
+  int num;
+};
+
+universe::universe(int elements) {
+  elts = new uni_elt[elements];
+  num = elements;
+  for (int i = 0; i < elements; i++) {
+    elts[i].rank = 0;
+    elts[i].size = 1;
+    elts[i].p = i;
+  }
+}
+
+universe::~universe() { delete[] elts; }
+
+int universe::find(int x) {
+  int y = x;
+  while (y != elts[y].p) y = elts[y].p;
+  elts[x].p = y;
+  return y;
+}
+
+void universe::join(int x, int y) {
+  if (elts[x].rank > elts[y].rank) {
+    elts[y].p = x;
+    elts[x].size += elts[y].size;
+  } else {
+    elts[x].p = y;
+    elts[y].size += elts[x].size;
+    if (elts[x].rank == elts[y].rank) elts[y].rank++;
+  }
+  num--;
+}
+
+#endif
diff --git a/third_party/segment/filter.h b/third_party/segment/filter.h
new file mode 100644
index 0000000..b4ea66a
--- /dev/null
+++ b/third_party/segment/filter.h
@@ -0,0 +1,83 @@
+/*
+Copyright (C) 2006 Pedro Felzenszwalb
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+*/
+
+/* simple filters */
+
+#ifndef FILTER_H
+#define FILTER_H
+
+#include <algorithm>
+#include <cmath>
+#include <vector>
+#include "third_party/segment/image.h"
+#include "third_party/segment/misc.h"
+#include "third_party/segment/convolve.h"
+#include "third_party/segment/imconv.h"
+
+#define WIDTH 4.0
+
+/* normalize mask so it integrates to one */
+static void normalize(std::vector<float> *mask) {
+  int len = mask->size();
+  float sum = 0;
+  for (int i = 1; i < len; i++) {
+    sum += (float)fabs((*mask)[i]);
+  }
+  sum = 2 * sum + (float)fabs((*mask)[0]);
+  for (int i = 0; i < len; i++) {
+    (*mask)[i] /= sum;
+  }
+}
+
+/* make filters */
+#define MAKE_FILTER(name, fun)                         \
+  static std::vector<float> make_##name(float sigma) { \
+    sigma = std::max(sigma, 0.01F);                    \
+    int len = (int)ceil(sigma * WIDTH) + 1;            \
+    std::vector<float> mask(len);                      \
+    for (int i = 0; i < len; i++) {                    \
+      mask[i] = fun;                                   \
+    }                                                  \
+    return mask;                                       \
+  }
+
+MAKE_FILTER(fgauss, (float)exp(-0.5 * square(i / sigma)));
+
+/* convolve image with gaussian filter */
+static image<float> *smooth(image<float> *src, float sigma) {
+  std::vector<float> mask = make_fgauss(sigma);
+  normalize(&mask);
+
+  image<float> *tmp = new image<float>(src->height(), src->width(), false);
+  image<float> *dst = new image<float>(src->width(), src->height(), false);
+  convolve_even(src, tmp, mask);
+  convolve_even(tmp, dst, mask);
+
+  delete tmp;
+  return dst;
+}
+
+/* convolve image with gaussian filter */
+image<float> *smooth(image<uchar> *src, float sigma) {
+  image<float> *tmp = imageUCHARtoFLOAT(src);
+  image<float> *dst = smooth(tmp, sigma);
+  delete tmp;
+  return dst;
+}
+
+#endif
diff --git a/third_party/segment/image.h b/third_party/segment/image.h
new file mode 100644
index 0000000..86e65f6
--- /dev/null
+++ b/third_party/segment/image.h
@@ -0,0 +1,96 @@
+/*
+Copyright (C) 2006 Pedro Felzenszwalb
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+*/
+
+/* a simple image class */
+
+#ifndef IMAGE_H
+#define IMAGE_H
+
+#include <cstring>
+
+template <class T>
+class image {
+ public:
+  /* create an image */
+  image(const int width, const int height, const bool init = true);
+
+  /* delete an image */
+  ~image();
+
+  /* init an image */
+  void init(const T &val);
+
+  /* copy an image */
+  image<T> *copy() const;
+
+  /* get the width of an image. */
+  int width() const { return w; }
+
+  /* get the height of an image. */
+  int height() const { return h; }
+
+  /* image data. */
+  T *data;
+
+  /* row pointers. */
+  T **access;
+
+ private:
+  int w, h;
+};
+
+/* use imRef to access image data. */
+#define imRef(im, x, y) (im->access[y][x])
+
+/* use imPtr to get pointer to image data. */
+#define imPtr(im, x, y) &(im->access[y][x])
+
+template <class T>
+image<T>::image(const int width, const int height, const bool init) {
+  w = width;
+  h = height;
+  data = new T[w * h];  // allocate space for image data
+  access = new T *[h];  // allocate space for row pointers
+
+  // initialize row pointers
+  for (int i = 0; i < h; i++) access[i] = data + (i * w);
+
+  if (init) memset(data, 0, w * h * sizeof(T));
+}
+
+template <class T>
+image<T>::~image() {
+  delete[] data;
+  delete[] access;
+}
+
+template <class T>
+void image<T>::init(const T &val) {
+  T *ptr = imPtr(this, 0, 0);
+  T *end = imPtr(this, w - 1, h - 1);
+  while (ptr <= end) *ptr++ = val;
+}
+
+template <class T>
+image<T> *image<T>::copy() const {
+  image<T> *im = new image<T>(w, h, false);
+  memcpy(im->data, data, w * h * sizeof(T));
+  return im;
+}
+
+#endif
diff --git a/third_party/segment/imconv.h b/third_party/segment/imconv.h
new file mode 100644
index 0000000..d24f3ee
--- /dev/null
+++ b/third_party/segment/imconv.h
@@ -0,0 +1,46 @@
+/*
+Copyright (C) 2006 Pedro Felzenszwalb
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+*/
+
+/* image conversion */
+
+#ifndef CONV_H
+#define CONV_H
+
+#include <climits>
+#include "third_party/segment/image.h"
+#include "third_party/segment/imutil.h"
+#include "third_party/segment/misc.h"
+
+#define RED_WEIGHT 0.299
+#define GREEN_WEIGHT 0.587
+#define BLUE_WEIGHT 0.114
+
+static image<float> *imageUCHARtoFLOAT(image<uchar> *input) {
+  int width = input->width();
+  int height = input->height();
+  image<float> *output = new image<float>(width, height, false);
+
+  for (int y = 0; y < height; y++) {
+    for (int x = 0; x < width; x++) {
+      imRef(output, x, y) = imRef(input, x, y);
+    }
+  }
+  return output;
+}
+
+#endif
diff --git a/third_party/segment/imutil.h b/third_party/segment/imutil.h
new file mode 100644
index 0000000..8083155
--- /dev/null
+++ b/third_party/segment/imutil.h
@@ -0,0 +1,63 @@
+/*
+Copyright (C) 2006 Pedro Felzenszwalb
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+*/
+
+/* some image utilities */
+
+#ifndef IMUTIL_H
+#define IMUTIL_H
+
+#include "third_party/segment/image.h"
+#include "third_party/segment/misc.h"
+
+/* compute minimum and maximum value in an image */
+template <class T>
+void min_max(image<T> *im, T *ret_min, T *ret_max) {
+  int width = im->width();
+  int height = im->height();
+
+  T min = imRef(im, 0, 0);
+  T max = imRef(im, 0, 0);
+  for (int y = 0; y < height; y++) {
+    for (int x = 0; x < width; x++) {
+      T val = imRef(im, x, y);
+      if (min > val) min = val;
+      if (max < val) max = val;
+    }
+  }
+
+  *ret_min = min;
+  *ret_max = max;
+}
+
+/* threshold image */
+template <class T>
+image<uchar> *threshold(image<T> *src, int t) {
+  int width = src->width();
+  int height = src->height();
+  image<uchar> *dst = new image<uchar>(width, height);
+
+  for (int y = 0; y < height; y++) {
+    for (int x = 0; x < width; x++) {
+      imRef(dst, x, y) = (imRef(src, x, y) >= t);
+    }
+  }
+
+  return dst;
+}
+
+#endif
diff --git a/third_party/segment/misc.h b/third_party/segment/misc.h
new file mode 100644
index 0000000..5431898
--- /dev/null
+++ b/third_party/segment/misc.h
@@ -0,0 +1,73 @@
+/*
+Copyright (C) 2006 Pedro Felzenszwalb
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+*/
+
+/* random stuff */
+
+#ifndef MISC_H
+#define MISC_H
+
+#include <cmath>
+
+#ifndef M_PI
+#define M_PI 3.141592653589793
+#endif
+
+typedef unsigned char uchar;
+
+typedef struct {
+  uchar r, g, b;
+} rgb;
+
+inline bool operator==(const rgb &a, const rgb &b) {
+  return ((a.r == b.r) && (a.g == b.g) && (a.b == b.b));
+}
+
+template <class T>
+inline T abs(const T &x) {
+  return (x > 0 ? x : -x);
+}
+
+template <class T>
+inline int sign(const T &x) {
+  return (x >= 0 ? 1 : -1);
+}
+
+template <class T>
+inline T square(const T &x) {
+  return x * x;
+}
+
+template <class T>
+inline T bound(const T &x, const T &min, const T &max) {
+  return (x < min ? min : (x > max ? max : x));
+}
+
+template <class T>
+inline bool check_bound(const T &x, const T &min, const T &max) {
+  return ((x < min) || (x > max));
+}
+
+inline int vlib_round(float x) { return (int)(x + 0.5F); }
+
+inline int vlib_round(double x) { return (int)(x + 0.5); }
+
+inline double gaussian(double val, double sigma) {
+  return exp(-square(val / sigma) / 2) / (sqrt(2 * M_PI) * sigma);
+}
+
+#endif
diff --git a/third_party/segment/segment-graph.h b/third_party/segment/segment-graph.h
new file mode 100644
index 0000000..1abe19f
--- /dev/null
+++ b/third_party/segment/segment-graph.h
@@ -0,0 +1,78 @@
+/*
+Copyright (C) 2006 Pedro Felzenszwalb
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+*/
+
+#ifndef SEGMENT_GRAPH
+#define SEGMENT_GRAPH
+
+#include <algorithm>
+#include <cmath>
+#include "third_party/segment/disjoint-set.h"
+
+// threshold function
+#define THRESHOLD(size, c) (c / size)
+
+typedef struct {
+  float w;
+  int a, b;
+} edge;
+
+bool operator<(const edge &a, const edge &b) { return a.w < b.w; }
+
+/*
+ * Segment a graph
+ *
+ * Returns a disjoint-set forest representing the segmentation.
+ *
+ * num_vertices: number of vertices in graph.
+ * num_edges: number of edges in graph
+ * edges: array of edges.
+ * c: constant for treshold function.
+ */
+universe *segment_graph(int num_vertices, int num_edges, edge *edges, float c) {
+  // sort edges by weight
+  std::sort(edges, edges + num_edges);
+
+  // make a disjoint-set forest
+  universe *u = new universe(num_vertices);
+
+  // init thresholds
+  float *threshold = new float[num_vertices];
+  for (int i = 0; i < num_vertices; i++) threshold[i] = THRESHOLD(1, c);
+
+  // for each edge, in non-decreasing weight order...
+  for (int i = 0; i < num_edges; i++) {
+    edge *pedge = &edges[i];
+
+    // components conected by this edge
+    int a = u->find(pedge->a);
+    int b = u->find(pedge->b);
+    if (a != b) {
+      if ((pedge->w <= threshold[a]) && (pedge->w <= threshold[b])) {
+        u->join(a, b);
+        a = u->find(a);
+        threshold[a] = pedge->w + THRESHOLD(u->size(a), c);
+      }
+    }
+  }
+
+  // free up
+  delete[] threshold;
+  return u;
+}
+
+#endif
diff --git a/third_party/segment/segment-image.h b/third_party/segment/segment-image.h
new file mode 100644
index 0000000..b4cb9f3
--- /dev/null
+++ b/third_party/segment/segment-image.h
@@ -0,0 +1,152 @@
+/*
+Copyright (C) 2006 Pedro Felzenszwalb
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+*/
+
+#ifndef SEGMENT_IMAGE
+#define SEGMENT_IMAGE
+
+#include <cstdlib>
+#include "third_party/segment/filter.h"
+#include "third_party/segment/image.h"
+#include "third_party/segment/misc.h"
+#include "third_party/segment/segment-graph.h"
+
+// random color
+rgb random_rgb() {
+  rgb c;
+
+  c.r = (uchar)random();
+  c.g = (uchar)random();
+  c.b = (uchar)random();
+
+  return c;
+}
+
+// dissimilarity measure between pixels
+static inline float diff(image<float> *r, image<float> *g, image<float> *b,
+                         int x1, int y1, int x2, int y2) {
+  return (float)sqrt(square(imRef(r, x1, y1) - imRef(r, x2, y2)) +
+                     square(imRef(g, x1, y1) - imRef(g, x2, y2)) +
+                     square(imRef(b, x1, y1) - imRef(b, x2, y2)));
+}
+
+/*
+ * Segment an image
+ *
+ * Returns a color image representing the segmentation.
+ *
+ * im: image to segment.
+ * sigma: to smooth the image.
+ * c: constant for treshold function.
+ * min_size: minimum component size (enforced by post-processing stage).
+ * num_ccs: number of connected components in the segmentation.
+ */
+image<rgb> *segment_image(image<rgb> *im, float sigma, float c, int min_size,
+                          int *num_ccs) {
+  int width = im->width();
+  int height = im->height();
+
+  image<float> *r = new image<float>(width, height);
+  image<float> *g = new image<float>(width, height);
+  image<float> *b = new image<float>(width, height);
+
+  // smooth each color channel
+  for (int y = 0; y < height; y++) {
+    for (int x = 0; x < width; x++) {
+      imRef(r, x, y) = imRef(im, x, y).r;
+      imRef(g, x, y) = imRef(im, x, y).g;
+      imRef(b, x, y) = imRef(im, x, y).b;
+    }
+  }
+  image<float> *smooth_r = smooth(r, sigma);
+  image<float> *smooth_g = smooth(g, sigma);
+  image<float> *smooth_b = smooth(b, sigma);
+  delete r;
+  delete g;
+  delete b;
+
+  // build graph
+  edge *edges = new edge[width * height * 4];
+  int num = 0;
+  for (int y = 0; y < height; y++) {
+    for (int x = 0; x < width; x++) {
+      if (x < width - 1) {
+        edges[num].a = y * width + x;
+        edges[num].b = y * width + (x + 1);
+        edges[num].w = diff(smooth_r, smooth_g, smooth_b, x, y, x + 1, y);
+        num++;
+      }
+
+      if (y < height - 1) {
+        edges[num].a = y * width + x;
+        edges[num].b = (y + 1) * width + x;
+        edges[num].w = diff(smooth_r, smooth_g, smooth_b, x, y, x, y + 1);
+        num++;
+      }
+
+      if ((x < width - 1) && (y < height - 1)) {
+        edges[num].a = y * width + x;
+        edges[num].b = (y + 1) * width + (x + 1);
+        edges[num].w = diff(smooth_r, smooth_g, smooth_b, x, y, x + 1, y + 1);
+        num++;
+      }
+
+      if ((x < width - 1) && (y > 0)) {
+        edges[num].a = y * width + x;
+        edges[num].b = (y - 1) * width + (x + 1);
+        edges[num].w = diff(smooth_r, smooth_g, smooth_b, x, y, x + 1, y - 1);
+        num++;
+      }
+    }
+  }
+  delete smooth_r;
+  delete smooth_g;
+  delete smooth_b;
+
+  // segment
+  universe *u = segment_graph(width * height, num, edges, c);
+
+  // post process small components
+  for (int i = 0; i < num; i++) {
+    int a = u->find(edges[i].a);
+    int b = u->find(edges[i].b);
+    if ((a != b) && ((u->size(a) < min_size) || (u->size(b) < min_size)))
+      u->join(a, b);
+  }
+  delete[] edges;
+  *num_ccs = u->num_sets();
+
+  image<rgb> *output = new image<rgb>(width, height);
+
+  // pick random colors for each component
+  rgb *colors = new rgb[width * height];
+  for (int i = 0; i < width * height; i++) colors[i] = random_rgb();
+
+  for (int y = 0; y < height; y++) {
+    for (int x = 0; x < width; x++) {
+      int comp = u->find(y * width + x);
+      imRef(output, x, y) = colors[comp];
+    }
+  }
+
+  delete[] colors;
+  delete u;
+
+  return output;
+}
+
+#endif