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"
37 static void fill_iplimage_from_picref(IplImage *img, const AVFilterBufferRef *picref, enum PixelFormat pixfmt)
40 int depth, channels_nb;
42 if (pixfmt == PIX_FMT_GRAY8) { depth = IPL_DEPTH_8U; channels_nb = 1; }
43 else if (pixfmt == PIX_FMT_BGRA) { depth = IPL_DEPTH_8U; channels_nb = 4; }
44 else if (pixfmt == PIX_FMT_BGR24) { depth = IPL_DEPTH_8U; channels_nb = 3; }
47 tmpimg = cvCreateImageHeader((CvSize){picref->video->w, picref->video->h}, depth, channels_nb);
49 img->imageData = img->imageDataOrigin = picref->data[0];
50 img->dataOrder = IPL_DATA_ORDER_PIXEL;
51 img->origin = IPL_ORIGIN_TL;
52 img->widthStep = picref->linesize[0];
55 static void fill_picref_from_iplimage(AVFilterBufferRef *picref, const IplImage *img, enum PixelFormat pixfmt)
57 picref->linesize[0] = img->widthStep;
58 picref->data[0] = img->imageData;
61 static int query_formats(AVFilterContext *ctx)
63 static const enum PixelFormat pix_fmts[] = {
64 PIX_FMT_BGR24, PIX_FMT_BGRA, PIX_FMT_GRAY8, PIX_FMT_NONE
67 ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
71 static int null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
78 int (*init)(AVFilterContext *ctx, const char *args);
79 void (*uninit)(AVFilterContext *ctx);
80 void (*end_frame_filter)(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg);
87 double param3, param4;
90 static av_cold int smooth_init(AVFilterContext *ctx, const char *args)
92 OCVContext *ocv = ctx->priv;
93 SmoothContext *smooth = ocv->priv;
94 char type_str[128] = "gaussian";
102 sscanf(args, "%127[^:]:%d:%d:%lf:%lf", type_str, &smooth->param1, &smooth->param2, &smooth->param3, &smooth->param4);
104 if (!strcmp(type_str, "blur" )) smooth->type = CV_BLUR;
105 else if (!strcmp(type_str, "blur_no_scale")) smooth->type = CV_BLUR_NO_SCALE;
106 else if (!strcmp(type_str, "median" )) smooth->type = CV_MEDIAN;
107 else if (!strcmp(type_str, "gaussian" )) smooth->type = CV_GAUSSIAN;
108 else if (!strcmp(type_str, "bilateral" )) smooth->type = CV_BILATERAL;
110 av_log(ctx, AV_LOG_ERROR, "Smoothing type '%s' unknown.\n", type_str);
111 return AVERROR(EINVAL);
114 if (smooth->param1 < 0 || !(smooth->param1%2)) {
115 av_log(ctx, AV_LOG_ERROR,
116 "Invalid value '%d' for param1, it has to be a positive odd number\n",
118 return AVERROR(EINVAL);
120 if ((smooth->type == CV_BLUR || smooth->type == CV_BLUR_NO_SCALE || smooth->type == CV_GAUSSIAN) &&
121 (smooth->param2 < 0 || (smooth->param2 && !(smooth->param2%2)))) {
122 av_log(ctx, AV_LOG_ERROR,
123 "Invalid value '%d' for param2, it has to be zero or a positive odd number\n",
125 return AVERROR(EINVAL);
128 av_log(ctx, AV_LOG_VERBOSE, "type:%s param1:%d param2:%d param3:%f param4:%f\n",
129 type_str, smooth->param1, smooth->param2, smooth->param3, smooth->param4);
133 static void smooth_end_frame_filter(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg)
135 OCVContext *ocv = ctx->priv;
136 SmoothContext *smooth = ocv->priv;
137 cvSmooth(inimg, outimg, smooth->type, smooth->param1, smooth->param2, smooth->param3, smooth->param4);
140 static int read_shape_from_file(int *cols, int *rows, int **values, const char *filename,
143 uint8_t *buf, *p, *pend;
147 if ((ret = av_file_map(filename, &buf, &size, 0, log_ctx)) < 0)
150 /* prescan file to get the number of lines and the maximum width */
152 for (i = 0; i < size; i++) {
153 if (buf[i] == '\n') {
154 if (*rows == INT_MAX) {
155 av_log(log_ctx, AV_LOG_ERROR, "Overflow on the number of rows in the file\n");
156 return AVERROR_INVALIDDATA;
159 *cols = FFMAX(*cols, w);
161 } else if (w == INT_MAX) {
162 av_log(log_ctx, AV_LOG_ERROR, "Overflow on the number of columns in the file\n");
163 return AVERROR_INVALIDDATA;
167 if (*rows > (SIZE_MAX / sizeof(int) / *cols)) {
168 av_log(log_ctx, AV_LOG_ERROR, "File with size %dx%d is too big\n",
170 return AVERROR_INVALIDDATA;
172 if (!(*values = av_mallocz(sizeof(int) * *rows * *cols)))
173 return AVERROR(ENOMEM);
178 for (i = 0; i < *rows; i++) {
180 if (p > pend || *p == '\n') {
184 (*values)[*cols*i + j] = !!isgraph(*(p++));
187 av_file_unmap(buf, size);
192 if (!(line = av_malloc(*cols + 1)))
193 return AVERROR(ENOMEM);
194 for (i = 0; i < *rows; i++) {
195 for (j = 0; j < *cols; j++)
196 line[j] = (*values)[i * *cols + j] ? '@' : ' ';
198 av_log(log_ctx, AV_LOG_DEBUG, "%3d: %s\n", i, line);
207 static int parse_iplconvkernel(IplConvKernel **kernel, char *buf, void *log_ctx)
209 char shape_filename[128] = "", shape_str[32] = "rect";
210 int cols = 0, rows = 0, anchor_x = 0, anchor_y = 0, shape = CV_SHAPE_RECT;
211 int *values = NULL, ret;
213 sscanf(buf, "%dx%d+%dx%d/%32[^=]=%127s", &cols, &rows, &anchor_x, &anchor_y, shape_str, shape_filename);
215 if (!strcmp(shape_str, "rect" )) shape = CV_SHAPE_RECT;
216 else if (!strcmp(shape_str, "cross" )) shape = CV_SHAPE_CROSS;
217 else if (!strcmp(shape_str, "ellipse")) shape = CV_SHAPE_ELLIPSE;
218 else if (!strcmp(shape_str, "custom" )) {
219 shape = CV_SHAPE_CUSTOM;
220 if ((ret = read_shape_from_file(&cols, &rows, &values, shape_filename, log_ctx)) < 0)
223 av_log(log_ctx, AV_LOG_ERROR,
224 "Shape unspecified or type '%s' unknown.\n", shape_str);
225 return AVERROR(EINVAL);
228 if (rows <= 0 || cols <= 0) {
229 av_log(log_ctx, AV_LOG_ERROR,
230 "Invalid non-positive values for shape size %dx%d\n", cols, rows);
231 return AVERROR(EINVAL);
234 if (anchor_x < 0 || anchor_y < 0 || anchor_x >= cols || anchor_y >= rows) {
235 av_log(log_ctx, AV_LOG_ERROR,
236 "Shape anchor %dx%d is not inside the rectangle with size %dx%d.\n",
237 anchor_x, anchor_y, cols, rows);
238 return AVERROR(EINVAL);
241 *kernel = cvCreateStructuringElementEx(cols, rows, anchor_x, anchor_y, shape, values);
244 return AVERROR(ENOMEM);
246 av_log(log_ctx, AV_LOG_VERBOSE, "Structuring element: w:%d h:%d x:%d y:%d shape:%s\n",
247 rows, cols, anchor_x, anchor_y, shape_str);
253 IplConvKernel *kernel;
256 static av_cold int dilate_init(AVFilterContext *ctx, const char *args)
258 OCVContext *ocv = ctx->priv;
259 DilateContext *dilate = ocv->priv;
260 char default_kernel_str[] = "3x3+0x0/rect";
262 const char *buf = args;
265 dilate->nb_iterations = 1;
268 kernel_str = av_get_token(&buf, ":");
269 if ((ret = parse_iplconvkernel(&dilate->kernel,
270 *kernel_str ? kernel_str : default_kernel_str,
275 sscanf(buf, ":%d", &dilate->nb_iterations);
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, const char *args)
323 OCVContext *ocv = ctx->priv;
324 char name[128], priv_args[1024];
328 sscanf(args, "%127[^=:]%c%1023s", name, &c, priv_args);
330 for (i = 0; i < FF_ARRAY_ELEMS(ocv_filter_entries); i++) {
331 OCVFilterEntry *entry = &ocv_filter_entries[i];
332 if (!strcmp(name, entry->name)) {
333 ocv->name = entry->name;
334 ocv->init = entry->init;
335 ocv->uninit = entry->uninit;
336 ocv->end_frame_filter = entry->end_frame_filter;
338 if (!(ocv->priv = av_mallocz(entry->priv_size)))
339 return AVERROR(ENOMEM);
340 return ocv->init(ctx, priv_args);
344 av_log(ctx, AV_LOG_ERROR, "No libopencv filter named '%s'\n", name);
345 return AVERROR(EINVAL);
348 static av_cold void uninit(AVFilterContext *ctx)
350 OCVContext *ocv = ctx->priv;
355 memset(ocv, 0, sizeof(*ocv));
358 static int end_frame(AVFilterLink *inlink)
360 AVFilterContext *ctx = inlink->dst;
361 OCVContext *ocv = ctx->priv;
362 AVFilterLink *outlink= inlink->dst->outputs[0];
363 AVFilterBufferRef *inpicref = inlink ->cur_buf;
364 AVFilterBufferRef *outpicref = outlink->out_buf;
365 IplImage inimg, outimg;
368 fill_iplimage_from_picref(&inimg , inpicref , inlink->format);
369 fill_iplimage_from_picref(&outimg, outpicref, inlink->format);
370 ocv->end_frame_filter(ctx, &inimg, &outimg);
371 fill_picref_from_iplimage(outpicref, &outimg, inlink->format);
373 if ((ret = ff_draw_slice(outlink, 0, outlink->h, 1)) < 0 ||
374 (ret = ff_end_frame(outlink)) < 0)
379 AVFilter avfilter_vf_ocv = {
381 .description = NULL_IF_CONFIG_SMALL("Apply transform using libopencv."),
383 .priv_size = sizeof(OCVContext),
385 .query_formats = query_formats,
389 .inputs = (const AVFilterPad[]) {{ .name = "default",
390 .type = AVMEDIA_TYPE_VIDEO,
391 .draw_slice = null_draw_slice,
392 .end_frame = end_frame,
393 .min_perms = AV_PERM_READ },
396 .outputs = (const AVFilterPad[]) {{ .name = "default",
397 .type = AVMEDIA_TYPE_VIDEO, },