vf_libopencv.c 13 KB

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