]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_edgedetect.c
avfilter/vf_edgedetect: add planes option
[ffmpeg] / libavfilter / vf_edgedetect.c
1 /*
2  * Copyright (c) 2012-2014 Clément Bœsch <u pkh me>
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /**
22  * @file
23  * Edge detection filter
24  *
25  * @see https://en.wikipedia.org/wiki/Canny_edge_detector
26  */
27
28 #include "libavutil/avassert.h"
29 #include "libavutil/imgutils.h"
30 #include "libavutil/opt.h"
31 #include "avfilter.h"
32 #include "formats.h"
33 #include "internal.h"
34 #include "video.h"
35
36 #define PLANE_R 0x4
37 #define PLANE_G 0x1
38 #define PLANE_B 0x2
39 #define PLANE_Y 0x1
40 #define PLANE_U 0x2
41 #define PLANE_V 0x4
42 #define PLANE_A 0x8
43
44 enum FilterMode {
45     MODE_WIRES,
46     MODE_COLORMIX,
47     MODE_CANNY,
48     NB_MODE
49 };
50
51 struct plane_info {
52     uint8_t  *tmpbuf;
53     uint16_t *gradients;
54     char     *directions;
55 };
56
57 typedef struct EdgeDetectContext {
58     const AVClass *class;
59     struct plane_info planes[3];
60     int filter_planes;
61     int nb_planes;
62     double   low, high;
63     uint8_t  low_u8, high_u8;
64     int mode;
65 } EdgeDetectContext;
66
67 #define OFFSET(x) offsetof(EdgeDetectContext, x)
68 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
69 static const AVOption edgedetect_options[] = {
70     { "high", "set high threshold", OFFSET(high), AV_OPT_TYPE_DOUBLE, {.dbl=50/255.}, 0, 1, FLAGS },
71     { "low",  "set low threshold",  OFFSET(low),  AV_OPT_TYPE_DOUBLE, {.dbl=20/255.}, 0, 1, FLAGS },
72     { "mode", "set mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=MODE_WIRES}, 0, NB_MODE-1, FLAGS, "mode" },
73         { "wires",    "white/gray wires on black",  0, AV_OPT_TYPE_CONST, {.i64=MODE_WIRES},    INT_MIN, INT_MAX, FLAGS, "mode" },
74         { "colormix", "mix colors",                 0, AV_OPT_TYPE_CONST, {.i64=MODE_COLORMIX}, INT_MIN, INT_MAX, FLAGS, "mode" },
75         { "canny",    "detect edges on planes",     0, AV_OPT_TYPE_CONST, {.i64=MODE_CANNY},    INT_MIN, INT_MAX, FLAGS, "mode" },
76     { "planes", "set planes to filter",  OFFSET(filter_planes), AV_OPT_TYPE_FLAGS, {.i64=7}, 1, 0x7, FLAGS, "flags" },
77         { "y", "filter luma plane",  0, AV_OPT_TYPE_CONST, {.i64=PLANE_Y}, 0, 0, FLAGS, "flags" },
78         { "u", "filter u plane",     0, AV_OPT_TYPE_CONST, {.i64=PLANE_U}, 0, 0, FLAGS, "flags" },
79         { "v", "filter v plane",     0, AV_OPT_TYPE_CONST, {.i64=PLANE_V}, 0, 0, FLAGS, "flags" },
80         { "r", "filter red plane",   0, AV_OPT_TYPE_CONST, {.i64=PLANE_R}, 0, 0, FLAGS, "flags" },
81         { "g", "filter green plane", 0, AV_OPT_TYPE_CONST, {.i64=PLANE_G}, 0, 0, FLAGS, "flags" },
82         { "b", "filter blue plane",  0, AV_OPT_TYPE_CONST, {.i64=PLANE_B}, 0, 0, FLAGS, "flags" },
83     { NULL }
84 };
85
86 AVFILTER_DEFINE_CLASS(edgedetect);
87
88 static av_cold int init(AVFilterContext *ctx)
89 {
90     EdgeDetectContext *edgedetect = ctx->priv;
91
92     edgedetect->low_u8  = edgedetect->low  * 255. + .5;
93     edgedetect->high_u8 = edgedetect->high * 255. + .5;
94     return 0;
95 }
96
97 static int query_formats(AVFilterContext *ctx)
98 {
99     const EdgeDetectContext *edgedetect = ctx->priv;
100     static const enum AVPixelFormat wires_pix_fmts[] = {AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE};
101     static const enum AVPixelFormat canny_pix_fmts[] = {AV_PIX_FMT_YUV444P, AV_PIX_FMT_GBRP, AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE};
102     static const enum AVPixelFormat colormix_pix_fmts[] = {AV_PIX_FMT_GBRP, AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE};
103     AVFilterFormats *fmts_list;
104     const enum AVPixelFormat *pix_fmts = NULL;
105
106     if (edgedetect->mode == MODE_WIRES) {
107         pix_fmts = wires_pix_fmts;
108     } else if (edgedetect->mode == MODE_COLORMIX) {
109         pix_fmts = colormix_pix_fmts;
110     } else if (edgedetect->mode == MODE_CANNY) {
111         pix_fmts = canny_pix_fmts;
112     } else {
113         av_assert0(0);
114     }
115     fmts_list = ff_make_format_list(pix_fmts);
116     if (!fmts_list)
117         return AVERROR(ENOMEM);
118     return ff_set_common_formats(ctx, fmts_list);
119 }
120
121 static int config_props(AVFilterLink *inlink)
122 {
123     int p;
124     AVFilterContext *ctx = inlink->dst;
125     EdgeDetectContext *edgedetect = ctx->priv;
126
127     edgedetect->nb_planes = inlink->format == AV_PIX_FMT_GRAY8 ? 1 : 3;
128     for (p = 0; p < edgedetect->nb_planes; p++) {
129         struct plane_info *plane = &edgedetect->planes[p];
130
131         plane->tmpbuf     = av_malloc(inlink->w * inlink->h);
132         plane->gradients  = av_calloc(inlink->w * inlink->h, sizeof(*plane->gradients));
133         plane->directions = av_malloc(inlink->w * inlink->h);
134         if (!plane->tmpbuf || !plane->gradients || !plane->directions)
135             return AVERROR(ENOMEM);
136     }
137     return 0;
138 }
139
140 static void gaussian_blur(AVFilterContext *ctx, int w, int h,
141                                 uint8_t *dst, int dst_linesize,
142                           const uint8_t *src, int src_linesize)
143 {
144     int i, j;
145
146     memcpy(dst, src, w); dst += dst_linesize; src += src_linesize;
147     memcpy(dst, src, w); dst += dst_linesize; src += src_linesize;
148     for (j = 2; j < h - 2; j++) {
149         dst[0] = src[0];
150         dst[1] = src[1];
151         for (i = 2; i < w - 2; i++) {
152             /* Gaussian mask of size 5x5 with sigma = 1.4 */
153             dst[i] = ((src[-2*src_linesize + i-2] + src[2*src_linesize + i-2]) * 2
154                     + (src[-2*src_linesize + i-1] + src[2*src_linesize + i-1]) * 4
155                     + (src[-2*src_linesize + i  ] + src[2*src_linesize + i  ]) * 5
156                     + (src[-2*src_linesize + i+1] + src[2*src_linesize + i+1]) * 4
157                     + (src[-2*src_linesize + i+2] + src[2*src_linesize + i+2]) * 2
158
159                     + (src[  -src_linesize + i-2] + src[  src_linesize + i-2]) *  4
160                     + (src[  -src_linesize + i-1] + src[  src_linesize + i-1]) *  9
161                     + (src[  -src_linesize + i  ] + src[  src_linesize + i  ]) * 12
162                     + (src[  -src_linesize + i+1] + src[  src_linesize + i+1]) *  9
163                     + (src[  -src_linesize + i+2] + src[  src_linesize + i+2]) *  4
164
165                     + src[i-2] *  5
166                     + src[i-1] * 12
167                     + src[i  ] * 15
168                     + src[i+1] * 12
169                     + src[i+2] *  5) / 159;
170         }
171         dst[i    ] = src[i    ];
172         dst[i + 1] = src[i + 1];
173
174         dst += dst_linesize;
175         src += src_linesize;
176     }
177     memcpy(dst, src, w); dst += dst_linesize; src += src_linesize;
178     memcpy(dst, src, w);
179 }
180
181 enum {
182     DIRECTION_45UP,
183     DIRECTION_45DOWN,
184     DIRECTION_HORIZONTAL,
185     DIRECTION_VERTICAL,
186 };
187
188 static int get_rounded_direction(int gx, int gy)
189 {
190     /* reference angles:
191      *   tan( pi/8) = sqrt(2)-1
192      *   tan(3pi/8) = sqrt(2)+1
193      * Gy/Gx is the tangent of the angle (theta), so Gy/Gx is compared against
194      * <ref-angle>, or more simply Gy against <ref-angle>*Gx
195      *
196      * Gx and Gy bounds = [-1020;1020], using 16-bit arithmetic:
197      *   round((sqrt(2)-1) * (1<<16)) =  27146
198      *   round((sqrt(2)+1) * (1<<16)) = 158218
199      */
200     if (gx) {
201         int tanpi8gx, tan3pi8gx;
202
203         if (gx < 0)
204             gx = -gx, gy = -gy;
205         gy <<= 16;
206         tanpi8gx  =  27146 * gx;
207         tan3pi8gx = 158218 * gx;
208         if (gy > -tan3pi8gx && gy < -tanpi8gx)  return DIRECTION_45UP;
209         if (gy > -tanpi8gx  && gy <  tanpi8gx)  return DIRECTION_HORIZONTAL;
210         if (gy >  tanpi8gx  && gy <  tan3pi8gx) return DIRECTION_45DOWN;
211     }
212     return DIRECTION_VERTICAL;
213 }
214
215 static void sobel(int w, int h,
216                        uint16_t *dst, int dst_linesize,
217                          int8_t *dir, int dir_linesize,
218                   const uint8_t *src, int src_linesize)
219 {
220     int i, j;
221
222     for (j = 1; j < h - 1; j++) {
223         dst += dst_linesize;
224         dir += dir_linesize;
225         src += src_linesize;
226         for (i = 1; i < w - 1; i++) {
227             const int gx =
228                 -1*src[-src_linesize + i-1] + 1*src[-src_linesize + i+1]
229                 -2*src[                i-1] + 2*src[                i+1]
230                 -1*src[ src_linesize + i-1] + 1*src[ src_linesize + i+1];
231             const int gy =
232                 -1*src[-src_linesize + i-1] + 1*src[ src_linesize + i-1]
233                 -2*src[-src_linesize + i  ] + 2*src[ src_linesize + i  ]
234                 -1*src[-src_linesize + i+1] + 1*src[ src_linesize + i+1];
235
236             dst[i] = FFABS(gx) + FFABS(gy);
237             dir[i] = get_rounded_direction(gx, gy);
238         }
239     }
240 }
241
242 static void non_maximum_suppression(int w, int h,
243                                           uint8_t  *dst, int dst_linesize,
244                                     const  int8_t  *dir, int dir_linesize,
245                                     const uint16_t *src, int src_linesize)
246 {
247     int i, j;
248
249 #define COPY_MAXIMA(ay, ax, by, bx) do {                \
250     if (src[i] > src[(ay)*src_linesize + i+(ax)] &&     \
251         src[i] > src[(by)*src_linesize + i+(bx)])       \
252         dst[i] = av_clip_uint8(src[i]);                 \
253 } while (0)
254
255     for (j = 1; j < h - 1; j++) {
256         dst += dst_linesize;
257         dir += dir_linesize;
258         src += src_linesize;
259         for (i = 1; i < w - 1; i++) {
260             switch (dir[i]) {
261             case DIRECTION_45UP:        COPY_MAXIMA( 1, -1, -1,  1); break;
262             case DIRECTION_45DOWN:      COPY_MAXIMA(-1, -1,  1,  1); break;
263             case DIRECTION_HORIZONTAL:  COPY_MAXIMA( 0, -1,  0,  1); break;
264             case DIRECTION_VERTICAL:    COPY_MAXIMA(-1,  0,  1,  0); break;
265             }
266         }
267     }
268 }
269
270 static void double_threshold(int low, int high, int w, int h,
271                                    uint8_t *dst, int dst_linesize,
272                              const uint8_t *src, int src_linesize)
273 {
274     int i, j;
275
276     for (j = 0; j < h; j++) {
277         for (i = 0; i < w; i++) {
278             if (src[i] > high) {
279                 dst[i] = src[i];
280                 continue;
281             }
282
283             if ((!i || i == w - 1 || !j || j == h - 1) &&
284                 src[i] > low &&
285                 (src[-src_linesize + i-1] > high ||
286                  src[-src_linesize + i  ] > high ||
287                  src[-src_linesize + i+1] > high ||
288                  src[                i-1] > high ||
289                  src[                i+1] > high ||
290                  src[ src_linesize + i-1] > high ||
291                  src[ src_linesize + i  ] > high ||
292                  src[ src_linesize + i+1] > high))
293                 dst[i] = src[i];
294             else
295                 dst[i] = 0;
296         }
297         dst += dst_linesize;
298         src += src_linesize;
299     }
300 }
301
302 static void color_mix(int w, int h,
303                             uint8_t *dst, int dst_linesize,
304                       const uint8_t *src, int src_linesize)
305 {
306     int i, j;
307
308     for (j = 0; j < h; j++) {
309         for (i = 0; i < w; i++)
310             dst[i] = (dst[i] + src[i]) >> 1;
311         dst += dst_linesize;
312         src += src_linesize;
313     }
314 }
315
316 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
317 {
318     AVFilterContext *ctx = inlink->dst;
319     EdgeDetectContext *edgedetect = ctx->priv;
320     AVFilterLink *outlink = ctx->outputs[0];
321     int p, direct = 0;
322     AVFrame *out;
323
324     if (edgedetect->mode != MODE_COLORMIX && av_frame_is_writable(in)) {
325         direct = 1;
326         out = in;
327     } else {
328         out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
329         if (!out) {
330             av_frame_free(&in);
331             return AVERROR(ENOMEM);
332         }
333         av_frame_copy_props(out, in);
334     }
335
336     for (p = 0; p < edgedetect->nb_planes; p++) {
337         struct plane_info *plane = &edgedetect->planes[p];
338         uint8_t  *tmpbuf     = plane->tmpbuf;
339         uint16_t *gradients  = plane->gradients;
340         int8_t   *directions = plane->directions;
341
342         if (!((1 << p) & edgedetect->filter_planes)) {
343             if (!direct)
344                 av_image_copy_plane(out->data[p], out->linesize[p],
345                                     in->data[p], in->linesize[p],
346                                     inlink->w, inlink->h);
347             continue;
348         }
349
350         /* gaussian filter to reduce noise  */
351         gaussian_blur(ctx, inlink->w, inlink->h,
352                       tmpbuf,      inlink->w,
353                       in->data[p], in->linesize[p]);
354
355         /* compute the 16-bits gradients and directions for the next step */
356         sobel(inlink->w, inlink->h,
357               gradients, inlink->w,
358               directions,inlink->w,
359               tmpbuf,    inlink->w);
360
361         /* non_maximum_suppression() will actually keep & clip what's necessary and
362          * ignore the rest, so we need a clean output buffer */
363         memset(tmpbuf, 0, inlink->w * inlink->h);
364         non_maximum_suppression(inlink->w, inlink->h,
365                                 tmpbuf,    inlink->w,
366                                 directions,inlink->w,
367                                 gradients, inlink->w);
368
369         /* keep high values, or low values surrounded by high values */
370         double_threshold(edgedetect->low_u8, edgedetect->high_u8,
371                          inlink->w, inlink->h,
372                          out->data[p], out->linesize[p],
373                          tmpbuf,       inlink->w);
374
375         if (edgedetect->mode == MODE_COLORMIX) {
376             color_mix(inlink->w, inlink->h,
377                       out->data[p], out->linesize[p],
378                       in->data[p], in->linesize[p]);
379         }
380     }
381
382     if (!direct)
383         av_frame_free(&in);
384     return ff_filter_frame(outlink, out);
385 }
386
387 static av_cold void uninit(AVFilterContext *ctx)
388 {
389     int p;
390     EdgeDetectContext *edgedetect = ctx->priv;
391
392     for (p = 0; p < edgedetect->nb_planes; p++) {
393         struct plane_info *plane = &edgedetect->planes[p];
394         av_freep(&plane->tmpbuf);
395         av_freep(&plane->gradients);
396         av_freep(&plane->directions);
397     }
398 }
399
400 static const AVFilterPad edgedetect_inputs[] = {
401     {
402         .name         = "default",
403         .type         = AVMEDIA_TYPE_VIDEO,
404         .config_props = config_props,
405         .filter_frame = filter_frame,
406     },
407     { NULL }
408 };
409
410 static const AVFilterPad edgedetect_outputs[] = {
411     {
412         .name = "default",
413         .type = AVMEDIA_TYPE_VIDEO,
414     },
415     { NULL }
416 };
417
418 AVFilter ff_vf_edgedetect = {
419     .name          = "edgedetect",
420     .description   = NULL_IF_CONFIG_SMALL("Detect and draw edge."),
421     .priv_size     = sizeof(EdgeDetectContext),
422     .init          = init,
423     .uninit        = uninit,
424     .query_formats = query_formats,
425     .inputs        = edgedetect_inputs,
426     .outputs       = edgedetect_outputs,
427     .priv_class    = &edgedetect_class,
428     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC,
429 };