You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

395 lines
13KB

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