vf_libopencv.c 13 KB

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