vf_libopencv.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. * @file
  22. * libopencv wrapper functions
  23. */
  24. /* #define DEBUG */
  25. #include <opencv/cv.h>
  26. #include <opencv/cxcore.h>
  27. #include "libavutil/avstring.h"
  28. #include "libavutil/file.h"
  29. #include "avfilter.h"
  30. static void fill_iplimage_from_picref(IplImage *img, const AVFilterBufferRef *picref, enum PixelFormat pixfmt)
  31. {
  32. IplImage *tmpimg;
  33. int depth, channels_nb;
  34. if (pixfmt == PIX_FMT_GRAY8) { depth = IPL_DEPTH_8U; channels_nb = 1; }
  35. else if (pixfmt == PIX_FMT_BGRA) { depth = IPL_DEPTH_8U; channels_nb = 4; }
  36. else if (pixfmt == PIX_FMT_BGR24) { depth = IPL_DEPTH_8U; channels_nb = 3; }
  37. else return;
  38. tmpimg = cvCreateImageHeader((CvSize){picref->video->w, picref->video->h}, depth, channels_nb);
  39. *img = *tmpimg;
  40. img->imageData = img->imageDataOrigin = picref->data[0];
  41. img->dataOrder = IPL_DATA_ORDER_PIXEL;
  42. img->origin = IPL_ORIGIN_TL;
  43. img->widthStep = picref->linesize[0];
  44. }
  45. static void fill_picref_from_iplimage(AVFilterBufferRef *picref, const IplImage *img, enum PixelFormat pixfmt)
  46. {
  47. picref->linesize[0] = img->widthStep;
  48. picref->data[0] = img->imageData;
  49. }
  50. static int query_formats(AVFilterContext *ctx)
  51. {
  52. static const enum PixelFormat pix_fmts[] = {
  53. PIX_FMT_BGR24, PIX_FMT_BGRA, PIX_FMT_GRAY8, PIX_FMT_NONE
  54. };
  55. avfilter_set_common_pixel_formats(ctx, avfilter_make_format_list(pix_fmts));
  56. return 0;
  57. }
  58. static void null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { }
  59. typedef struct {
  60. const char *name;
  61. int (*init)(AVFilterContext *ctx, const char *args, void *opaque);
  62. void (*uninit)(AVFilterContext *ctx);
  63. void (*end_frame_filter)(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg);
  64. void *priv;
  65. } OCVContext;
  66. typedef struct {
  67. int type;
  68. int param1, param2;
  69. double param3, param4;
  70. } SmoothContext;
  71. static av_cold int smooth_init(AVFilterContext *ctx, const char *args, void *opaque)
  72. {
  73. OCVContext *ocv = ctx->priv;
  74. SmoothContext *smooth = ocv->priv;
  75. char type_str[128] = "gaussian";
  76. smooth->param1 = 3;
  77. smooth->param2 = 0;
  78. smooth->param3 = 0.0;
  79. smooth->param4 = 0.0;
  80. if (args)
  81. sscanf(args, "%127[^:]:%d:%d:%lf:%lf", type_str, &smooth->param1, &smooth->param2, &smooth->param3, &smooth->param4);
  82. if (!strcmp(type_str, "blur" )) smooth->type = CV_BLUR;
  83. else if (!strcmp(type_str, "blur_no_scale")) smooth->type = CV_BLUR_NO_SCALE;
  84. else if (!strcmp(type_str, "median" )) smooth->type = CV_MEDIAN;
  85. else if (!strcmp(type_str, "gaussian" )) smooth->type = CV_GAUSSIAN;
  86. else if (!strcmp(type_str, "bilateral" )) smooth->type = CV_BILATERAL;
  87. else {
  88. av_log(ctx, AV_LOG_ERROR, "Smoothing type '%s' unknown\n.", type_str);
  89. return AVERROR(EINVAL);
  90. }
  91. if (smooth->param1 < 0 || !(smooth->param1%2)) {
  92. av_log(ctx, AV_LOG_ERROR,
  93. "Invalid value '%d' for param1, it has to be a positive odd number\n",
  94. smooth->param1);
  95. return AVERROR(EINVAL);
  96. }
  97. if ((smooth->type == CV_BLUR || smooth->type == CV_BLUR_NO_SCALE || smooth->type == CV_GAUSSIAN) &&
  98. (smooth->param2 < 0 || (smooth->param2 && !(smooth->param2%2)))) {
  99. av_log(ctx, AV_LOG_ERROR,
  100. "Invalid value '%d' for param2, it has to be zero or a positive odd number\n",
  101. smooth->param2);
  102. return AVERROR(EINVAL);
  103. }
  104. av_log(ctx, AV_LOG_INFO, "type:%s param1:%d param2:%d param3:%f param4:%f\n",
  105. type_str, smooth->param1, smooth->param2, smooth->param3, smooth->param4);
  106. return 0;
  107. }
  108. static void smooth_end_frame_filter(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg)
  109. {
  110. OCVContext *ocv = ctx->priv;
  111. SmoothContext *smooth = ocv->priv;
  112. cvSmooth(inimg, outimg, smooth->type, smooth->param1, smooth->param2, smooth->param3, smooth->param4);
  113. }
  114. static int read_shape_from_file(int *cols, int *rows, int **values, const char *filename,
  115. void *log_ctx)
  116. {
  117. uint8_t *buf, *p, *pend;
  118. size_t size;
  119. int ret, i, j, w;
  120. if ((ret = av_file_map(filename, &buf, &size, 0, log_ctx)) < 0)
  121. return ret;
  122. /* prescan file to get the number of lines and the maximum width */
  123. w = 0;
  124. for (i = 0; i < size; i++) {
  125. if (buf[i] == '\n') {
  126. if (*rows == INT_MAX) {
  127. av_log(log_ctx, AV_LOG_ERROR, "Overflow on the number of rows in the file\n");
  128. return AVERROR_INVALIDDATA;
  129. }
  130. ++(*rows);
  131. *cols = FFMAX(*cols, w);
  132. w = 0;
  133. } else if (w == INT_MAX) {
  134. av_log(log_ctx, AV_LOG_ERROR, "Overflow on the number of columns in the file\n");
  135. return AVERROR_INVALIDDATA;
  136. }
  137. w++;
  138. }
  139. if (*rows > (FF_INTERNAL_MEM_TYPE_MAX_VALUE / (sizeof(int)) / *cols)) {
  140. av_log(log_ctx, AV_LOG_ERROR, "File with size %dx%d is too big\n",
  141. *rows, *cols);
  142. return AVERROR_INVALIDDATA;
  143. }
  144. if (!(*values = av_mallocz(sizeof(int) * *rows * *cols)))
  145. return AVERROR(ENOMEM);
  146. /* fill *values */
  147. p = buf;
  148. pend = buf + size-1;
  149. for (i = 0; i < *rows; i++) {
  150. for (j = 0;; j++) {
  151. if (p > pend || *p == '\n') {
  152. p++;
  153. break;
  154. } else
  155. (*values)[*cols*i + j] = !!isgraph(*(p++));
  156. }
  157. }
  158. av_file_unmap(buf, size);
  159. #ifdef DEBUG
  160. {
  161. char *line;
  162. if (!(line = av_malloc(*cols + 1)))
  163. return AVERROR(ENOMEM);
  164. for (i = 0; i < *rows; i++) {
  165. for (j = 0; j < *cols; j++)
  166. line[j] = (*values)[i * *cols + j] ? '@' : ' ';
  167. line[j] = 0;
  168. av_log(log_ctx, AV_LOG_DEBUG, "%3d: %s\n", i, line);
  169. }
  170. av_free(line);
  171. }
  172. #endif
  173. return 0;
  174. }
  175. static int parse_iplconvkernel(IplConvKernel **kernel, char *buf, void *log_ctx)
  176. {
  177. char shape_filename[128] = "", shape_str[32] = "rect";
  178. int cols = 0, rows = 0, anchor_x = 0, anchor_y = 0, shape = CV_SHAPE_RECT;
  179. int *values = NULL, ret;
  180. sscanf(buf, "%dx%d+%dx%d/%32[^=]=%127s", &cols, &rows, &anchor_x, &anchor_y, shape_str, shape_filename);
  181. if (!strcmp(shape_str, "rect" )) shape = CV_SHAPE_RECT;
  182. else if (!strcmp(shape_str, "cross" )) shape = CV_SHAPE_CROSS;
  183. else if (!strcmp(shape_str, "ellipse")) shape = CV_SHAPE_ELLIPSE;
  184. else if (!strcmp(shape_str, "custom" )) {
  185. shape = CV_SHAPE_CUSTOM;
  186. if ((ret = read_shape_from_file(&cols, &rows, &values, shape_filename, log_ctx)) < 0)
  187. return ret;
  188. } else {
  189. av_log(log_ctx, AV_LOG_ERROR,
  190. "Shape unspecified or type '%s' unknown\n.", shape_str);
  191. return AVERROR(EINVAL);
  192. }
  193. if (rows <= 0 || cols <= 0) {
  194. av_log(log_ctx, AV_LOG_ERROR,
  195. "Invalid non-positive values for shape size %dx%d\n", cols, rows);
  196. return AVERROR(EINVAL);
  197. }
  198. if (anchor_x < 0 || anchor_y < 0 || anchor_x >= cols || anchor_y >= rows) {
  199. av_log(log_ctx, AV_LOG_ERROR,
  200. "Shape anchor %dx%d is not inside the rectangle with size %dx%d.\n",
  201. anchor_x, anchor_y, cols, rows);
  202. return AVERROR(EINVAL);
  203. }
  204. *kernel = cvCreateStructuringElementEx(cols, rows, anchor_x, anchor_y, shape, values);
  205. av_freep(&values);
  206. if (!*kernel)
  207. return AVERROR(ENOMEM);
  208. av_log(log_ctx, AV_LOG_INFO, "Structuring element: w:%d h:%d x:%d y:%d shape:%s\n",
  209. rows, cols, anchor_x, anchor_y, shape_str);
  210. return 0;
  211. }
  212. typedef struct {
  213. int nb_iterations;
  214. IplConvKernel *kernel;
  215. } DilateContext;
  216. static av_cold int dilate_init(AVFilterContext *ctx, const char *args, void *opaque)
  217. {
  218. OCVContext *ocv = ctx->priv;
  219. DilateContext *dilate = ocv->priv;
  220. char default_kernel_str[] = "3x3+0x0/rect";
  221. char *kernel_str;
  222. const char *buf = args;
  223. int ret;
  224. dilate->nb_iterations = 1;
  225. if (args)
  226. kernel_str = av_get_token(&buf, ":");
  227. if ((ret = parse_iplconvkernel(&dilate->kernel,
  228. *kernel_str ? kernel_str : default_kernel_str,
  229. ctx)) < 0)
  230. return ret;
  231. av_free(kernel_str);
  232. sscanf(buf, ":%d", &dilate->nb_iterations);
  233. av_log(ctx, AV_LOG_INFO, "iterations_nb:%d\n", dilate->nb_iterations);
  234. if (dilate->nb_iterations <= 0) {
  235. av_log(ctx, AV_LOG_ERROR, "Invalid non-positive value '%d' for nb_iterations\n",
  236. dilate->nb_iterations);
  237. return AVERROR(EINVAL);
  238. }
  239. return 0;
  240. }
  241. static av_cold void dilate_uninit(AVFilterContext *ctx)
  242. {
  243. OCVContext *ocv = ctx->priv;
  244. DilateContext *dilate = ocv->priv;
  245. cvReleaseStructuringElement(&dilate->kernel);
  246. }
  247. static void dilate_end_frame_filter(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg)
  248. {
  249. OCVContext *ocv = ctx->priv;
  250. DilateContext *dilate = ocv->priv;
  251. cvDilate(inimg, outimg, dilate->kernel, dilate->nb_iterations);
  252. }
  253. static void erode_end_frame_filter(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg)
  254. {
  255. OCVContext *ocv = ctx->priv;
  256. DilateContext *dilate = ocv->priv;
  257. cvErode(inimg, outimg, dilate->kernel, dilate->nb_iterations);
  258. }
  259. typedef struct {
  260. const char *name;
  261. size_t priv_size;
  262. int (*init)(AVFilterContext *ctx, const char *args, void *opaque);
  263. void (*uninit)(AVFilterContext *ctx);
  264. void (*end_frame_filter)(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg);
  265. } OCVFilterEntry;
  266. static OCVFilterEntry ocv_filter_entries[] = {
  267. { "dilate", sizeof(DilateContext), dilate_init, dilate_uninit, dilate_end_frame_filter },
  268. { "erode", sizeof(DilateContext), dilate_init, dilate_uninit, erode_end_frame_filter },
  269. { "smooth", sizeof(SmoothContext), smooth_init, NULL, smooth_end_frame_filter },
  270. };
  271. static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
  272. {
  273. OCVContext *ocv = ctx->priv;
  274. char name[128], priv_args[1024];
  275. int i;
  276. char c;
  277. sscanf(args, "%127[^=:]%c%1023s", name, &c, priv_args);
  278. for (i = 0; i < FF_ARRAY_ELEMS(ocv_filter_entries); i++) {
  279. OCVFilterEntry *entry = &ocv_filter_entries[i];
  280. if (!strcmp(name, entry->name)) {
  281. ocv->name = entry->name;
  282. ocv->init = entry->init;
  283. ocv->uninit = entry->uninit;
  284. ocv->end_frame_filter = entry->end_frame_filter;
  285. if (!(ocv->priv = av_mallocz(entry->priv_size)))
  286. return AVERROR(ENOMEM);
  287. return ocv->init(ctx, priv_args, opaque);
  288. }
  289. }
  290. av_log(ctx, AV_LOG_ERROR, "No libopencv filter named '%s'\n", name);
  291. return AVERROR(EINVAL);
  292. }
  293. static av_cold void uninit(AVFilterContext *ctx)
  294. {
  295. OCVContext *ocv = ctx->priv;
  296. if (ocv->uninit)
  297. ocv->uninit(ctx);
  298. av_free(ocv->priv);
  299. memset(ocv, 0, sizeof(*ocv));
  300. }
  301. static void end_frame(AVFilterLink *inlink)
  302. {
  303. AVFilterContext *ctx = inlink->dst;
  304. OCVContext *ocv = ctx->priv;
  305. AVFilterLink *outlink= inlink->dst->outputs[0];
  306. AVFilterBufferRef *inpicref = inlink ->cur_buf;
  307. AVFilterBufferRef *outpicref = outlink->out_buf;
  308. IplImage inimg, outimg;
  309. fill_iplimage_from_picref(&inimg , inpicref , inlink->format);
  310. fill_iplimage_from_picref(&outimg, outpicref, inlink->format);
  311. ocv->end_frame_filter(ctx, &inimg, &outimg);
  312. fill_picref_from_iplimage(outpicref, &outimg, inlink->format);
  313. avfilter_unref_buffer(inpicref);
  314. avfilter_draw_slice(outlink, 0, outlink->h, 1);
  315. avfilter_end_frame(outlink);
  316. avfilter_unref_buffer(outpicref);
  317. }
  318. AVFilter avfilter_vf_ocv = {
  319. .name = "ocv",
  320. .description = NULL_IF_CONFIG_SMALL("Apply transform using libopencv."),
  321. .priv_size = sizeof(OCVContext),
  322. .query_formats = query_formats,
  323. .init = init,
  324. .uninit = uninit,
  325. .inputs = (AVFilterPad[]) {{ .name = "default",
  326. .type = AVMEDIA_TYPE_VIDEO,
  327. .draw_slice = null_draw_slice,
  328. .end_frame = end_frame,
  329. .min_perms = AV_PERM_READ },
  330. { .name = NULL}},
  331. .outputs = (AVFilterPad[]) {{ .name = "default",
  332. .type = AVMEDIA_TYPE_VIDEO, },
  333. { .name = NULL}},
  334. };