vf_libopencv.c 13.1 KB
Newer Older
1
/*
2
 * Copyright (c) 2010 Stefano Sabatini
3
 *
4
 * This file is part of Libav.
5
 *
6
 * Libav is free software; you can redistribute it and/or
7 8 9 10
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
11
 * Libav is distributed in the hope that it will be useful,
12 13 14 15 16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with Libav; if not, write to the Free Software
18 19 20 21 22 23 24 25
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

/**
 * @file
 * libopencv wrapper functions
 */

26
#include <opencv/cv.h>
27
#include <opencv/cxcore.h>
28
#include "libavutil/avstring.h"
29
#include "libavutil/common.h"
30
#include "libavutil/file.h"
31
#include "libavutil/opt.h"
32
#include "avfilter.h"
33
#include "formats.h"
34
#include "internal.h"
35
#include "video.h"
36

37
static void fill_iplimage_from_frame(IplImage *img, const AVFrame *frame, enum AVPixelFormat pixfmt)
38 39 40 41
{
    IplImage *tmpimg;
    int depth, channels_nb;

42 43 44
    if      (pixfmt == AV_PIX_FMT_GRAY8) { depth = IPL_DEPTH_8U;  channels_nb = 1; }
    else if (pixfmt == AV_PIX_FMT_BGRA)  { depth = IPL_DEPTH_8U;  channels_nb = 4; }
    else if (pixfmt == AV_PIX_FMT_BGR24) { depth = IPL_DEPTH_8U;  channels_nb = 3; }
45 46
    else return;

47
    tmpimg = cvCreateImageHeader((CvSize){frame->width, frame->height}, depth, channels_nb);
48
    *img = *tmpimg;
49
    img->imageData = img->imageDataOrigin = frame->data[0];
50 51
    img->dataOrder = IPL_DATA_ORDER_PIXEL;
    img->origin    = IPL_ORIGIN_TL;
52
    img->widthStep = frame->linesize[0];
53 54
}

55
static void fill_frame_from_iplimage(AVFrame *frame, const IplImage *img, enum AVPixelFormat pixfmt)
56
{
57 58
    frame->linesize[0] = img->widthStep;
    frame->data[0]     = img->imageData;
59 60 61 62
}

static int query_formats(AVFilterContext *ctx)
{
63 64
    static const enum AVPixelFormat pix_fmts[] = {
        AV_PIX_FMT_BGR24, AV_PIX_FMT_BGRA, AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE
65 66
    };

67
    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
68 69 70
    return 0;
}

71
typedef struct OCVContext {
72 73 74
    const AVClass *class;
    char *name;
    char *params;
75
    int (*init)(AVFilterContext *ctx, const char *args);
76 77 78 79
    void (*uninit)(AVFilterContext *ctx);
    void (*end_frame_filter)(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg);
    void *priv;
} OCVContext;
80

81
typedef struct SmoothContext {
82 83 84 85 86
    int type;
    int    param1, param2;
    double param3, param4;
} SmoothContext;

87
static av_cold int smooth_init(AVFilterContext *ctx, const char *args)
88
{
89 90
    OCVContext *s = ctx->priv;
    SmoothContext *smooth = s->priv;
91 92 93 94 95 96 97 98
    char type_str[128] = "gaussian";

    smooth->param1 = 3;
    smooth->param2 = 0;
    smooth->param3 = 0.0;
    smooth->param4 = 0.0;

    if (args)
99
        sscanf(args, "%127[^|]|%d|%d|%lf|%lf", type_str, &smooth->param1, &smooth->param2, &smooth->param3, &smooth->param4);
100 101 102 103 104 105 106

    if      (!strcmp(type_str, "blur"         )) smooth->type = CV_BLUR;
    else if (!strcmp(type_str, "blur_no_scale")) smooth->type = CV_BLUR_NO_SCALE;
    else if (!strcmp(type_str, "median"       )) smooth->type = CV_MEDIAN;
    else if (!strcmp(type_str, "gaussian"     )) smooth->type = CV_GAUSSIAN;
    else if (!strcmp(type_str, "bilateral"    )) smooth->type = CV_BILATERAL;
    else {
107
        av_log(ctx, AV_LOG_ERROR, "Smoothing type '%s' unknown.\n", type_str);
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
        return AVERROR(EINVAL);
    }

    if (smooth->param1 < 0 || !(smooth->param1%2)) {
        av_log(ctx, AV_LOG_ERROR,
               "Invalid value '%d' for param1, it has to be a positive odd number\n",
               smooth->param1);
        return AVERROR(EINVAL);
    }
    if ((smooth->type == CV_BLUR || smooth->type == CV_BLUR_NO_SCALE || smooth->type == CV_GAUSSIAN) &&
        (smooth->param2 < 0 || (smooth->param2 && !(smooth->param2%2)))) {
        av_log(ctx, AV_LOG_ERROR,
               "Invalid value '%d' for param2, it has to be zero or a positive odd number\n",
               smooth->param2);
        return AVERROR(EINVAL);
    }

125
    av_log(ctx, AV_LOG_VERBOSE, "type:%s param1:%d param2:%d param3:%f param4:%f\n",
126 127 128 129
           type_str, smooth->param1, smooth->param2, smooth->param3, smooth->param4);
    return 0;
}

130
static void smooth_end_frame_filter(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg)
131
{
132 133
    OCVContext *s = ctx->priv;
    SmoothContext *smooth = s->priv;
134 135 136
    cvSmooth(inimg, outimg, smooth->type, smooth->param1, smooth->param2, smooth->param3, smooth->param4);
}

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
static int read_shape_from_file(int *cols, int *rows, int **values, const char *filename,
                                void *log_ctx)
{
    uint8_t *buf, *p, *pend;
    size_t size;
    int ret, i, j, w;

    if ((ret = av_file_map(filename, &buf, &size, 0, log_ctx)) < 0)
        return ret;

    /* prescan file to get the number of lines and the maximum width */
    w = 0;
    for (i = 0; i < size; i++) {
        if (buf[i] == '\n') {
            if (*rows == INT_MAX) {
                av_log(log_ctx, AV_LOG_ERROR, "Overflow on the number of rows in the file\n");
                return AVERROR_INVALIDDATA;
            }
            ++(*rows);
            *cols = FFMAX(*cols, w);
            w = 0;
        } else if (w == INT_MAX) {
            av_log(log_ctx, AV_LOG_ERROR, "Overflow on the number of columns in the file\n");
            return AVERROR_INVALIDDATA;
        }
        w++;
    }
164
    if (*rows > (SIZE_MAX / sizeof(int) / *cols)) {
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
        av_log(log_ctx, AV_LOG_ERROR, "File with size %dx%d is too big\n",
               *rows, *cols);
        return AVERROR_INVALIDDATA;
    }
    if (!(*values = av_mallocz(sizeof(int) * *rows * *cols)))
        return AVERROR(ENOMEM);

    /* fill *values */
    p    = buf;
    pend = buf + size-1;
    for (i = 0; i < *rows; i++) {
        for (j = 0;; j++) {
            if (p > pend || *p == '\n') {
                p++;
                break;
            } else
181
                (*values)[*cols*i + j] = !!av_isgraph(*(p++));
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
        }
    }
    av_file_unmap(buf, size);

#ifdef DEBUG
    {
        char *line;
        if (!(line = av_malloc(*cols + 1)))
            return AVERROR(ENOMEM);
        for (i = 0; i < *rows; i++) {
            for (j = 0; j < *cols; j++)
                line[j] = (*values)[i * *cols + j] ? '@' : ' ';
            line[j] = 0;
            av_log(log_ctx, AV_LOG_DEBUG, "%3d: %s\n", i, line);
        }
        av_free(line);
    }
#endif

    return 0;
}

static int parse_iplconvkernel(IplConvKernel **kernel, char *buf, void *log_ctx)
{
    char shape_filename[128] = "", shape_str[32] = "rect";
    int cols = 0, rows = 0, anchor_x = 0, anchor_y = 0, shape = CV_SHAPE_RECT;
    int *values = NULL, ret;

    sscanf(buf, "%dx%d+%dx%d/%32[^=]=%127s", &cols, &rows, &anchor_x, &anchor_y, shape_str, shape_filename);

    if      (!strcmp(shape_str, "rect"   )) shape = CV_SHAPE_RECT;
    else if (!strcmp(shape_str, "cross"  )) shape = CV_SHAPE_CROSS;
    else if (!strcmp(shape_str, "ellipse")) shape = CV_SHAPE_ELLIPSE;
    else if (!strcmp(shape_str, "custom" )) {
        shape = CV_SHAPE_CUSTOM;
        if ((ret = read_shape_from_file(&cols, &rows, &values, shape_filename, log_ctx)) < 0)
            return ret;
    } else {
        av_log(log_ctx, AV_LOG_ERROR,
221
               "Shape unspecified or type '%s' unknown.\n", shape_str);
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
        return AVERROR(EINVAL);
    }

    if (rows <= 0 || cols <= 0) {
        av_log(log_ctx, AV_LOG_ERROR,
               "Invalid non-positive values for shape size %dx%d\n", cols, rows);
        return AVERROR(EINVAL);
    }

    if (anchor_x < 0 || anchor_y < 0 || anchor_x >= cols || anchor_y >= rows) {
        av_log(log_ctx, AV_LOG_ERROR,
               "Shape anchor %dx%d is not inside the rectangle with size %dx%d.\n",
               anchor_x, anchor_y, cols, rows);
        return AVERROR(EINVAL);
    }

    *kernel = cvCreateStructuringElementEx(cols, rows, anchor_x, anchor_y, shape, values);
    av_freep(&values);
    if (!*kernel)
        return AVERROR(ENOMEM);

243
    av_log(log_ctx, AV_LOG_VERBOSE, "Structuring element: w:%d h:%d x:%d y:%d shape:%s\n",
244 245 246 247
           rows, cols, anchor_x, anchor_y, shape_str);
    return 0;
}

248
typedef struct DilateContext {
249 250 251 252
    int nb_iterations;
    IplConvKernel *kernel;
} DilateContext;

253
static av_cold int dilate_init(AVFilterContext *ctx, const char *args)
254
{
255 256
    OCVContext *s = ctx->priv;
    DilateContext *dilate = s->priv;
257 258 259 260 261 262 263 264
    char default_kernel_str[] = "3x3+0x0/rect";
    char *kernel_str;
    const char *buf = args;
    int ret;

    dilate->nb_iterations = 1;

    if (args)
265
        kernel_str = av_get_token(&buf, "|");
266 267 268 269 270 271
    if ((ret = parse_iplconvkernel(&dilate->kernel,
                                   *kernel_str ? kernel_str : default_kernel_str,
                                   ctx)) < 0)
        return ret;
    av_free(kernel_str);

272
    sscanf(buf, "|%d", &dilate->nb_iterations);
273
    av_log(ctx, AV_LOG_VERBOSE, "iterations_nb:%d\n", dilate->nb_iterations);
274 275 276 277 278 279 280 281 282 283
    if (dilate->nb_iterations <= 0) {
        av_log(ctx, AV_LOG_ERROR, "Invalid non-positive value '%d' for nb_iterations\n",
               dilate->nb_iterations);
        return AVERROR(EINVAL);
    }
    return 0;
}

static av_cold void dilate_uninit(AVFilterContext *ctx)
{
284 285
    OCVContext *s = ctx->priv;
    DilateContext *dilate = s->priv;
286 287 288 289 290 291

    cvReleaseStructuringElement(&dilate->kernel);
}

static void dilate_end_frame_filter(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg)
{
292 293
    OCVContext *s = ctx->priv;
    DilateContext *dilate = s->priv;
294 295 296
    cvDilate(inimg, outimg, dilate->kernel, dilate->nb_iterations);
}

297 298
static void erode_end_frame_filter(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg)
{
299 300
    OCVContext *s = ctx->priv;
    DilateContext *dilate = s->priv;
301 302 303
    cvErode(inimg, outimg, dilate->kernel, dilate->nb_iterations);
}

304
typedef struct OCVFilterEntry {
305 306
    const char *name;
    size_t priv_size;
307
    int  (*init)(AVFilterContext *ctx, const char *args);
308 309 310 311 312
    void (*uninit)(AVFilterContext *ctx);
    void (*end_frame_filter)(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg);
} OCVFilterEntry;

static OCVFilterEntry ocv_filter_entries[] = {
313
    { "dilate", sizeof(DilateContext), dilate_init, dilate_uninit, dilate_end_frame_filter },
314
    { "erode",  sizeof(DilateContext), dilate_init, dilate_uninit, erode_end_frame_filter  },
315 316 317
    { "smooth", sizeof(SmoothContext), smooth_init, NULL, smooth_end_frame_filter },
};

318
static av_cold int init(AVFilterContext *ctx)
319
{
320
    OCVContext *s = ctx->priv;
321 322 323 324
    int i;

    for (i = 0; i < FF_ARRAY_ELEMS(ocv_filter_entries); i++) {
        OCVFilterEntry *entry = &ocv_filter_entries[i];
325 326 327 328
        if (!strcmp(s->name, entry->name)) {
            s->init             = entry->init;
            s->uninit           = entry->uninit;
            s->end_frame_filter = entry->end_frame_filter;
329

330
            if (!(s->priv = av_mallocz(entry->priv_size)))
331
                return AVERROR(ENOMEM);
332
            return s->init(ctx, s->params);
333 334 335
        }
    }

336
    av_log(ctx, AV_LOG_ERROR, "No libopencv filter named '%s'\n", s->name);
337 338 339 340 341
    return AVERROR(EINVAL);
}

static av_cold void uninit(AVFilterContext *ctx)
{
342
    OCVContext *s = ctx->priv;
343

344 345 346
    if (s->uninit)
        s->uninit(ctx);
    av_free(s->priv);
347 348
}

349
static int filter_frame(AVFilterLink *inlink, AVFrame *in)
350 351
{
    AVFilterContext *ctx = inlink->dst;
352
    OCVContext *s = ctx->priv;
353
    AVFilterLink *outlink= inlink->dst->outputs[0];
354
    AVFrame *out;
355 356
    IplImage inimg, outimg;

357
    out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
358
    if (!out) {
359
        av_frame_free(&in);
360 361
        return AVERROR(ENOMEM);
    }
362
    av_frame_copy_props(out, in);
363

364 365
    fill_iplimage_from_frame(&inimg , in , inlink->format);
    fill_iplimage_from_frame(&outimg, out, inlink->format);
366
    s->end_frame_filter(ctx, &inimg, &outimg);
367
    fill_frame_from_iplimage(out, &outimg, inlink->format);
368

369
    av_frame_free(&in);
370 371

    return ff_filter_frame(outlink, out);
372 373
}

374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
#define OFFSET(x) offsetof(OCVContext, x)
#define FLAGS AV_OPT_FLAG_VIDEO_PARAM
static const AVOption options[] = {
    { "filter_name",   NULL, OFFSET(name),   AV_OPT_TYPE_STRING, .flags = FLAGS },
    { "filter_params", NULL, OFFSET(params), AV_OPT_TYPE_STRING, .flags = FLAGS },
    { NULL },
};

static const AVClass ocv_class = {
    .class_name = "ocv",
    .item_name  = av_default_item_name,
    .option     = options,
    .version    = LIBAVUTIL_VERSION_INT,
};

389 390 391 392
static const AVFilterPad avfilter_vf_ocv_inputs[] = {
    {
        .name       = "default",
        .type       = AVMEDIA_TYPE_VIDEO,
393
        .filter_frame = filter_frame,
394 395 396 397 398 399 400 401 402 403 404 405
    },
    { NULL }
};

static const AVFilterPad avfilter_vf_ocv_outputs[] = {
    {
        .name = "default",
        .type = AVMEDIA_TYPE_VIDEO,
    },
    { NULL }
};

406
AVFilter ff_vf_ocv = {
407 408
    .name        = "ocv",
    .description = NULL_IF_CONFIG_SMALL("Apply transform using libopencv."),
409

410
    .priv_size = sizeof(OCVContext),
411
    .priv_class = &ocv_class,
412 413

    .query_formats = query_formats,
414 415
    .init = init,
    .uninit = uninit,
416

417
    .inputs    = avfilter_vf_ocv_inputs,
418

419
    .outputs   = avfilter_vf_ocv_outputs,
420
};