2 * Copyright (c) 2010 Stefano Sabatini
4 * This file is part of FFmpeg.
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.
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.
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
23 * libopencv wrapper functions
28 #include <opencv/cv.h>
29 #include <opencv/cxcore.h>
30 #include "libavutil/avstring.h"
31 #include "libavutil/common.h"
32 #include "libavutil/file.h"
33 #include "libavutil/opt.h"
39 static void fill_iplimage_from_frame(IplImage *img, const AVFrame *frame, enum AVPixelFormat pixfmt)
42 int depth, channels_nb;
44 if (pixfmt == AV_PIX_FMT_GRAY8) { depth = IPL_DEPTH_8U; channels_nb = 1; }
45 else if (pixfmt == AV_PIX_FMT_BGRA) { depth = IPL_DEPTH_8U; channels_nb = 4; }
46 else if (pixfmt == AV_PIX_FMT_BGR24) { depth = IPL_DEPTH_8U; channels_nb = 3; }
49 tmpimg = cvCreateImageHeader((CvSize){frame->width, frame->height}, depth, channels_nb);
51 img->imageData = img->imageDataOrigin = frame->data[0];
52 img->dataOrder = IPL_DATA_ORDER_PIXEL;
53 img->origin = IPL_ORIGIN_TL;
54 img->widthStep = frame->linesize[0];
57 static void fill_frame_from_iplimage(AVFrame *frame, const IplImage *img, enum AVPixelFormat pixfmt)
59 frame->linesize[0] = img->widthStep;
60 frame->data[0] = img->imageData;
63 static int query_formats(AVFilterContext *ctx)
65 static const enum AVPixelFormat pix_fmts[] = {
66 AV_PIX_FMT_BGR24, AV_PIX_FMT_BGRA, AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE
69 ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
77 int (*init)(AVFilterContext *ctx, const char *args);
78 void (*uninit)(AVFilterContext *ctx);
79 void (*end_frame_filter)(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg);
86 double param3, param4;
89 static av_cold int smooth_init(AVFilterContext *ctx, const char *args)
91 OCVContext *ocv = ctx->priv;
92 SmoothContext *smooth = ocv->priv;
93 char type_str[128] = "gaussian";
101 sscanf(args, "%127[^|]|%d|%d|%lf|%lf", type_str, &smooth->param1, &smooth->param2, &smooth->param3, &smooth->param4);
103 if (!strcmp(type_str, "blur" )) smooth->type = CV_BLUR;
104 else if (!strcmp(type_str, "blur_no_scale")) smooth->type = CV_BLUR_NO_SCALE;
105 else if (!strcmp(type_str, "median" )) smooth->type = CV_MEDIAN;
106 else if (!strcmp(type_str, "gaussian" )) smooth->type = CV_GAUSSIAN;
107 else if (!strcmp(type_str, "bilateral" )) smooth->type = CV_BILATERAL;
109 av_log(ctx, AV_LOG_ERROR, "Smoothing type '%s' unknown.\n", type_str);
110 return AVERROR(EINVAL);
113 if (smooth->param1 < 0 || !(smooth->param1%2)) {
114 av_log(ctx, AV_LOG_ERROR,
115 "Invalid value '%d' for param1, it has to be a positive odd number\n",
117 return AVERROR(EINVAL);
119 if ((smooth->type == CV_BLUR || smooth->type == CV_BLUR_NO_SCALE || smooth->type == CV_GAUSSIAN) &&
120 (smooth->param2 < 0 || (smooth->param2 && !(smooth->param2%2)))) {
121 av_log(ctx, AV_LOG_ERROR,
122 "Invalid value '%d' for param2, it has to be zero or a positive odd number\n",
124 return AVERROR(EINVAL);
127 av_log(ctx, AV_LOG_VERBOSE, "type:%s param1:%d param2:%d param3:%f param4:%f\n",
128 type_str, smooth->param1, smooth->param2, smooth->param3, smooth->param4);
132 static void smooth_end_frame_filter(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg)
134 OCVContext *ocv = ctx->priv;
135 SmoothContext *smooth = ocv->priv;
136 cvSmooth(inimg, outimg, smooth->type, smooth->param1, smooth->param2, smooth->param3, smooth->param4);
139 static int read_shape_from_file(int *cols, int *rows, int **values, const char *filename,
142 uint8_t *buf, *p, *pend;
146 if ((ret = av_file_map(filename, &buf, &size, 0, log_ctx)) < 0)
149 /* prescan file to get the number of lines and the maximum width */
151 for (i = 0; i < size; i++) {
152 if (buf[i] == '\n') {
153 if (*rows == INT_MAX) {
154 av_log(log_ctx, AV_LOG_ERROR, "Overflow on the number of rows in the file\n");
155 return AVERROR_INVALIDDATA;
158 *cols = FFMAX(*cols, w);
160 } else if (w == INT_MAX) {
161 av_log(log_ctx, AV_LOG_ERROR, "Overflow on the number of columns in the file\n");
162 return AVERROR_INVALIDDATA;
166 if (*rows > (SIZE_MAX / sizeof(int) / *cols)) {
167 av_log(log_ctx, AV_LOG_ERROR, "File with size %dx%d is too big\n",
169 return AVERROR_INVALIDDATA;
171 if (!(*values = av_mallocz(sizeof(int) * *rows * *cols)))
172 return AVERROR(ENOMEM);
177 for (i = 0; i < *rows; i++) {
179 if (p > pend || *p == '\n') {
183 (*values)[*cols*i + j] = !!av_isgraph(*(p++));
186 av_file_unmap(buf, size);
191 if (!(line = av_malloc(*cols + 1)))
192 return AVERROR(ENOMEM);
193 for (i = 0; i < *rows; i++) {
194 for (j = 0; j < *cols; j++)
195 line[j] = (*values)[i * *cols + j] ? '@' : ' ';
197 av_log(log_ctx, AV_LOG_DEBUG, "%3d: %s\n", i, line);
206 static int parse_iplconvkernel(IplConvKernel **kernel, char *buf, void *log_ctx)
208 char shape_filename[128] = "", shape_str[32] = "rect";
209 int cols = 0, rows = 0, anchor_x = 0, anchor_y = 0, shape = CV_SHAPE_RECT;
210 int *values = NULL, ret;
212 sscanf(buf, "%dx%d+%dx%d/%32[^=]=%127s", &cols, &rows, &anchor_x, &anchor_y, shape_str, shape_filename);
214 if (!strcmp(shape_str, "rect" )) shape = CV_SHAPE_RECT;
215 else if (!strcmp(shape_str, "cross" )) shape = CV_SHAPE_CROSS;
216 else if (!strcmp(shape_str, "ellipse")) shape = CV_SHAPE_ELLIPSE;
217 else if (!strcmp(shape_str, "custom" )) {
218 shape = CV_SHAPE_CUSTOM;
219 if ((ret = read_shape_from_file(&cols, &rows, &values, shape_filename, log_ctx)) < 0)
222 av_log(log_ctx, AV_LOG_ERROR,
223 "Shape unspecified or type '%s' unknown.\n", shape_str);
224 return AVERROR(EINVAL);
227 if (rows <= 0 || cols <= 0) {
228 av_log(log_ctx, AV_LOG_ERROR,
229 "Invalid non-positive values for shape size %dx%d\n", cols, rows);
230 return AVERROR(EINVAL);
233 if (anchor_x < 0 || anchor_y < 0 || anchor_x >= cols || anchor_y >= rows) {
234 av_log(log_ctx, AV_LOG_ERROR,
235 "Shape anchor %dx%d is not inside the rectangle with size %dx%d.\n",
236 anchor_x, anchor_y, cols, rows);
237 return AVERROR(EINVAL);
240 *kernel = cvCreateStructuringElementEx(cols, rows, anchor_x, anchor_y, shape, values);
243 return AVERROR(ENOMEM);
245 av_log(log_ctx, AV_LOG_VERBOSE, "Structuring element: w:%d h:%d x:%d y:%d shape:%s\n",
246 rows, cols, anchor_x, anchor_y, shape_str);
252 IplConvKernel *kernel;
255 static av_cold int dilate_init(AVFilterContext *ctx, const char *args)
257 OCVContext *ocv = ctx->priv;
258 DilateContext *dilate = ocv->priv;
259 char default_kernel_str[] = "3x3+0x0/rect";
261 const char *buf = args;
265 kernel_str = av_get_token(&buf, "|");
267 kernel_str = av_strdup(default_kernel_str);
269 return AVERROR(ENOMEM);
270 if ((ret = parse_iplconvkernel(&dilate->kernel, kernel_str, ctx)) < 0)
274 if (!buf || sscanf(buf, "|%d", &dilate->nb_iterations) != 1)
275 dilate->nb_iterations = 1;
276 av_log(ctx, AV_LOG_VERBOSE, "iterations_nb:%d\n", dilate->nb_iterations);
277 if (dilate->nb_iterations <= 0) {
278 av_log(ctx, AV_LOG_ERROR, "Invalid non-positive value '%d' for nb_iterations\n",
279 dilate->nb_iterations);
280 return AVERROR(EINVAL);
285 static av_cold void dilate_uninit(AVFilterContext *ctx)
287 OCVContext *ocv = ctx->priv;
288 DilateContext *dilate = ocv->priv;
290 cvReleaseStructuringElement(&dilate->kernel);
293 static void dilate_end_frame_filter(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg)
295 OCVContext *ocv = ctx->priv;
296 DilateContext *dilate = ocv->priv;
297 cvDilate(inimg, outimg, dilate->kernel, dilate->nb_iterations);
300 static void erode_end_frame_filter(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg)
302 OCVContext *ocv = ctx->priv;
303 DilateContext *dilate = ocv->priv;
304 cvErode(inimg, outimg, dilate->kernel, dilate->nb_iterations);
310 int (*init)(AVFilterContext *ctx, const char *args);
311 void (*uninit)(AVFilterContext *ctx);
312 void (*end_frame_filter)(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg);
315 static OCVFilterEntry ocv_filter_entries[] = {
316 { "dilate", sizeof(DilateContext), dilate_init, dilate_uninit, dilate_end_frame_filter },
317 { "erode", sizeof(DilateContext), dilate_init, dilate_uninit, erode_end_frame_filter },
318 { "smooth", sizeof(SmoothContext), smooth_init, NULL, smooth_end_frame_filter },
321 static av_cold int init(AVFilterContext *ctx)
323 OCVContext *ocv = ctx->priv;
327 av_log(ctx, AV_LOG_ERROR, "No libopencv filter name specified\n");
328 return AVERROR(EINVAL);
330 for (i = 0; i < FF_ARRAY_ELEMS(ocv_filter_entries); i++) {
331 OCVFilterEntry *entry = &ocv_filter_entries[i];
332 if (!strcmp(ocv->name, entry->name)) {
333 ocv->init = entry->init;
334 ocv->uninit = entry->uninit;
335 ocv->end_frame_filter = entry->end_frame_filter;
337 if (!(ocv->priv = av_mallocz(entry->priv_size)))
338 return AVERROR(ENOMEM);
339 return ocv->init(ctx, ocv->params);
343 av_log(ctx, AV_LOG_ERROR, "No libopencv filter named '%s'\n", ocv->name);
344 return AVERROR(EINVAL);
347 static av_cold void uninit(AVFilterContext *ctx)
349 OCVContext *ocv = ctx->priv;
356 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
358 AVFilterContext *ctx = inlink->dst;
359 OCVContext *ocv = ctx->priv;
360 AVFilterLink *outlink= inlink->dst->outputs[0];
362 IplImage inimg, outimg;
364 out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
367 return AVERROR(ENOMEM);
369 av_frame_copy_props(out, in);
371 fill_iplimage_from_frame(&inimg , in , inlink->format);
372 fill_iplimage_from_frame(&outimg, out, inlink->format);
373 ocv->end_frame_filter(ctx, &inimg, &outimg);
374 fill_frame_from_iplimage(out, &outimg, inlink->format);
378 return ff_filter_frame(outlink, out);
381 #define OFFSET(x) offsetof(OCVContext, x)
382 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_FILTERING_PARAM
383 static const AVOption options[] = {
384 { "filter_name", NULL, OFFSET(name), AV_OPT_TYPE_STRING, .flags = FLAGS },
385 { "filter_params", NULL, OFFSET(params), AV_OPT_TYPE_STRING, .flags = FLAGS },
389 static const AVClass ocv_class = {
391 .item_name = av_default_item_name,
393 .version = LIBAVUTIL_VERSION_INT,
396 static const AVFilterPad avfilter_vf_ocv_inputs[] = {
399 .type = AVMEDIA_TYPE_VIDEO,
400 .filter_frame = filter_frame,
405 static const AVFilterPad avfilter_vf_ocv_outputs[] = {
408 .type = AVMEDIA_TYPE_VIDEO,
413 AVFilter avfilter_vf_ocv = {
415 .description = NULL_IF_CONFIG_SMALL("Apply transform using libopencv."),
417 .priv_size = sizeof(OCVContext),
418 .priv_class = &ocv_class,
420 .query_formats = query_formats,
424 .inputs = avfilter_vf_ocv_inputs,
426 .outputs = avfilter_vf_ocv_outputs,