]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_libopencv.c
Merge commit 'b8de14bcdf876c7e236a6dd2ad35342ff4b42cf8'
[ffmpeg] / libavfilter / vf_libopencv.c
1 /*
2  * Copyright (c) 2010 Stefano Sabatini
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  * libopencv wrapper functions
24  */
25
26 #include "config.h"
27 #if HAVE_OPENCV2_CORE_CORE_C_H
28 #include <opencv2/core/core_c.h>
29 #include <opencv2/imgproc/imgproc_c.h>
30 #else
31 #include <opencv/cv.h>
32 #include <opencv/cxcore.h>
33 #endif
34 #include "libavutil/avstring.h"
35 #include "libavutil/common.h"
36 #include "libavutil/file.h"
37 #include "libavutil/opt.h"
38 #include "avfilter.h"
39 #include "formats.h"
40 #include "internal.h"
41 #include "video.h"
42
43 static void fill_iplimage_from_frame(IplImage *img, const AVFrame *frame, enum AVPixelFormat pixfmt)
44 {
45     IplImage *tmpimg;
46     int depth, channels_nb;
47
48     if      (pixfmt == AV_PIX_FMT_GRAY8) { depth = IPL_DEPTH_8U;  channels_nb = 1; }
49     else if (pixfmt == AV_PIX_FMT_BGRA)  { depth = IPL_DEPTH_8U;  channels_nb = 4; }
50     else if (pixfmt == AV_PIX_FMT_BGR24) { depth = IPL_DEPTH_8U;  channels_nb = 3; }
51     else return;
52
53     tmpimg = cvCreateImageHeader((CvSize){frame->width, frame->height}, depth, channels_nb);
54     *img = *tmpimg;
55     img->imageData = img->imageDataOrigin = frame->data[0];
56     img->dataOrder = IPL_DATA_ORDER_PIXEL;
57     img->origin    = IPL_ORIGIN_TL;
58     img->widthStep = frame->linesize[0];
59 }
60
61 static void fill_frame_from_iplimage(AVFrame *frame, const IplImage *img, enum AVPixelFormat pixfmt)
62 {
63     frame->linesize[0] = img->widthStep;
64     frame->data[0]     = img->imageData;
65 }
66
67 static int query_formats(AVFilterContext *ctx)
68 {
69     static const enum AVPixelFormat pix_fmts[] = {
70         AV_PIX_FMT_BGR24, AV_PIX_FMT_BGRA, AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE
71     };
72     AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
73     if (!fmts_list)
74         return AVERROR(ENOMEM);
75     return ff_set_common_formats(ctx, fmts_list);
76 }
77
78 typedef struct OCVContext {
79     const AVClass *class;
80     char *name;
81     char *params;
82     int (*init)(AVFilterContext *ctx, const char *args);
83     void (*uninit)(AVFilterContext *ctx);
84     void (*end_frame_filter)(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg);
85     void *priv;
86 } OCVContext;
87
88 typedef struct SmoothContext {
89     int type;
90     int    param1, param2;
91     double param3, param4;
92 } SmoothContext;
93
94 static av_cold int smooth_init(AVFilterContext *ctx, const char *args)
95 {
96     OCVContext *s = ctx->priv;
97     SmoothContext *smooth = s->priv;
98     char type_str[128] = "gaussian";
99
100     smooth->param1 = 3;
101     smooth->param2 = 0;
102     smooth->param3 = 0.0;
103     smooth->param4 = 0.0;
104
105     if (args)
106         sscanf(args, "%127[^|]|%d|%d|%lf|%lf", type_str, &smooth->param1, &smooth->param2, &smooth->param3, &smooth->param4);
107
108     if      (!strcmp(type_str, "blur"         )) smooth->type = CV_BLUR;
109     else if (!strcmp(type_str, "blur_no_scale")) smooth->type = CV_BLUR_NO_SCALE;
110     else if (!strcmp(type_str, "median"       )) smooth->type = CV_MEDIAN;
111     else if (!strcmp(type_str, "gaussian"     )) smooth->type = CV_GAUSSIAN;
112     else if (!strcmp(type_str, "bilateral"    )) smooth->type = CV_BILATERAL;
113     else {
114         av_log(ctx, AV_LOG_ERROR, "Smoothing type '%s' unknown.\n", type_str);
115         return AVERROR(EINVAL);
116     }
117
118     if (smooth->param1 < 0 || !(smooth->param1%2)) {
119         av_log(ctx, AV_LOG_ERROR,
120                "Invalid value '%d' for param1, it has to be a positive odd number\n",
121                smooth->param1);
122         return AVERROR(EINVAL);
123     }
124     if ((smooth->type == CV_BLUR || smooth->type == CV_BLUR_NO_SCALE || smooth->type == CV_GAUSSIAN) &&
125         (smooth->param2 < 0 || (smooth->param2 && !(smooth->param2%2)))) {
126         av_log(ctx, AV_LOG_ERROR,
127                "Invalid value '%d' for param2, it has to be zero or a positive odd number\n",
128                smooth->param2);
129         return AVERROR(EINVAL);
130     }
131
132     av_log(ctx, AV_LOG_VERBOSE, "type:%s param1:%d param2:%d param3:%f param4:%f\n",
133            type_str, smooth->param1, smooth->param2, smooth->param3, smooth->param4);
134     return 0;
135 }
136
137 static void smooth_end_frame_filter(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg)
138 {
139     OCVContext *s = ctx->priv;
140     SmoothContext *smooth = s->priv;
141     cvSmooth(inimg, outimg, smooth->type, smooth->param1, smooth->param2, smooth->param3, smooth->param4);
142 }
143
144 static int read_shape_from_file(int *cols, int *rows, int **values, const char *filename,
145                                 void *log_ctx)
146 {
147     uint8_t *buf, *p, *pend;
148     size_t size;
149     int ret, i, j, w;
150
151     if ((ret = av_file_map(filename, &buf, &size, 0, log_ctx)) < 0)
152         return ret;
153
154     /* prescan file to get the number of lines and the maximum width */
155     w = 0;
156     for (i = 0; i < size; i++) {
157         if (buf[i] == '\n') {
158             if (*rows == INT_MAX) {
159                 av_log(log_ctx, AV_LOG_ERROR, "Overflow on the number of rows in the file\n");
160                 return AVERROR_INVALIDDATA;
161             }
162             ++(*rows);
163             *cols = FFMAX(*cols, w);
164             w = 0;
165         } else if (w == INT_MAX) {
166             av_log(log_ctx, AV_LOG_ERROR, "Overflow on the number of columns in the file\n");
167             return AVERROR_INVALIDDATA;
168         }
169         w++;
170     }
171     if (*rows > (SIZE_MAX / sizeof(int) / *cols)) {
172         av_log(log_ctx, AV_LOG_ERROR, "File with size %dx%d is too big\n",
173                *rows, *cols);
174         return AVERROR_INVALIDDATA;
175     }
176     if (!(*values = av_mallocz_array(sizeof(int) * *rows, *cols)))
177         return AVERROR(ENOMEM);
178
179     /* fill *values */
180     p    = buf;
181     pend = buf + size-1;
182     for (i = 0; i < *rows; i++) {
183         for (j = 0;; j++) {
184             if (p > pend || *p == '\n') {
185                 p++;
186                 break;
187             } else
188                 (*values)[*cols*i + j] = !!av_isgraph(*(p++));
189         }
190     }
191     av_file_unmap(buf, size);
192
193 #ifdef DEBUG
194     {
195         char *line;
196         if (!(line = av_malloc(*cols + 1)))
197             return AVERROR(ENOMEM);
198         for (i = 0; i < *rows; i++) {
199             for (j = 0; j < *cols; j++)
200                 line[j] = (*values)[i * *cols + j] ? '@' : ' ';
201             line[j] = 0;
202             av_log(log_ctx, AV_LOG_DEBUG, "%3d: %s\n", i, line);
203         }
204         av_free(line);
205     }
206 #endif
207
208     return 0;
209 }
210
211 static int parse_iplconvkernel(IplConvKernel **kernel, char *buf, void *log_ctx)
212 {
213     char shape_filename[128] = "", shape_str[32] = "rect";
214     int cols = 0, rows = 0, anchor_x = 0, anchor_y = 0, shape = CV_SHAPE_RECT;
215     int *values = NULL, ret = 0;
216
217     sscanf(buf, "%dx%d+%dx%d/%32[^=]=%127s", &cols, &rows, &anchor_x, &anchor_y, shape_str, shape_filename);
218
219     if      (!strcmp(shape_str, "rect"   )) shape = CV_SHAPE_RECT;
220     else if (!strcmp(shape_str, "cross"  )) shape = CV_SHAPE_CROSS;
221     else if (!strcmp(shape_str, "ellipse")) shape = CV_SHAPE_ELLIPSE;
222     else if (!strcmp(shape_str, "custom" )) {
223         shape = CV_SHAPE_CUSTOM;
224         if ((ret = read_shape_from_file(&cols, &rows, &values, shape_filename, log_ctx)) < 0)
225             return ret;
226     } else {
227         av_log(log_ctx, AV_LOG_ERROR,
228                "Shape unspecified or type '%s' unknown.\n", shape_str);
229         ret = AVERROR(EINVAL);
230         goto out;
231     }
232
233     if (rows <= 0 || cols <= 0) {
234         av_log(log_ctx, AV_LOG_ERROR,
235                "Invalid non-positive values for shape size %dx%d\n", cols, rows);
236         ret = AVERROR(EINVAL);
237         goto out;
238     }
239
240     if (anchor_x < 0 || anchor_y < 0 || anchor_x >= cols || anchor_y >= rows) {
241         av_log(log_ctx, AV_LOG_ERROR,
242                "Shape anchor %dx%d is not inside the rectangle with size %dx%d.\n",
243                anchor_x, anchor_y, cols, rows);
244         ret = AVERROR(EINVAL);
245         goto out;
246     }
247
248     *kernel = cvCreateStructuringElementEx(cols, rows, anchor_x, anchor_y, shape, values);
249     if (!*kernel) {
250         ret = AVERROR(ENOMEM);
251         goto out;
252     }
253
254     av_log(log_ctx, AV_LOG_VERBOSE, "Structuring element: w:%d h:%d x:%d y:%d shape:%s\n",
255            rows, cols, anchor_x, anchor_y, shape_str);
256 out:
257     av_freep(&values);
258     return ret;
259 }
260
261 typedef struct DilateContext {
262     int nb_iterations;
263     IplConvKernel *kernel;
264 } DilateContext;
265
266 static av_cold int dilate_init(AVFilterContext *ctx, const char *args)
267 {
268     OCVContext *s = ctx->priv;
269     DilateContext *dilate = s->priv;
270     char default_kernel_str[] = "3x3+0x0/rect";
271     char *kernel_str = NULL;
272     const char *buf = args;
273     int ret;
274
275     if (args) {
276         kernel_str = av_get_token(&buf, "|");
277
278         if (!kernel_str)
279             return AVERROR(ENOMEM);
280     }
281
282     ret = parse_iplconvkernel(&dilate->kernel,
283                               (!kernel_str || !*kernel_str) ? default_kernel_str
284                                                             : kernel_str,
285                               ctx);
286     av_free(kernel_str);
287     if (ret < 0)
288         return ret;
289
290     if (!buf || sscanf(buf, "|%d", &dilate->nb_iterations) != 1)
291         dilate->nb_iterations = 1;
292     av_log(ctx, AV_LOG_VERBOSE, "iterations_nb:%d\n", dilate->nb_iterations);
293     if (dilate->nb_iterations <= 0) {
294         av_log(ctx, AV_LOG_ERROR, "Invalid non-positive value '%d' for nb_iterations\n",
295                dilate->nb_iterations);
296         return AVERROR(EINVAL);
297     }
298     return 0;
299 }
300
301 static av_cold void dilate_uninit(AVFilterContext *ctx)
302 {
303     OCVContext *s = ctx->priv;
304     DilateContext *dilate = s->priv;
305
306     cvReleaseStructuringElement(&dilate->kernel);
307 }
308
309 static void dilate_end_frame_filter(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg)
310 {
311     OCVContext *s = ctx->priv;
312     DilateContext *dilate = s->priv;
313     cvDilate(inimg, outimg, dilate->kernel, dilate->nb_iterations);
314 }
315
316 static void erode_end_frame_filter(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg)
317 {
318     OCVContext *s = ctx->priv;
319     DilateContext *dilate = s->priv;
320     cvErode(inimg, outimg, dilate->kernel, dilate->nb_iterations);
321 }
322
323 typedef struct OCVFilterEntry {
324     const char *name;
325     size_t priv_size;
326     int  (*init)(AVFilterContext *ctx, const char *args);
327     void (*uninit)(AVFilterContext *ctx);
328     void (*end_frame_filter)(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg);
329 } OCVFilterEntry;
330
331 static const OCVFilterEntry ocv_filter_entries[] = {
332     { "dilate", sizeof(DilateContext), dilate_init, dilate_uninit, dilate_end_frame_filter },
333     { "erode",  sizeof(DilateContext), dilate_init, dilate_uninit, erode_end_frame_filter  },
334     { "smooth", sizeof(SmoothContext), smooth_init, NULL, smooth_end_frame_filter },
335 };
336
337 static av_cold int init(AVFilterContext *ctx)
338 {
339     OCVContext *s = ctx->priv;
340     int i;
341
342     if (!s->name) {
343         av_log(ctx, AV_LOG_ERROR, "No libopencv filter name specified\n");
344         return AVERROR(EINVAL);
345     }
346     for (i = 0; i < FF_ARRAY_ELEMS(ocv_filter_entries); i++) {
347         const OCVFilterEntry *entry = &ocv_filter_entries[i];
348         if (!strcmp(s->name, entry->name)) {
349             s->init             = entry->init;
350             s->uninit           = entry->uninit;
351             s->end_frame_filter = entry->end_frame_filter;
352
353             if (!(s->priv = av_mallocz(entry->priv_size)))
354                 return AVERROR(ENOMEM);
355             return s->init(ctx, s->params);
356         }
357     }
358
359     av_log(ctx, AV_LOG_ERROR, "No libopencv filter named '%s'\n", s->name);
360     return AVERROR(EINVAL);
361 }
362
363 static av_cold void uninit(AVFilterContext *ctx)
364 {
365     OCVContext *s = ctx->priv;
366
367     if (s->uninit)
368         s->uninit(ctx);
369     av_freep(&s->priv);
370 }
371
372 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
373 {
374     AVFilterContext *ctx = inlink->dst;
375     OCVContext *s = ctx->priv;
376     AVFilterLink *outlink= inlink->dst->outputs[0];
377     AVFrame *out;
378     IplImage inimg, outimg;
379
380     out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
381     if (!out) {
382         av_frame_free(&in);
383         return AVERROR(ENOMEM);
384     }
385     av_frame_copy_props(out, in);
386
387     fill_iplimage_from_frame(&inimg , in , inlink->format);
388     fill_iplimage_from_frame(&outimg, out, inlink->format);
389     s->end_frame_filter(ctx, &inimg, &outimg);
390     fill_frame_from_iplimage(out, &outimg, inlink->format);
391
392     av_frame_free(&in);
393
394     return ff_filter_frame(outlink, out);
395 }
396
397 #define OFFSET(x) offsetof(OCVContext, x)
398 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_FILTERING_PARAM
399 static const AVOption ocv_options[] = {
400     { "filter_name",   NULL, OFFSET(name),   AV_OPT_TYPE_STRING, .flags = FLAGS },
401     { "filter_params", NULL, OFFSET(params), AV_OPT_TYPE_STRING, .flags = FLAGS },
402     { NULL }
403 };
404
405 AVFILTER_DEFINE_CLASS(ocv);
406
407 static const AVFilterPad avfilter_vf_ocv_inputs[] = {
408     {
409         .name         = "default",
410         .type         = AVMEDIA_TYPE_VIDEO,
411         .filter_frame = filter_frame,
412     },
413     { NULL }
414 };
415
416 static const AVFilterPad avfilter_vf_ocv_outputs[] = {
417     {
418         .name = "default",
419         .type = AVMEDIA_TYPE_VIDEO,
420     },
421     { NULL }
422 };
423
424 AVFilter ff_vf_ocv = {
425     .name          = "ocv",
426     .description   = NULL_IF_CONFIG_SMALL("Apply transform using libopencv."),
427     .priv_size     = sizeof(OCVContext),
428     .priv_class    = &ocv_class,
429     .query_formats = query_formats,
430     .init          = init,
431     .uninit        = uninit,
432     .inputs        = avfilter_vf_ocv_inputs,
433     .outputs       = avfilter_vf_ocv_outputs,
434 };