vf_libopencv.c 14 KB

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