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.

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