` and points\n at the detail anchor. Parameter types are still individually\n clickable — step 8g's pass 1 walks the inner HTML of this\n ``, skips the embedded ``, and linkifies any\n recognized type tokens it finds in the rest of the signature.\n Parameter names + default values stay plain (no link).\"\"\"\n from html import escape as _esc_html\n target = _member_anchor_target(m)\n # `::` is HTML-entity-encoded so the later `_linkify_cv_symbols`\n # text-level pass doesn't see `cv::Name` and nest a second\n # anchor inside ours. Browsers decode back to `:` on render.\n name_text = f\"cv::{m['name']}\".replace(\"::\", \"::\")\n name_html = (f'{name_text}')\n params_sig = m.get(\"params_sig\") or []\n # Pipe escaping: a literal `|` inside the cell would split the\n # markdown-table row, so swap to its HTML entity.\n def _esc(s: str) -> str:\n return _esc_html(s).replace(\"|\", \"|\")\n if not params_sig:\n inner = f\"{name_html}()\"\n elif len(params_sig) == 1:\n t, nm, dv = params_sig[0]\n decl = nm + (f\" = {dv}\" if dv else \"\")\n inner = f\"{name_html}({_esc(t)} {_esc(decl)})\"\n else:\n # Multi-line: `
` inside the code block gives one param\n # per line; CSS already handles `` line breaks for\n # the existing detail blocks.\n last_i = len(params_sig) - 1\n lines = [f\"{name_html}(\"]\n for i, (t, nm, dv) in enumerate(params_sig):\n tail = \" )\" if i == last_i else \",\"\n decl = nm + (f\" = {dv}\" if dv else \"\")\n lines.append(f\" {_esc(t)} {_esc(decl)}{tail}\")\n inner = \"
\".join(lines)\n return f'{inner}'\n\n # Renders the summary table (or enum synopsis) for one member kind given a\n # list of members — used both for the standard per-kind sections and for\n # the @name-group sections appended afterwards. Returns markdown lines\n # (no `## heading`); enum output already carries its own trailing blanks.\n #\n # `_is_core_page` extends the original `core_basic`-only treatment to\n # every Core-functionality group page (core_array, core_cluster,\n # core_utils, …). The user's spec: \"apply the same clickability +\n # redirection rules to all other pages in core functionality\" — that\n # means the clickable HTML enum synopsis, the \"More...\" link from\n # summary to detail, the per-page hand-rolled function detail blocks,\n # the rich return-type cell, and the per-enum detail section all flip\n # on together for every `core_*` group. Any page whose group name\n # starts with `core` qualifies (top-level group is \"core\"; children\n # are \"core_basic\", \"core_array\", …).\n _is_core_page = name.startswith(\"core\")\n _rich_return = _is_core_page\n\n def _summary_block(section_title: str, members: list) -> list[str]:\n out: list[str] = []\n if section_title == \"Functions\":\n out += [\"{.api-reference-table .api-function-table}\",\n \"| Return | Name | Description |\", \"|---|---|---|\"]\n for m in members:\n ret_type = _md_escape_cell(m[\"type\"])\n sig_link = _func_row_split_md(m)\n if not ret_type:\n ret = \"\\u00a0\" # ctor/dtor: blank cell, never backticked\n elif _rich_return:\n storage = \"static \" if m.get(\"static\") else \"\"\n if m.get(\"template\"):\n ret = f\"`{m['template']}`
`{storage}{ret_type}`\"\n else:\n ret = f\"`{storage}{ret_type}`\"\n else:\n ret = f\"`{ret_type}`\"\n out.append(f\"| {ret} | {sig_link} | {_md_escape_cell(m['brief'])} |\")\n elif section_title == \"Typedefs\":\n # Type cell as a code span so steps 8b/8g linkify its tokens.\n out += [\"{.api-typedef-table}\",\n \"| Type | Name | Description |\", \"|---|---|---|\"]\n for m in members:\n t = _md_escape_cell(m[\"type\"])\n t_cell = f\"`{t}`\" if t else \"\\u00a0\"\n # Function-pointer typedefs (e.g. cv::dnn::ActivationFunc) store\n # the name inside the type (\"void(*\") with the params in\n # (\")(const void *...)\"). Split the type: keep only\n # the return type (\"void\") in the Type column and move the\n # \"(*)(args)\" declarator into the Name column, so the\n # row reads naturally as \"void | (*cv::dnn::ActivationFunc)(...)\"\n # rather than the disjoint \"void(*\" / \"cv::ActivationFunc)(...)\".\n # Plain typedefs have no argsstring, so they keep \"cv::\".\n fp_args = (m.get(\"args\") or \"\").strip()\n if fp_args and \"(\" in (m.get(\"type\") or \"\"):\n ret, _sep, rest = (m.get(\"type\") or \"\").strip().partition(\"(\")\n t_cell = f\"`{_md_escape_cell(ret.strip())}`\" if ret.strip() else \"\\u00a0\"\n label = \"(\" + rest + (m.get(\"qualified\") or f\"cv::{m['name']}\") + fp_args\n else:\n label = f\"cv::{m['name']}\"\n name_link = _member_anchor_link(m, label.replace(\"|\", \"\\\\|\"))\n out.append(f\"| {t_cell} | {name_link} | {_md_escape_cell(m['brief'])} |\")\n elif section_title == \"Variables\":\n out += [\"{.api-reference-table}\",\n \"| Type | Name | Description |\", \"|---|---|---|\"]\n for m in members:\n t = _md_escape_cell(m[\"type\"])\n t_cell = f\"`{t}`\" if t else \"\\u00a0\"\n name_link = _member_anchor_link(m, m[\"name\"])\n out.append(f\"| {t_cell} | {name_link} | {_md_escape_cell(m['brief'])} |\")\n elif section_title == \"Enumerations\":\n # Code-style synopsis (Doxygen layout) instead of name/desc table.\n # On non-core group pages we emit the synopsis only — the\n # per-value initializer list is already self-explanatory. On\n # every Core-functionality page we additionally append a\n # \"More...\" link, inline at the end of the brief description\n # (or alone below the synopsis when no brief exists),\n # pointing to that enum's detail block in the \"Enumeration\n # Type Documentation\" section emitted by the detail loop\n # below.\n _enum_more_link = True\n # On every Core-functionality page the synopsis is emitted\n # as raw HTML (NOT a ```cpp code fence) so every `cv::…`\n # token becomes its own `` linking to the enum's detail\n # block. We hand-roll Pygments-style spans (`k`, `n`, `p`)\n # so the existing `.highlight pre` styling kicks in and the\n # synopsis still looks like a code block.\n _clickable_synopsis = True\n import html as _html_mod\n # Encode `::` so translate's cv-linkifier skips it.\n def _safe(s: str) -> str:\n return _html_mod.escape(s).replace(\"::\", \"::\")\n for m in members:\n # Named enums anchor on their `### Name` heading slug. Anonymous\n # enums anchor on the detail block's MyST `({id})=` target, whose\n # slug normalizes `_`-runs to `-`; a raw `#` with underscores\n # does NOT resolve in MyST, so match the normalized form here.\n _enum_anchor = (m[\"name\"].lower() if m.get(\"name\")\n else re.sub(r\"_+\", \"-\", m[\"id\"]))\n _more = \"\"\n if _enum_more_link:\n _more = f\"[View details](#{_enum_anchor})\"\n if _clickable_synopsis:\n _qual = m[\"qualified\"] or m[\"name\"]\n _is_strong = bool(m.get(\"strong\"))\n _keyword = \"enum struct\" if _is_strong else \"enum\"\n # Enumerator-name prefix: scoped → \"cv::EnumName::\",\n # unscoped → the enum's parent scope (so values\n # render as `cv::ACCESS_READ`).\n if _is_strong:\n _val_prefix = _qual + \"::\"\n elif \"::\" in _qual:\n _val_prefix = _qual.rsplit(\"::\", 1)[0] + \"::\"\n else:\n _val_prefix = \"\"\n _href = f\"#{_enum_anchor}\"\n out.append(\n ''\n )\n # Anonymous enums have no name to link; emit a bare `enum {`.\n _name_html = (\n f''\n f'{_safe(_qual)} ' if _qual else \"\")\n out.append(\n f'{_html_mod.escape(_keyword)} '\n f'{_name_html}{{'\n )\n _vals = m.get(\"enum_values\") or []\n for _i, _v in enumerate(_vals):\n _comma = (','\n if _i < len(_vals) - 1 else '')\n _init = (' ' + _html_mod.escape(_v[\"initializer\"])\n if _v.get(\"initializer\") else '')\n _full = _val_prefix + _v[\"name\"]\n # All enumerators link to the enum's detail section via\n # its `#` heading anchor (which exists on the\n # page). Per-value `_CPPv4…` ids are NOT emitted in the\n # detail block, so a per-value href would dead-link.\n out.append(\n f' '\n f'{_safe(_full)}'\n f'{_init}{_comma}'\n )\n out.append('} ')\n # Blank line closes the raw-HTML block (CommonMark rule 7).\n out.append(\"\")\n else:\n out.append(\"```cpp\")\n out.extend(_enum_synopsis_lines(m))\n out.append(\"```\")\n # Brief + the inline \"More...\" link (when generated).\n if m[\"brief\"]:\n line = _md_escape_cell(m[\"brief\"])\n if _more:\n line = f\"{line} {_more}\"\n _more = \"\"\n out.append(line)\n if _more:\n out.append(_more)\n out.append(\"\")\n else: # Macros\n out += [\"{.api-reference-table}\", \"| Name | Description |\", \"|---|---|\"]\n for m in members:\n name_link = _member_anchor_link(m, m[\"name\"])\n out.append(f\"| {name_link} | {_md_escape_cell(m['brief'])} |\")\n return out\n\n _named_groups: list[tuple[str, str, list]] = [] # (header, section_title, members)\n def _grp_detail_covers(m, kind_key):\n # Must mirror the detail loop's skips below: a summary member lacks a\n # detail block only if it's a class member or a template specialization.\n if kind_key in (\"function\", \"variable\") and _is_class_member(m):\n return False\n if _is_template_spec(m):\n return False\n return True\n for kind_key, section_title in _MEMBERDEF_SECTIONS:\n items = node[\"sections\"].get(section_title, [])\n if not items:\n continue\n ungrouped = [m for m in items if not (m.get(\"section_header\") or \"\")]\n for _hdr, _members in _group_by_section_header(\n [m for m in items if (m.get(\"section_header\") or \"\")]):\n _named_groups.append((_hdr, section_title, _members))\n # Drop the redundant summary only when the detail loop covers every\n # ungrouped member; keep Enumerations always.\n if ungrouped:\n _covered = section_title != \"Enumerations\" and all(\n _grp_detail_covers(m, kind_key) for m in ungrouped)\n if not _covered:\n lines.append(f\"## {section_title}\")\n lines.append(\"\")\n lines += _summary_block(section_title, ungrouped)\n lines.append(\"\")\n for _hdr, section_title, _members in _named_groups:\n lines.append(f\"## {_hdr}\")\n lines.append(\"\")\n lines += _summary_block(section_title, _members)\n lines.append(\"\")\n\n # Detail blocks via `_render_member_detail` (breathe chokes); macros keep\n # `{doxygendefine}`; enum detail is hand-rolled (every core_* page).\n seen_define_names: set[str] = set()\n for kind_key, section_title in _MEMBERDEF_SECTIONS:\n items = node[\"sections\"].get(section_title, [])\n if not items:\n continue\n _core_basic_funcs = (_is_core_page and kind_key == \"function\")\n _ov_total: dict[str, int] = {}\n _ov_idx: dict[str, int] = {}\n _slug_seen: set[str] = set()\n if _core_basic_funcs:\n for m in items:\n if _is_class_member(m) or _is_template_spec(m):\n continue\n _ov_total[m[\"name\"]] = _ov_total.get(m[\"name\"], 0) + 1\n blocks: list[list[str]] = []\n for m in items:\n # Class members render on their own class page; skip on the group.\n if kind_key in (\"function\", \"variable\") and _is_class_member(m):\n continue\n # Template specializations carry `<…>`; summary table still lists them.\n if _is_template_spec(m):\n continue\n if _core_basic_funcs:\n short = m[\"name\"]\n _ov_idx[short] = _ov_idx.get(short, 0) + 1\n slug = _func_slug(short)\n emit_anchor = slug not in _slug_seen\n _slug_seen.add(slug)\n blocks.append(_render_core_basic_func(\n m, _ov_idx[short], _ov_total.get(short, 1), emit_anchor))\n continue\n if kind_key == \"enum\":\n # Every core_* page (gated by the early `continue` above).\n # Hand-rolled in place of `{doxygenenum}` — breathe's directive\n # drops every enumerator's initializer and `briefdescription`\n # (renders the `` empty), so the live page's per-value\n # `=1<<24` constants and one-line descriptions vanished.\n # Pulling from the XML metadata ourselves restores them.\n _qual = m[\"qualified\"] or m[\"name\"]\n _is_strong = bool(m.get(\"strong\"))\n _keyword = \"enum class\" if _is_strong else \"enum\"\n _qual_safe = _qual.replace(\"::\", \"::\")\n if m.get(\"name\"):\n _enum_href = f\"#{m['name'].lower()}\"\n blk: list[str] = [\n f\"({_sphinx_cpp_v4_id(_qual)})=\",\n f\"### {m['name']}\",\n \"\",\n f''\n f'{_keyword} {_qual_safe}',\n \"\",\n ]\n else:\n # Anonymous enum has no heading slug; anchor it with a MyST\n # `({id})=` target (what `_enum_anchor` links to). A raw\n # `` is not a MyST reference target and dead-links.\n blk = [\n f\"({m['id']})=\",\n f\"### {_keyword}\",\n \"\",\n ]\n if m.get(\"include_file\"):\n _einc = m[\"include_file\"]\n _ehref = _include_page_href(_einc)\n if _ehref:\n blk += [\n \"{.opencv-api-include}\",\n f''\n f'#include <'\n f'{_einc}>',\n \"\",\n ]\n else:\n blk += [\"{.opencv-api-include}\",\n f\"`#include <{_einc}>`\", \"\"]\n if m.get(\"brief\"):\n blk += [m[\"brief\"], \"\"]\n if m.get(\"detailed\"):\n blk += [m[\"detailed\"], \"\"]\n _vals = m.get(\"enum_values\") or []\n if _vals:\n blk += [\"**Enumerator:**\", \"\"]\n blk += _enumerator_list_table(_vals, _qual, _is_strong)\n blocks.append(blk)\n continue\n if kind_key == \"define\":\n # Macros aren't namespaced; dedupe arity-overloaded ones.\n if m[\"name\"] in seen_define_names:\n continue\n seen_define_names.add(m[\"name\"])\n # Hand-rolled block (breathe's {doxygendefine} drops the #include and\n # the macro's Value); `_render_member_detail` keeps `#define NAME(…)`,\n # the include row and the Value, and emits the `(id)=` cross-ref anchor.\n m = _enhance_xphoto_member(m)\n _full_name = m[\"qualified\"] or m[\"name\"]\n blocks.append(\n _render_member_detail(m, _full_name))\n if not blocks:\n continue\n lines.append(f\"## {_MEMBER_DETAIL_SECTION[section_title]}\")\n lines.append(\"\")\n for b in blocks:\n lines += b\n\n # Hidden toctree registers per-class pages in the sidebar.\n if node[\"innerclasses\"]:\n lines += [\"```{toctree}\", \":hidden:\", \":maxdepth: 1\", \"\"]\n for c in node[\"innerclasses\"]:\n lines.append(_class_page_name(c[\"refid\"]))\n lines += [\"```\", \"\"]\n\n _stub_write(out, \"\\n\".join(lines) + \"\\n\")\n # Subgroup pages: recurse (no-op for leaf groups).\n for child in node[\"children\"]:\n _write_api_stub(child, out_dir, classes_seen, ns_map)\n\n\ndef _collect_base_chain(data: dict, xml_dir: pathlib.Path) -> list:\n \"\"\"Transitive base classes in inheritance order, each with its loaded class\n data — for rendering Doxygen's \"inherited from \" member sections.\n Deduped and cycle-safe.\"\"\"\n out: list = []\n seen: set = set()\n queue = list(data.get(\"bases\", []))\n while queue:\n refid, name, _prot = queue.pop(0)\n if not refid or refid in seen:\n continue\n seen.add(refid)\n bdata = _read_class_data(refid, xml_dir)\n if bdata is None:\n continue\n out.append((refid, bdata.get(\"name\") or name, bdata))\n queue.extend(bdata.get(\"bases\", []))\n return out\n\n\ndef _inherited_section(summary_title: str, base_qual: str, base_refid: str,\n items: list) -> list[str]:\n \"\"\"A collapsible \" inherited from \" block (sphinx-design\n dropdown). The base name and every member name are clickable links; the\n return-type column stays plain — only the links are blue.\"\"\"\n # Absolute (root-relative) docname so the base link resolves even when the\n # base class lives in a different module dir (e.g. cv::Algorithm in\n # main_modules linked from an extra_modules page).\n _dn = _ANCHOR_TO_DOC.get(base_refid)\n base_link = f\"[{base_qual}](/{_dn}.md)\" if _dn else base_qual\n out = [f\":::{{dropdown}} {summary_title} inherited from {base_link}\",\n \":animate: fade-in\", \"\",\n \"{.api-reference-table .api-function-table}\",\n \"| Return | Name | Description |\", \"|---|---|---|\"]\n for m in items:\n ret = _md_escape_cell(m[\"type\"])\n if ret and m.get(\"static\"):\n ret = \"static \" + ret\n ret_cell = f\"`{ret}`\" if ret else \" \"\n if m[\"kind\"] == \"function\":\n label = _func_sig_md(m[\"name\"], m.get(\"params_sig\"))\n sig_link = f\"[{label}](#{m['id']})\"\n else:\n sig = f\"{m['name']}{_md_escape_cell(m['args'])}\"\n sig_link = f\"[`{sig}`](#{m['id']})\"\n out.append(f\"| {ret_cell} | {sig_link} | {_md_escape_cell(m['brief'])} |\")\n out += [\"\", \":::\", \"\"]\n return out\n\n\n# sectiondef kind → summary heading, in Doxygen order.\n_CLASS_SUMMARY_SECTIONS = [\n (\"public-type\", \"Public Types\"),\n (\"public-func\", \"Public Member Functions\"),\n (\"public-static-func\", \"Static Public Member Functions\"),\n (\"public-attrib\", \"Public Attributes\"),\n (\"public-static-attrib\", \"Static Public Attributes\"),\n (\"protected-type\", \"Protected Types\"),\n (\"protected-func\", \"Protected Member Functions\"),\n (\"protected-static-func\", \"Static Protected Member Functions\"),\n (\"protected-attrib\", \"Protected Attributes\"),\n (\"protected-static-attrib\", \"Static Protected Attributes\"),\n (\"friend\", \"Friends\"),\n]\n\n\ndef _param_item_lines(nm: str, desc: str) -> list[str]:\n \"\"\"Render one `**Parameters**` entry, indenting any multi-line / bulleted\n description so it nests under the param bullet. Without this a description\n carrying its own list (e.g. calibration `flags`) collapses into a run-on\n blob or breaks out past the card boundary as a flat sibling list.\n\n Param NAME renders as a monospace box (`code.opencv-param-name`, styled\n for light + dark in custom.css).\"\"\"\n import html as _html\n chip = f'{_html.escape(nm)}'\n if not desc:\n return [f\"- {chip}\"]\n lines = desc.split(\"\\n\")\n out = [f\"- {chip} — {lines[0]}\"]\n # Continuation lines align with the bullet's content column (2 spaces);\n # blank lines stay empty so the nested list/paragraphs render loosely.\n out += [f\" {ln}\" if ln.strip() else \"\" for ln in lines[1:]]\n return out\n\n\ndef _enumerator_list_table(values: list[dict], enum_qualified: str,\n is_strong: bool, with_anchors: bool = False) -> list[str]:\n \"\"\"Render an enum's values as a MyST `{list-table}`.\n\n Unlike a Markdown pipe table, list-table cells hold block content, so a\n value's description keeps its `@note` admonition, lists and links instead of\n being flattened (see `_enum_value_desc`). `with_anchors` adds a per-value\n `` so the clickable class-synopsis links resolve to each row.\"\"\"\n if not values:\n return []\n has_desc = any((v.get(\"brief\") or \"\").strip() for v in values)\n # Lead with a blank line: the class-member enum path emits a raw `` (and\n # optional `
` brief) immediately before this table. Without the separator\n # CommonMark folds the ````{list-table}` opener and its `:option:` lines into\n # that HTML block (HTML blocks run until a blank line), leaving the closing\n # ``` orphaned — it then opens a stray code block that swallows the rest of\n # the page (Member Function docs, etc.) as literal text.\n out = [\"\", \"```{list-table}\", \":header-rows: 0\",\n f\":widths: {'30 70' if has_desc else '100'}\",\n \":class: opencv-enum-table\", \"\"]\n for v in values:\n nm = v[\"name\"]\n cell = \"\"\n if with_anchors:\n cell = f''\n cell += f\"`{nm}`\"\n py = _python_enum_name(enum_qualified, nm, is_strong)\n if py:\n cell += f\"
Python: `{py}`\"\n out.append(f\"* - {cell}\")\n if has_desc:\n desc = (v.get(\"brief\") or \"\").strip()\n if desc:\n _dl = desc.split(\"\\n\")\n out.append(f\" - {_dl[0]}\")\n out += [(\" \" + ln) if ln.strip() else \"\" for ln in _dl[1:]]\n else:\n out.append(\" -\")\n out += [\"```\", \"\"]\n return out\n\n\ndef _signature_lines(head: str, params_sig: list) -> list[str]:\n \"\"\"Doxygen-style declaration split across lines, one parameter per line\n (`type name`, single-spaced — no column padding).\n\n `head` is everything up to the `(` (e.g. ``double cv::calibrateCamera``).\n Returns plain strings; the caller wraps each as inline code. A 0/1-param\n declaration stays on one line — the wrapping only helps long lists.\"\"\"\n if not params_sig:\n return [f\"{head}()\"]\n def _decl(nm: str, dv: str) -> str:\n return (nm + (f\" = {dv}\" if dv else \"\")).strip()\n if len(params_sig) == 1:\n t, nm, dv = params_sig[0]\n inner = f\"{t} {_decl(nm, dv)}\".strip()\n return [f\"{head}({inner})\"]\n lines = [f\"{head}(\"]\n last = len(params_sig) - 1\n for i, (t, nm, dv) in enumerate(params_sig):\n tail = \" )\" if i == last else \",\"\n # Single space between type and name (no column padding).\n lines.append(f\" {t} {_decl(nm, dv)}{tail}\".rstrip())\n return lines\n\n\ndef _func_sig_md(name: str, params_sig: list) -> str:\n \"\"\"Multi-line signature for a summary-table cell, matching the detail block.\n\n Each line from `_signature_lines` becomes its own inline-code span joined\n by `
`, so the padded type column survives (CSS gives these spans\n `white-space: pre-wrap`) and the whole signature stays one clickable link.\n Pipes are escaped per line so an `A|B` default can't break the table cell.\"\"\"\n return \"
\".join(\n f\"`{ln.replace('|', chr(0x5c) + '|')}`\"\n for ln in _signature_lines(name, params_sig or []))\n\n\ndef _render_member_detail(m: dict, full_name: str) -> list[str]:\n \"\"\"Render one member's detail block from XML (no breathe; it chokes).\n\n `full_name` is the declaration name; `(id)=` keeps `#refid` links working.\"\"\"\n short = m[\"name\"]\n kind = m[\"kind\"]\n # Heading is just `name()` for functions; full signature is in the block below.\n head = f\"{short}()\" if kind == \"function\" else short\n if m.get(\"id\"):\n _LOCAL_MEMBER_IDS.add(m[\"id\"])\n out = [f\"({m['id']})=\", f\"### {head}\".rstrip(), \"\"]\n\n # Declaration (template line, if any, then the C++ signature).\n tmpl = m.get(\"template\") or \"\"\n prefix = \"static \" if m.get(\"static\") else \"\"\n typ = (m.get(\"type\") or \"\").strip()\n if kind == \"function\":\n # One parameter per line, type column padded so names align.\n # sig_prefix/sig_suffix allow callers to inject qualifiers (e.g. virtual/const = 0).\n sig_prefix = m.get(\"sig_prefix\") or \"\"\n sig_suffix = m.get(\"sig_suffix\") or \"\"\n head = f\"{sig_prefix}{prefix}{typ + ' ' if typ else ''}{full_name}\"\n sig_lines = _signature_lines(head, m.get(\"params_sig\") or [])\n if sig_suffix:\n sig_lines[-1] = sig_lines[-1] + sig_suffix\n elif kind == \"define\":\n # `#define NAME(args)` — macro params carry only a name, no type.\n mp = m.get(\"macro_params\") or []\n params = f\"({', '.join(mp)})\" if mp else \"\"\n sig_lines = [f\"#define {short}{params}\"]\n elif kind == \"typedef\":\n # Function-pointer typedefs (e.g. cv::dnn::ActivationFunc) are split by\n # Doxygen across //: type=\"void(*\", the name sits\n # in the middle, and argsstring=\")(const void *input, …)\". Append the\n # args or the decl truncates to \"typedef void(* cv::dnn::ActivationFunc\".\n # Plain typedefs carry an empty argsstring, so this is a no-op for them.\n args = (m.get(\"args\") or \"\").strip()\n sig_lines = [f\"typedef {typ} {full_name}{args}\".strip()]\n else: # variable / attribute — append the `= value` initializer if present.\n decl = f\"{prefix}{typ + ' ' if typ else ''}{full_name}\".strip()\n init = (m.get(\"initializer\") or \"\").strip()\n sig_lines = [f\"{decl} {init}\".strip() if init else decl]\n # Template clause + declaration as inline code (keeps token-linkifier\n # active); `{.opencv-api-sig}` lets the CSS preserve the alignment spaces.\n # Lines carrying a `` (a type/typedef/enum value Doxygen hyperlinks)\n # are emitted as an HTML with explicit, refid-resolved links — same\n # element as a markdown code span, so the box format is unchanged.\n _url_by_text: dict = {}\n for _t, _rid in (m.get(\"sig_refs\") or []):\n if _t and _t not in _url_by_text:\n _u = _rel_doc_url(_rid)\n if _u:\n _url_by_text[_t] = _u\n\n import html as _html_pkg\n def _code(ln: str) -> str:\n if _url_by_text:\n _h = _sig_html_with_links(ln, _url_by_text)\n if _h is not None:\n return f'{_h}'\n return (f''\n f'{_html_pkg.escape(ln)}')\n _sig = ([f\"`{tmpl}`\"] if tmpl else []) + [_code(ln) for ln in sig_lines]\n out += [\"{.opencv-api-sig}\", \"\\\\\\n\".join(_sig), \"\"]\n\n inc = (m.get(\"include_file\") or \"\").strip()\n if inc:\n _href = _include_page_href(inc)\n if _href:\n out += [\n \"{.opencv-api-include}\",\n f''\n f'#include <{inc}>',\n \"\",\n ]\n else:\n out += [\"{.opencv-api-include}\", f\"`#include <{inc}>`\", \"\"]\n\n # Macro body, shown as docs.opencv.org's \"Value:\" row.\n if kind == \"define\":\n val = (m.get(\"initializer\") or \"\").strip()\n if val:\n out += [\"**Value:**\", \"\", \"```cpp\", val, \"```\", \"\"]\n\n # Python binding signature(s) from pyopencv_signatures.json (dormant until built).\n if kind == \"function\":\n py_entries = (_PY_SIGNATURES.get(full_name)\n or _PY_SIGNATURES.get(f\"cv::{full_name}\")\n or [])\n if py_entries:\n out += [\"**Python:**\", \"\"]\n for e in py_entries:\n py_name = e.get(\"name\", \"\")\n if not py_name:\n continue\n py_sig = f\"{py_name}({e.get('arg', '')})\"\n py_ret = e.get(\"ret\", \"\")\n if py_ret and py_ret not in (\"None\", \"\"):\n py_sig += f\" -> {py_ret}\"\n out += [\"```python\", py_sig, \"```\", \"\"]\n\n if m.get(\"brief\"):\n out += [m[\"brief\"], \"\"]\n if m.get(\"detailed\"):\n out += [m[\"detailed\"], \"\"]\n if m.get(\"params\"):\n out += [\"**Parameters**\", \"\"]\n for nm, desc in m[\"params\"]:\n out += _param_item_lines(nm, desc)\n out.append(\"\")\n if m.get(\"returns\"):\n out += [\"**Returns**\", \"\", m[\"returns\"], \"\"]\n out += _call_graph_lines(m)\n return out\n\n\ndef _render_core_basic_func(m: dict, idx: int, total: int,\n emit_anchor: bool) -> list[str]:\n \"\"\"Hand-rolled Function block for core_basic (breathe can't parse it).\n\n Signature is inline code for token-linkifier (translate step 8g); heading\n `{#cv-slug}` anchor (first overload) is the Functions-table target (step 8i).\"\"\"\n short = m[\"name\"]\n slug = _func_slug(short)\n suffix = f\" [{idx}/{total}]\" if total > 1 else \"\"\n head = f\"### {short}(){suffix}\"\n out = [f\"{head} {{#{slug}}}\" if emit_anchor else head, \"\"]\n # Template clause + signature as inline code (keeps token-linkifier active).\n ret = m.get(\"type\") or \"\"\n storage = (\"static \" if m.get(\"static\") else \"\") \\\n + (\"inline \" if m.get(\"inline\") else \"\")\n qname = m[\"qualified\"] or m[\"name\"]\n head = f\"{storage}{ret} {qname}\".strip()\n sig_lines = _signature_lines(head, m.get(\"params_sig\") or [])\n _url_by_text: dict = {}\n for _t, _rid in (m.get(\"sig_refs\") or []):\n if _t and _t not in _url_by_text:\n _u = _rel_doc_url(_rid)\n if _u:\n _url_by_text[_t] = _u\n\n import html as _html_pkg\n def _code(ln: str) -> str:\n if _url_by_text:\n _h = _sig_html_with_links(ln, _url_by_text)\n if _h is not None:\n return f'{_h}'\n return (f''\n f'{_html_pkg.escape(ln)}')\n _sig = ([f\"`{m['template']}`\"] if m.get(\"template\") else []) + \\\n [_code(ln) for ln in sig_lines]\n out += [\"{.opencv-api-sig}\", \"\\\\\\n\".join(_sig), \"\"]\n if m.get(\"include_file\"):\n _ipath = m[\"include_file\"]\n _href = _include_page_href(_ipath)\n if _href:\n out += [\n \"{.opencv-api-include}\",\n f''\n f'#include <{_ipath}>',\n \"\",\n ]\n else:\n out += [\"{.opencv-api-include}\", f\"`#include <{_ipath}>`\", \"\"]\n if m.get(\"brief\"):\n out += [m[\"brief\"], \"\"]\n if m.get(\"detailed\"):\n out += [m[\"detailed\"], \"\"]\n if m.get(\"params\"):\n out += [\"**Parameters**\", \"\"]\n for nm, desc in m[\"params\"]:\n out += _param_item_lines(nm, desc)\n out.append(\"\")\n if m.get(\"returns\"):\n out += [f\"**Returns** — {m['returns']}\", \"\"]\n out += _call_graph_lines(m)\n return out\n\n\ndef _write_class_stub(cls: dict, out_dir: pathlib.Path,\n xml_dir: pathlib.Path, inline: bool = False):\n \"\"\"One .md per inner class, mirroring Doxygen's class-page layout.\n\n Falls back to `{doxygenclass}`/`{doxygenstruct}` if class XML can't be read.\n When `inline=True`, the body lines are returned (no title, not written) so a\n single-class \"shell\" group page can host the class content directly.\"\"\"\n page = _class_page_name(cls[\"refid\"])\n out = out_dir / f\"{page}.md\"\n qualified = cls[\"qualified\"] or cls[\"name\"]\n kind_label = cls[\"kind\"].title()\n title = f\"{kind_label} {qualified}\"\n # No `{#refid}` anchor; `_generate_api_stubs` seeds `_ANCHOR_TO_DOC` instead.\n lines = [] if inline else [f\"# {title}\", \"\"]\n\n # Class-page header: brief + `View details` + `#include` line.\n _header_data = _read_class_data(cls[\"refid\"], xml_dir)\n if _header_data is not None:\n import html as _html_pkg\n _brief = (_header_data.get(\"brief\") or \"\").strip()\n if _brief:\n # Link only when there's a detailed description to jump to; skip when\n # inlined, where the #detailed-description anchor collides with a\n # sibling class and the detail is right below anyway.\n _more = (\n ' View details'\n if _header_data.get(\"detailed\") and not inline else \"\"\n )\n lines.append(\n f''\n f'{_html_pkg.escape(_brief)}{_more}
'\n )\n lines.append(\"\")\n _inc = (_header_data.get(\"include\") or \"\").strip()\n if _inc:\n _chref = _include_page_href(_inc)\n if _chref:\n _inc_code = (\n f'#include <'\n f'{_html_pkg.escape(_inc)}>')\n else:\n _inc_code = f'#include <{_html_pkg.escape(_inc)}>'\n lines.append(\n f'{_inc_code}'\n )\n lines.append(\"\")\n\n _svg = _find_collaboration_svg(cls[\"refid\"], xml_dir.parent / \"html\")\n if _svg is not None:\n lines += _diagram_svg_lines(\n _svg, out_dir,\n f\"Collaboration diagram for {qualified}\",\n f\"Collaboration diagram for {qualified}:\")\n\n data = _read_class_data(cls[\"refid\"], xml_dir)\n if data is None: # missing XML\n directive = \"doxygenstruct\" if cls[\"kind\"] == \"struct\" else \"doxygenclass\"\n lines += [\n f\"```{{{directive}}} {qualified}\",\n \":project: opencv\",\n \":members:\",\n \":protected-members:\",\n \":undoc-members:\",\n \"```\",\n \"\",\n ]\n _stub_write(out, \"\\n\".join(lines))\n return\n\n # 1) Summary tables in Doxygen's order, each followed by the same-kind\n # members inherited from base classes (collapsible, like Doxygen).\n base_chain = _collect_base_chain(data, xml_dir)\n _additional: list = [] # protected/private inherited -> trailing group\n for sd_kind, summary_title in _CLASS_SUMMARY_SECTIONS:\n items = data[\"sections\"].get(sd_kind, [])\n inherited = [(rid, qual, bdata[\"sections\"].get(sd_kind, []))\n for rid, qual, bdata in base_chain\n if bdata[\"sections\"].get(sd_kind, [])]\n # Public inherited members sit inline under their section; inherited\n # protected/private members go in a trailing \"Additional Inherited\n # Members\" group, matching Doxygen's layout.\n if sd_kind.startswith(\"public\"):\n inline_inherited = inherited\n else:\n inline_inherited = []\n _additional += [(summary_title, rid, qual, bi)\n for rid, qual, bi in inherited]\n non_enum_items = [m for m in items if m[\"kind\"] != \"enum\"]\n enum_items = [m for m in items if m[\"kind\"] == \"enum\"]\n # Own typedef/function/variable get a detail block below, so drop their\n # summary rows; keep kinds without one (e.g. friends) and enums.\n kept_rows = [m for m in non_enum_items\n if m[\"kind\"] not in (\"typedef\", \"function\", \"variable\")]\n if not kept_rows and not enum_items and not inline_inherited:\n continue\n lines.append(f\"## {summary_title}\")\n lines.append(\"\")\n if kept_rows:\n lines += [\"{.api-reference-table .api-function-table}\",\n \"| Return | Name | Description |\", \"|---|---|---|\"]\n for m in kept_rows:\n ret = _md_escape_cell(m[\"type\"])\n if ret and m[\"static\"]:\n ret = \"static \" + ret\n ret_cell = f\"`{ret}`\" if ret else \"\\u00a0\"\n if m[\"kind\"] == \"function\":\n sig_link = f\"[{_func_sig_md(m['name'], m.get('params_sig'))}](#{m['id']})\"\n else:\n sig = f\"{m['name']}{_md_escape_cell(m['args'])}\"\n sig_link = f\"[`{sig}`](#{m['id']})\"\n lines.append(\n f\"| {ret_cell} | {sig_link} | {_md_escape_cell(m['brief'])} |\")\n lines.append(\"\")\n for m in enum_items:\n if m[\"brief\"]:\n lines.append(_md_escape_cell(m[\"brief\"]))\n lines.append(\"\")\n # HTML synopsis: `` ids match the `_CPPv4…` detail anchors.\n lines.extend(_enum_synopsis_html(m, strip_scope=qualified))\n lines.append(\"\")\n # Public members of this kind inherited from each base class (inline).\n for _b_refid, _b_qual, _b_items in inline_inherited:\n lines += _inherited_section(summary_title, _b_qual, _b_refid, _b_items)\n\n # Inherited protected/private members, grouped like Doxygen.\n if _additional:\n lines += [\"## Additional Inherited Members\", \"\"]\n for _title, _b_refid, _b_qual, _b_items in _additional:\n lines += _inherited_section(_title, _b_qual, _b_refid, _b_items)\n\n _directive = \"doxygenstruct\" if cls[\"kind\"] == \"struct\" else \"doxygenclass\"\n examples = _find_examples_for_class(qualified.rsplit(\"::\", 1)[-1])\n if data[\"detailed\"]:\n lines += [\n \"## Detailed Description\",\n \"\",\n f\"```{{{_directive}}} {qualified}\",\n \":project: opencv\",\n \"```\",\n \"\",\n ]\n lines += _render_examples_block(examples)\n elif (data.get(\"brief\") or \"\").strip():\n # No separate detailed text — show the brief under a Detailed\n # Description heading so the section (and its `#detailed-description`\n # anchor, which \"More…\" links target) exists, like the original docs.\n lines += [\"## Detailed Description\", \"\", data[\"brief\"].strip(), \"\"]\n lines += _render_examples_block(examples)\n elif examples:\n lines += [\"## Examples\", \"\"]\n lines += _render_examples_block(examples)\n\n # 3) Per-member detail blocks (ctor/dtor split from other functions).\n class_simple = qualified.rsplit(\"::\", 1)[-1]\n\n typedef_items: list[dict] = []\n enum_items_all: list[dict] = []\n ctor_dtor_items: list[dict] = []\n func_items: list[dict] = []\n var_items: list[dict] = []\n for sd_items in data[\"sections\"].values():\n for m in sd_items:\n if m[\"kind\"] == \"typedef\":\n typedef_items.append(m)\n elif m[\"kind\"] == \"enum\":\n enum_items_all.append(m)\n elif m[\"kind\"] == \"function\":\n if m[\"name\"] == class_simple or m[\"name\"] == f\"~{class_simple}\":\n ctor_dtor_items.append(m)\n else:\n func_items.append(m)\n elif m[\"kind\"] == \"variable\":\n var_items.append(m)\n\n if typedef_items:\n lines += [\"## Member Typedef Documentation\", \"\"]\n for m in typedef_items:\n lines += _render_member_detail(m, f\"{qualified}::{m['name']}\")\n\n if enum_items_all:\n # Target of the Public Types synopsis links.\n import html as _html\n lines += [\"## Member Enumeration Documentation\", \"\"]\n for m in enum_items_all:\n lines.append(f\"({m['id']})=\") # legacy MyST anchor for old @ref\n enum_qualified = m.get(\"qualified\") or m[\"name\"]\n enum_id = _sphinx_cpp_v4_id(enum_qualified)\n enum_short = enum_qualified.rsplit(\"::\", 1)[-1]\n lines.append(\n f''\n f'enum {_html.escape(enum_short)}
'\n )\n if m[\"brief\"]:\n lines.append(f\"{_html.escape(_md_escape_cell(m['brief']))}
\")\n lines += _enumerator_list_table(\n m.get(\"enum_values\") or [], enum_qualified,\n bool(m.get(\"strong\")), with_anchors=True)\n\n # Dedupe by refid (a memberdef can span sectiondefs).\n def _dedupe(items: list[dict]) -> list[dict]:\n seen, out = set(), []\n for m in items:\n if m[\"id\"] in seen:\n continue\n seen.add(m[\"id\"])\n out.append(m)\n return out\n\n if ctor_dtor_items:\n lines += [\"## Constructor & Destructor Documentation\", \"\"]\n for m in _dedupe(ctor_dtor_items):\n lines += _render_member_detail(m, f\"{qualified}::{m['name']}\")\n\n if func_items:\n lines += [\"## Member Function Documentation\", \"\"]\n for m in _dedupe(func_items):\n # Enhance xphoto documentation with detailed descriptions\n m = _enhance_xphoto_member(m, qualified)\n lines += _render_member_detail(m, f\"{qualified}::{m['name']}\")\n\n if var_items:\n lines += [\"## Member Data Documentation\", \"\"]\n for m in _dedupe(var_items):\n lines += _render_member_detail(m, f\"{qualified}::{m['name']}\")\n\n _src_inc = (_header_data.get(\"include\") or \"\").strip() if _header_data else \"\"\n if _src_inc:\n import html as _html_pkg2\n _kind_word = \"struct\" if cls[\"kind\"] == \"struct\" else \"class\"\n _dir = _src_inc.rsplit(\"/\", 1)[0] + \"/\" if \"/\" in _src_inc else \"\"\n _base = _src_inc.rsplit(\"/\", 1)[-1]\n _fhref = _include_page_href(_src_inc)\n if _fhref:\n _flink = (f'{_html_pkg2.escape(_dir)}'\n f'{_html_pkg2.escape(_base)}')\n else:\n _flink = _html_pkg2.escape(_src_inc)\n lines += [\n \"\",\n \"{.opencv-class-files}\",\n \"## Source file\",\n \"\",\n f\"The documentation for this {_kind_word} was generated from the \"\n \"following file:\",\n \"\",\n f\"- {_flink}\",\n \"\",\n ]\n\n if inline:\n return lines\n _stub_write(out, \"\\n\".join(lines))\n\n\ndef _write_placeholder_stubs(out_dir: pathlib.Path,\n xml_dir: pathlib.Path) -> None:\n \"\"\"Stub pages for Doxygen's bare template-param classes (`_Tp`, `float_type`).\n Doxygen renders near-empty `class…` pages for these (title + collaboration\n diagram); mirror that so diagram cross-links resolve instead of 404ing.\n Marked `orphan` since nothing toctrees them.\"\"\"\n html_root = xml_dir.parent / \"html\"\n for _doxy_file, (_display, _page) in _PLACEHOLDER_STUBS.items():\n stem = _page[:-5] if _page.endswith(\".html\") else _page\n refid = _doxy_file[:-5] if _doxy_file.endswith(\".html\") else _doxy_file\n lines = [\"---\", \"orphan: true\", \"---\", \"\",\n f\"# {_display} Class Reference\", \"\"]\n _svg = _find_collaboration_svg(refid, html_root)\n if _svg is not None:\n lines += _diagram_svg_lines(\n _svg, out_dir,\n f\"Collaboration diagram for {_display}\",\n f\"Collaboration diagram for {_display}:\")\n lines += [\"\", \"The documentation for this class was generated from the \"\n \"following files:\", \"\"]\n _stub_write(out_dir / f\"{stem}.md\", \"\\n\".join(lines))\n _ANCHOR_TO_DOC[stem] = f\"{out_dir.name}/{stem}\"\n\n\n# Feature-complete content for optional modules whose Doxygen group XML is\n# absent from this build (disabled / hardware-gated — e.g. cannops needs the\n# Ascend SDK). When the XML is missing we render a full page from this data —\n# Topics, Classes, Functions and Function Documentation — mirroring the official\n# group pages. Links are either working `#include` file pages or in-page anchors\n# (no dependency on class/subgroup pages that don't exist here → no 404s).\n# Each module: title, include (umbrella, top of page), fn_include (shown in\n# Function Documentation), description (markdown), topics, classes\n# (kind, qualified, brief), functions (return, qualified, args, brief).\n_FALLBACK_MODULE_DATA: dict = {\n \"datasets\": {\n \"title\": \"Framework for working with different datasets\",\n \"include\": \"opencv2/datasets/dataset.hpp\",\n \"fn_include\": \"opencv2/datasets/util.hpp\",\n \"description\":\n \"The datasets module includes classes for working with different \"\n \"datasets: load data, evaluate different algorithms on them, \"\n \"contains benchmarks, etc.\\n\\n\"\n \"It is planned to have:\\n\\n\"\n \"- *basic*: loading code for all datasets to help start work with \"\n \"them.\\n\"\n \"- *next stage*: quick benchmarks for all datasets to show how to \"\n \"solve them using OpenCV and implement evaluation code.\\n\"\n \"- *finally*: implement on OpenCV state-of-the-art algorithms, \"\n \"which solve these tasks.\",\n \"topics\": [\"Action Recognition\", \"Face Recognition\",\n \"Gesture Recognition\", \"Human Pose Estimation\",\n \"Image Registration\", \"Image Segmentation\",\n \"Multiview Stereo Matching\", \"Object Recognition\",\n \"Pedestrian Detection\", \"SLAM\", \"Super Resolution\",\n \"Text Recognition\", \"Tracking\"],\n \"classes\": [\n (\"class\", \"cv::datasets::Dataset\", \"\"),\n (\"struct\", \"cv::datasets::Object\", \"\"),\n ],\n \"functions\": [\n (\"void\", \"cv::datasets::createDirectory\",\n \"(const std::string &path)\",\n \"Create a directory at the given path.\"),\n (\"void\", \"cv::datasets::getDirList\",\n \"(const std::string &dirName, \"\n \"std::vector< std::string > &fileNames)\",\n \"List the file names in a directory.\"),\n (\"void\", \"cv::datasets::split\",\n \"(const std::string &s, std::vector< std::string > &elems, \"\n \"char delim)\",\n \"Split a string into tokens on a delimiter.\"),\n ],\n },\n \"dnn_objdetect\": {\n \"title\": \"DNN used for object detection\",\n \"include\": \"opencv2/core_detect.hpp\",\n \"fn_include\": \"opencv2/core_detect.hpp\",\n \"description\":\n \"The dnn_objdetect module includes deep-neural-network utilities \"\n \"for object detection, grouping the structures and bounding-box \"\n \"handling required to run and post-process specialized object \"\n \"localization models on top of the OpenCV DNN backend.\",\n \"classes\": [\n (\"class\", \"cv::dnn_objdetect::InferBbox\",\n \"A class to post process model predictions.\"),\n (\"struct\", \"cv::dnn_objdetect::object\",\n \"Structure to hold the details pertaining to a single bounding \"\n \"box.\"),\n ],\n \"functions\": [],\n },\n \"quality\": {\n \"title\": \"Image Quality Analysis (IQA) API\",\n \"include\": \"opencv2/quality.hpp\",\n \"fn_include\": \"opencv2/quality/qualitybase.hpp\",\n \"description\":\n \"The quality module implements Image Quality Analysis (IQA) \"\n \"metrics. It provides algorithms to compute objective image-quality \"\n \"scores — full-reference metrics against a reference image, plus \"\n \"the no-reference BRISQUE metric — behind a common QualityBase \"\n \"interface.\",\n \"classes\": [\n (\"class\", \"cv::quality::QualityBase\", \"\"),\n (\"class\", \"cv::quality::QualityBRISQUE\",\n \"BRISQUE (Blind/Referenceless Image Spatial Quality Evaluator) is \"\n \"a No Reference Image Quality Assessment (NR-IQA) algorithm.\"),\n (\"class\", \"cv::quality::QualityGMSD\",\n \"Full reference GMSD algorithm\"),\n (\"class\", \"cv::quality::QualityMSE\",\n \"Full reference mean square error algorithm \"\n \"https://en.wikipedia.org/wiki/Mean_squared_error\"),\n (\"class\", \"cv::quality::QualityPSNR\",\n \"Full reference peak signal to noise ratio (PSNR) algorithm \"\n \"https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio\"),\n (\"class\", \"cv::quality::QualitySSIM\",\n \"Full reference structural similarity algorithm \"\n \"https://en.wikipedia.org/wiki/Structural_similarity\"),\n ],\n \"functions\": [],\n },\n \"reg\": {\n \"title\": \"Image Registration\",\n \"include\": \"opencv2/reg/map.hpp\",\n \"fn_include\": \"opencv2/reg/mapper.hpp\",\n \"description\": (\n \"The Registration module implements parametric image registration. \"\n \"The implemented method is direct alignment, that is, it uses \"\n \"directly the pixel values for calculating the registration between \"\n \"a pair of images, as opposed to feature-based registration.\\n\\n\"\n \"Feature based methods have some advantages over pixel based \"\n \"methods when we are trying to register pictures that have been \"\n \"shoot under different lighting conditions or exposition times, or \"\n \"when the images overlap only partially. On the other hand, the \"\n \"main advantage of pixel-based methods when compared to feature \"\n \"based methods is their better precision for some pictures (those \"\n \"shoot under similar lighting conditions and that have a \"\n \"significative overlap), due to the fact that we are using all the \"\n \"information available in the image, which allows us to achieve \"\n \"subpixel accuracy. This is particularly important for certain \"\n \"applications like multi-frame denoising or super-resolution.\\n\\n\"\n \"In fact, pixel and feature registration methods can complement \"\n \"each other: an application could first obtain a coarse \"\n \"registration using features and then refine the registration \"\n \"using a pixel based method on the overlapping area of the \"\n \"images.\\n\\n\"\n \"The module implements classes derived from the abstract classes \"\n \"[cv::reg::Map](classcv_1_1reg_1_1Map.md) or \"\n \"[cv::reg::Mapper](classcv_1_1reg_1_1Mapper.md). The former models \"\n \"a coordinate transformation between two reference frames, while \"\n \"the later encapsulates a way of invoking a method that calculates \"\n \"a Map between two images.\\n\\n\"\n \"Each class derived from Map implements a motion model, as \"\n \"follows:\\n\\n\"\n \"- [MapShift](classcv_1_1reg_1_1MapShift.md): Models a simple \"\n \"translation\\n\"\n \"- [MapAffine](classcv_1_1reg_1_1MapAffine.md): Models an affine \"\n \"transformation\\n\"\n \"- [MapProjec](classcv_1_1reg_1_1MapProjec.md): Models a projective \"\n \"transformation\\n\\n\"\n \"The classes derived from Mapper are:\\n\\n\"\n \"- [MapperGradShift](classcv_1_1reg_1_1MapperGradShift.md): \"\n \"Gradient based alignment for calculating translations.\\n\"\n \"- [MapperGradEuclid](classcv_1_1reg_1_1MapperGradEuclid.md): \"\n \"Gradient based alignment for euclidean motions (rotations and \"\n \"translations).\\n\"\n \"- [MapperGradSimilar](classcv_1_1reg_1_1MapperGradSimilar.md): \"\n \"Gradient based alignment for similarities (euclidean motion plus \"\n \"scaling).\\n\"\n \"- [MapperGradAffine](classcv_1_1reg_1_1MapperGradAffine.md): \"\n \"Gradient based alignment for an affine motion model.\\n\"\n \"- [MapperGradProj](classcv_1_1reg_1_1MapperGradProj.md): Gradient \"\n \"based alignment for calculating projective transformations.\\n\"\n \"- [MapperPyramid](classcv_1_1reg_1_1MapperPyramid.md): Implements \"\n \"hierarchical motion estimation using a Gaussian pyramid.\"),\n \"classes\": [\n (\"class\", \"cv::reg::Map\",\n \"Base class for modelling a Map between two images.\"),\n (\"class\", \"cv::reg::MapAffine\", \"\"),\n (\"class\", \"cv::reg::Mapper\",\n \"Base class for modelling an algorithm for calculating a map.\"),\n (\"class\", \"cv::reg::MapperGradAffine\", \"\"),\n (\"class\", \"cv::reg::MapperGradEuclid\", \"\"),\n (\"class\", \"cv::reg::MapperGradProj\", \"\"),\n (\"class\", \"cv::reg::MapperGradShift\", \"\"),\n (\"class\", \"cv::reg::MapperGradSimilar\", \"\"),\n (\"class\", \"cv::reg::MapperPyramid\", \"\"),\n (\"class\", \"cv::reg::MapProjec\", \"\"),\n (\"class\", \"cv::reg::MapShift\", \"\"),\n (\"class\", \"cv::reg::MapTypeCaster\", \"\"),\n ],\n \"functions\": [],\n },\n \"cannops\": {\n \"title\": \"Ascend-accelerated Computer Vision\",\n \"include\": \"opencv2/cann.hpp\",\n \"fn_include\": \"opencv2/cann_interface.hpp\",\n \"description\": (\n \"This module provides Ascend-accelerated implementations of core \"\n \"Computer-Vision operations, offloading element-wise arithmetic \"\n \"and image-processing primitives to Huawei Ascend NPU hardware for \"\n \"high-throughput acceleration.\"),\n \"topics\": [\"Core part\", \"Operations for Ascend Backend.\"],\n \"classes\": [],\n \"functions\": [],\n },\n}\n\n\ndef _fallback_fn_anchor(name: str, idx: int) -> str:\n \"\"\"Stable in-page anchor for a fallback function's detail block.\"\"\"\n return f\"api-fn-{name}-{idx}\"\n\n\ndef _fallback_topic_name(module: str, topic: str) -> str:\n \"\"\"Docname/anchor stem for a topic subpage (e.g. datasets_action_recognition).\"\"\"\n return f\"{module}_\" + re.sub(r\"[^a-z0-9]+\", \"_\", topic.lower()).strip(\"_\")\n\n\ndef _fallback_class_refid(kind: str, qualified: str) -> str:\n \"\"\"Doxygen-style page stem for a class/struct (e.g.\n `classcv_1_1datasets_1_1Dataset`) so the class link mirrors the convention.\"\"\"\n pfx = kind if kind in (\"class\", \"struct\", \"union\") else \"class\"\n return pfx + qualified.replace(\"::\", \"_1_1\")\n\n\ndef _render_fallback_body(name: str, d: dict) -> str:\n \"\"\"Full group-page body for a module with no Doxygen XML, in Doxygen's group\n order: Topics, Detailed Description, Classes, Functions, Function\n Documentation. Every link is a working `#include` file page, a generated\n topic/class subpage, or an in-page anchor — so nothing 404s.\"\"\"\n lines: list = []\n topics = d.get(\"topics\") or []\n classes = d.get(\"classes\") or []\n funcs = d.get(\"functions\") or []\n if topics:\n lines += [\"## Topics\", \"\"]\n lines += [f\"- [{t}](#api_{_fallback_topic_name(name, t)})\"\n for t in topics] + [\"\"]\n if d.get(\"description\"):\n lines += [\"## Detailed Description\", \"\", d[\"description\"], \"\"]\n if classes:\n lines += [\"## Classes\", \"\", \"{.api-reference-table}\",\n \"| Name | Description |\", \"|---|---|\"]\n for kind, qual, brief in classes:\n page = _fallback_class_refid(kind, qual)\n link = f\"[`{kind} {qual}`]({page}.md)\"\n # \"More…\" links to the class page's detail, as on the real pages —\n # only where there's a brief (matching Doxygen).\n desc = _md_escape_cell(brief)\n if brief:\n desc += f\" [More…]({page}.md#detailed-description)\"\n lines.append(f\"| {link} | {desc or chr(0xa0)} |\")\n lines += [\"\"]\n if funcs:\n lines += [\"## Functions\", \"\",\n \"{.api-reference-table .api-function-table}\",\n \"| Return | Name | Description |\", \"|---|---|---|\"]\n for i, (ret, qual, _args, brief) in enumerate(funcs):\n anc = _fallback_fn_anchor(name, i)\n lines.append(f\"| `{_md_escape_cell(ret)}` | \"\n f\"[`{qual}`](#{anc}) | {_md_escape_cell(brief)} |\")\n lines += [\"\"]\n if funcs:\n lines += [\"## Function Documentation\", \"\"]\n fn_inc = d.get(\"fn_include\") or d.get(\"include\")\n href = _include_page_href(fn_inc) if fn_inc else None\n for i, (ret, qual, args, brief) in enumerate(funcs):\n short = qual.rsplit(\"::\", 1)[-1]\n lines += [f\"({_fallback_fn_anchor(name, i)})=\",\n f\"### {short}()\", \"\",\n \"{.opencv-api-sig}\", f\"`{ret} {qual}{args}`\", \"\"]\n if href:\n lines += [\n \"{.opencv-api-include}\",\n f''\n f'#include <{fn_inc}>',\n \"\"]\n if brief:\n lines += [brief, \"\"]\n # Hidden toctree registers the topic + class subpages in the sidebar nav\n # (and avoids \"not in any toctree\" warnings); the lists above link to them.\n toc = [_fallback_topic_name(name, t) for t in topics]\n toc += [_fallback_class_refid(k, q) for k, q, _b in classes]\n if toc:\n lines += [\"```{toctree}\", \":hidden:\", \"\"] + toc + [\"```\", \"\"]\n return \"\\n\".join(lines)\n\n\ndef _fallback_module_tree(name: str):\n \"\"\"In-memory stand-in for a module group whose Doxygen XML is missing.\n Carries `body_md` (the full hand-rendered page body); `_write_api_stub`\n emits it verbatim so the page has Topics/Classes/Functions/Function\n Documentation with working links, and its `{#api_}` anchor resolves\n for any reference to the module. `topic_children` are the topic subpages\n `_write_api_stub` also writes. Other fields keep the node-schema shape so\n `module_rows`/`_flatten`/the index treat it like a real module.\n\n No top-of-page `#include` — like the real Doxygen group page, the include\n belongs in the Function Documentation (where it links to the file page).\"\"\"\n d = _FALLBACK_MODULE_DATA.get(name)\n if d is None:\n return None\n title = d[\"title\"]\n back = f\"Part of the [{title}](#api_{name}) module.\"\n child_pages: list = []\n # Topic subpages (linked from the Topics list).\n for t in (d.get(\"topics\") or []):\n cn = _fallback_topic_name(name, t)\n child_pages.append((cn, \"\\n\".join(\n [f\"# {t} {{#api_{cn}}}\", \"\", back, \"\"])))\n # Class/struct subpages (linked from the Classes table; the brief lives\n # under a Detailed Description heading so it reads like a class page).\n for kind, qual, brief in (d.get(\"classes\") or []):\n crefid = _fallback_class_refid(kind, qual)\n child_pages.append((crefid, \"\\n\".join(\n [f\"# {kind.capitalize()} {qual}\", \"\",\n (brief or \"\"), \"\",\n \"## Detailed Description\", \"\",\n (brief or f\"`{qual}` reference.\"), \"\", back, \"\"])))\n return {\n \"name\": name, # single-underscore group name -> page & anchor\n \"title\": title,\n \"detailed\": \"\",\n \"innerclasses\": [],\n \"sections\": {},\n \"children\": [],\n \"child_pages\": child_pages,\n \"body_md\": _render_fallback_body(name, d),\n }\n\n\ndef _apply_group_doc_override(tree: dict, xml_dir: pathlib.Path) -> None:\n \"\"\"Repair module groups whose subgroups were `@addtogroup`'d but never nested\n under a titled `@defgroup`, which Doxygen leaves as orphan top-level groups\n with an empty landing page. Injects the group description and attaches the\n real subgroups as children (recursively retitled). Driven by\n `_GROUP_DOC_OVERRIDES` / `_GROUP_TITLE_OVERRIDES`; no-op without an override.\"\"\"\n ov = _GROUP_DOC_OVERRIDES.get(tree[\"name\"])\n if not ov:\n return\n if ov.get(\"detailed\") and not tree[\"detailed\"]:\n tree[\"detailed\"] = ov[\"detailed\"]\n have = {c[\"name\"] for c in tree[\"children\"]}\n for sub in ov.get(\"subgroups\", ()):\n if sub in have:\n continue\n child = _build_api_hierarchy(\"group__\" + sub.replace(\"_\", \"__\"), xml_dir)\n if child is not None:\n tree[\"children\"].append(child)\n\n def _retitle(node: dict) -> None:\n node[\"title\"] = _GROUP_TITLE_OVERRIDES.get(node[\"name\"], node[\"title\"])\n for c in node.get(\"children\", ()):\n _retitle(c)\n _retitle(tree)\n\n\ndef _harvest_namespace_into_group(tree: dict, xml_dir: pathlib.Path) -> None:\n # Pull funcs/classes under the module's include prefix (per _GROUP_NS_HARVEST)\n # into the otherwise-empty group node, from the cv namespace and any group\n # they were filed under (e.g. depth.hpp uses @addtogroup rgbd).\n import xml.etree.ElementTree as _ET\n prefix = _GROUP_NS_HARVEST.get(tree[\"name\"])\n if not prefix:\n return\n tree.setdefault(\"sections\", {})\n have = {c[\"refid\"] for c in tree[\"innerclasses\"]}\n\n def _ingest(cd):\n for title, members in _parse_member_sections(cd).items():\n seen = {m[\"id\"] for m in tree[\"sections\"].get(title, [])}\n kept = [m for m in members\n if (m.get(\"include_file\") or \"\").startswith(prefix)\n and m[\"id\"] not in seen]\n if kept:\n tree[\"sections\"].setdefault(title, []).extend(kept)\n for ic in cd.findall(\"innerclass\"):\n rid = ic.get(\"refid\", \"\")\n if ic.get(\"prot\") != \"public\" or not rid or rid in have:\n continue\n cx = xml_dir / f\"{rid}.xml\"\n if not cx.is_file():\n continue\n try:\n ccd = _ET.parse(cx).getroot().find(\"compounddef\")\n except _ET.ParseError:\n continue\n loc = ccd.find(\"location\") if ccd is not None else None\n if loc is None or not (loc.get(\"file\") or \"\").startswith(prefix):\n continue\n qualified = \" \".join((ic.text or \"\").split())\n tree[\"innerclasses\"].append({\n \"refid\": rid, \"name\": qualified, \"qualified\": qualified,\n \"kind\": \"struct\" if rid.startswith(\"struct\") else \"class\",\n \"brief\": _read_class_brief(rid, xml_dir),\n })\n have.add(rid)\n\n srcs = [xml_dir / \"namespacecv.xml\"]\n srcs += [g for g in xml_dir.glob(\"group__*.xml\")\n if prefix in g.read_text(encoding=\"utf-8\", errors=\"ignore\")]\n for s in srcs:\n if not s.is_file():\n continue\n try:\n cd = _ET.parse(s).getroot().find(\"compounddef\")\n except _ET.ParseError:\n continue\n if cd is not None:\n _ingest(cd)\n\n\ndef _generate_api_stubs(modules, xml_dir, out_dir,\n root_anchor=\"api_root\", root_title=\"API Reference\",\n root_desc=None, extra_groups=()):\n \"\"\"Generate a stub tree (group/namespace/class pages) under out_dir.\n\n Docnames are prefixed with out_dir.name so the same generator drives both\n main_modules/ and extra_modules/ (contrib) trees from separate calls.\n extra_groups: orphan group stems rendered as pages but kept out of the\n module index (referenced groups not nested under any module top).\"\"\"\n if not modules and not extra_groups:\n return\n if not xml_dir.is_dir():\n return # No XML yet; degrade silently.\n\n global _CUR_MODULE_DIR\n _CUR_MODULE_DIR = out_dir.name\n _doc_prefix = out_dir.name\n\n # Where the member renderers find legacy graph SVGs / write their variants.\n global _DOXY_HTML_ROOT, _API_OUT_DIR\n _DOXY_HTML_ROOT = xml_dir.parent / \"html\"\n _API_OUT_DIR = out_dir\n\n # Freshness guard: skip rebuild only if the tree is newer than BOTH the XML\n # and the generator code. Without the code check, editing these modules\n # never invalidates the cache (the XML is unchanged), so `make sphinx`\n # silently keeps stale stubs and edits appear to have no effect.\n src_index = xml_dir / \"index.xml\"\n root_md = out_dir / \"api_root.markdown\"\n _code_mtime = max(\n (p.stat().st_mtime for p in pathlib.Path(__file__).parent.glob(\"*.py\")),\n default=0.0)\n if (src_index.is_file() and root_md.is_file()\n and root_md.stat().st_mtime >= src_index.stat().st_mtime\n and root_md.stat().st_mtime >= _code_mtime\n and any(p.name.startswith(\"namespace_\") and p.suffix == \".md\"\n for p in out_dir.iterdir())):\n for stub in out_dir.iterdir():\n n = stub.name\n if n.endswith(\".md\") and (n.startswith(\"class\") or n.startswith(\"struct\")):\n _ANCHOR_TO_DOC[n[:-3]] = f\"{_doc_prefix}/{n[:-3]}\"\n return\n\n import shutil\n if out_dir.exists():\n shutil.rmtree(out_dir)\n out_dir.mkdir(parents=True, exist_ok=True)\n global _stub_written, _MERGED_GROUPS, _MERGED_CLASS_TO_GROUP\n _stub_written = set()\n _MERGED_GROUPS = []\n _MERGED_CLASS_TO_GROUP = {}\n _desc = root_desc or (\n \"Sphinx-rendered API reference. Each entry below is a module's \"\n \"umbrella `@defgroup`; sub-pages mirror the Doxygen subgroup hierarchy.\")\n root_lines = [\n f\"{root_title} {{#{root_anchor}}}\",\n \"=\" * len(root_title),\n \"\",\n _desc,\n \"\",\n ]\n classes_seen: dict[str, dict] = {}\n global_group_info: dict[str, dict] = {}\n global_ns_group_map: dict[str, set] = {}\n trees: list = []\n module_rows: list = [] # (folder, page_stem, title) for the api_root list\n _gapi_tree = None # saved to write gapi.md wrapper after all stubs\n for m in list(modules) + list(extra_groups):\n is_extra = m in extra_groups\n if m in _GROUP_OVERRIDE_SUBGROUPS:\n # Re-parented under its module by _apply_group_doc_override; skip so\n # it isn't also emitted as a standalone orphan page.\n continue\n stem = _module_group_stem(m)\n tree = _build_api_hierarchy(\"group__\" + stem.replace(\"_\", \"__\"), xml_dir)\n if tree is None:\n # No Doxygen XML for this module — inject a placeholder tree for the\n # known optional modules so they still render & link; else skip.\n tree = _fallback_module_tree(m)\n if tree is None:\n continue\n _apply_group_doc_override(tree, xml_dir)\n _harvest_namespace_into_group(tree, xml_dir)\n trees.append(tree)\n if is_extra:\n pass\n elif m == \"gapi\":\n # gapi: expose as top-level \"Graph API\" wrapper page, not \"G-API framework\"\n _gapi_tree = tree\n module_rows.append((m, \"gapi\", \"Graph API\"))\n else:\n module_rows.append((m, tree[\"name\"], tree[\"title\"]))\n all_group_names = _collect_all_group_names(tree)\n all_refids = [\"group__\" + n.replace(\"_\", \"__\") for n in all_group_names]\n for ns_name, grps in _build_ns_group_map(all_refids, xml_dir).items():\n global_ns_group_map.setdefault(ns_name, set()).update(grps)\n def _flatten(node: dict, parent: str | None) -> None:\n global_group_info[node[\"name\"]] = {\"title\": node[\"title\"], \"parent\": parent}\n for child in node.get(\"children\", []):\n _flatten(child, node[\"name\"])\n _flatten(tree, None)\n # Pass 2 — write namespace stubs (once each) then group stubs.\n written_ns: set[str] = set()\n for tree in trees:\n all_group_names = _collect_all_group_names(tree)\n ns_map: dict[str, list] = {}\n for group_name in all_group_names:\n for ns in _namespaces_for_group(group_name, xml_dir, global_ns_group_map):\n anchor = f\"api_ns_{ns['name'].replace('::', '__')}\"\n if ns[\"name\"] not in written_ns:\n _write_namespace_stub(ns, out_dir, xml_dir,\n global_ns_group_map, global_group_info,\n classes_seen)\n written_ns.add(ns[\"name\"])\n _ALL_NAMESPACES[ns[\"name\"]] = {\n \"refid\": ns.get(\"refid\", \"\"),\n \"brief\": ns.get(\"brief\", \"\"),\n \"docname\": f\"{_doc_prefix}/namespace_\"\n f\"{ns['name'].replace('::', '__')}\",\n }\n ns_map.setdefault(group_name, []).append((ns[\"name\"], anchor))\n _write_api_stub(tree, out_dir, classes_seen, ns_map)\n # Expand to NESTED classes (a class's own inner types, e.g.\n # cv::ImageCollection::iterator) so each gets its own page like Doxygen —\n # the group-level collection skips names containing `::`.\n import xml.etree.ElementTree as _ET_nested\n _queue = list(classes_seen.keys())\n while _queue:\n _rid = _queue.pop()\n _cx = xml_dir / f\"{_rid}.xml\"\n if not _cx.is_file():\n continue\n try:\n _ccd = _ET_nested.parse(str(_cx)).getroot().find(\"compounddef\")\n except _ET_nested.ParseError:\n _ccd = None\n if _ccd is None:\n continue\n for _ic in _ccd.findall(\"innerclass\"):\n _icid = _ic.get(\"refid\", \"\")\n if not _icid or _icid in classes_seen:\n continue\n _icname = (_ic.text or \"\").strip()\n _ickind = (\"struct\" if _icid.startswith(\"struct\")\n else \"union\" if _icid.startswith(\"union\") else \"class\")\n classes_seen[_icid] = {\"refid\": _icid, \"name\": _icname,\n \"qualified\": _icname, \"kind\": _ickind}\n _queue.append(_icid)\n # Pre-seed every class's docname BEFORE writing, so cross-references made\n # while rendering one page (e.g. \"inherited from \" links) resolve even\n # when the base class is written later in this same pass.\n for _cls in classes_seen.values():\n _ANCHOR_TO_DOC.setdefault(\n _cls[\"refid\"], f\"{_doc_prefix}/{_class_page_name(_cls['refid'])}\")\n # Merged shell groups: a Classes box then each class inline. Done after\n # seeding above so bases resolve for \"inherited from\" links.\n for _mout, _mlines, _mclasses in _MERGED_GROUPS:\n _lines = list(_mlines)\n # Slug matching the per-class `## heading` its box entry links to.\n def _cls_slug(_c):\n _h = f\"{_c['kind'].title()} {_c.get('qualified') or _c['name']}\"\n return re.sub(r\"[^a-z0-9]+\", \"-\", _h.lower()).strip(\"-\")\n _lines += [\"## Classes\", \"\", \"{.api-reference-table}\",\n \"| Name | Description |\", \"|---|---|\"]\n for _c in _mclasses:\n # Encode \"::\" so the cv-linkifier doesn't nest an in our link.\n _nm = _c[\"name\"].replace(\"::\", \"::\")\n _lines.append(\n f'| {_c[\"kind\"]} '\n f'{_nm} '\n f\"| {_md_escape_cell(_c.get('brief', ''))} |\")\n _lines.append(\"\")\n for _c in _mclasses:\n _q = _c.get(\"qualified\") or _c[\"name\"]\n _lines += [f\"## {_c['kind'].title()} {_q}\", \"\"]\n _lines += _write_class_stub(_c, out_dir, xml_dir, inline=True) or []\n _stub_write(_mout, \"\\n\".join(_lines) + \"\\n\")\n # Per-class pages; seed `_ANCHOR_TO_DOC` refid→docname for `@ref`.\n for cls in classes_seen.values():\n _grp = _MERGED_CLASS_TO_GROUP.get(cls[\"refid\"])\n if _grp:\n # Inlined into its group page: turn this page into a redirect and\n # aim refid xrefs at the group instead.\n _rel = _grp.split(\"/\", 1)[-1]\n _stub_write(\n out_dir / f\"{_class_page_name(cls['refid'])}.md\",\n f\"# {cls.get('qualified') or cls['name']}\\n\\n\"\n f'\\n\\n'\n f'This page has moved to '\n f'{_rel}.
\\n')\n _ANCHOR_TO_DOC[cls[\"refid\"]] = _grp\n _ALL_CLASSES[cls[\"refid\"]] = {\n \"qualified\": cls.get(\"qualified\") or cls.get(\"name\", \"\"),\n \"kind\": cls.get(\"kind\", \"class\"),\n \"brief\": cls.get(\"brief\", \"\"),\n \"docname\": _grp,\n }\n continue\n _write_class_stub(cls, out_dir, xml_dir)\n _docname = f\"{_doc_prefix}/{_class_page_name(cls['refid'])}\"\n _ANCHOR_TO_DOC[cls[\"refid\"]] = _docname\n _ALL_CLASSES[cls[\"refid\"]] = {\n \"qualified\": cls.get(\"qualified\") or cls.get(\"name\", \"\"),\n \"kind\": cls.get(\"kind\", \"class\"),\n \"brief\": cls.get(\"brief\", \"\"),\n \"docname\": _docname,\n }\n # Placeholder stubs for bare template params (_Tp, …) so diagram links resolve.\n _write_placeholder_stubs(out_dir, xml_dir)\n\n # Write standalone \"Graph API\" page for gapi module (replaces gapi_ref as entry)\n if _gapi_tree is not None:\n content = _read_gapi_full_content()\n # Collect all gapi subgroup page names for the hidden toctree\n all_gapi_names = _collect_all_group_names(_gapi_tree)\n gapi_toctree = \"\\n\".join(all_gapi_names)\n gapi_lines = [\"# Graph API {#api_gapi}\", \"\"]\n if content:\n gapi_lines += [content, \"\"]\n gapi_lines += [\n \"```{toctree}\", \":hidden:\", \":maxdepth: 2\", \"\",\n gapi_toctree,\n \"```\", \"\",\n ]\n _stub_write(out_dir / \"gapi.md\", \"\\n\".join(gapi_lines) + \"\\n\")\n\n # File-reference pages (include dependency graphs) so #include links land on\n # a Sphinx diagram page.\n _write_file_ref_stubs(out_dir, xml_dir)\n # Hidden toctree drives nav/sidebar; the visible list shows \"folder. Title\".\n root_lines += [\"```{toctree}\", \":hidden:\", \":maxdepth: 1\", \"\"]\n root_lines += [stem for _m, stem, _t in module_rows]\n root_lines += [\"```\", \"\"]\n for _m, stem, title in module_rows:\n root_lines.append(f\"- {_m}. [{title}]({stem}.md)\")\n root_lines.append(\"\")\n _stub_write(out_dir / \"api_root.markdown\", \"\\n\".join(root_lines) + \"\\n\")\n # Sweep stale files.\n for _p in list(out_dir.iterdir()):\n if _p.is_file() and _p not in _stub_written:\n _p.unlink()\n # Flush per-sample example pages now to avoid orphans.\n _generate_example_pages(out_dir.parent / \"examples\")\n", "source": "opencv", "added": "2026-11-08", "created": "", "token_count": 30675, "license": "Apache-2.0", "author": "opencv contributors"}
{"id": "github:opencv:hal/carotene/include/carotene/types.hpp", "text": "/*\n * By downloading, copying, installing or using the software you agree to this license.\n * If you do not agree to this license, do not download, install,\n * copy or use the software.\n *\n *\n * License Agreement\n * For Open Source Computer Vision Library\n * (3-clause BSD License)\n *\n * Copyright (C) 2014-2015, NVIDIA Corporation, all rights reserved.\n * Third party copyrights are property of their respective owners.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n *\n * * Neither the names of the copyright holders nor the names of the contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * This software is provided by the copyright holders and contributors \"as is\" and\n * any express or implied warranties, including, but not limited to, the implied\n * warranties of merchantability and fitness for a particular purpose are disclaimed.\n * In no event shall copyright holders or contributors be liable for any direct,\n * indirect, incidental, special, exemplary, or consequential damages\n * (including, but not limited to, procurement of substitute goods or services;\n * loss of use, data, or profits; or business interruption) however caused\n * and on any theory of liability, whether in contract, strict liability,\n * or tort (including negligence or otherwise) arising in any way out of\n * the use of this software, even if advised of the possibility of such damage.\n */\n\n#ifndef CAROTENE_TYPES_HPP\n#define CAROTENE_TYPES_HPP\n\n#include \n#include \n#include \n\n#ifndef UINT32_MAX\n #define UINT32_MAX (4294967295U)\n#endif\n\nnamespace CAROTENE_NS {\n using std::size_t;\n using std::ptrdiff_t;\n\n typedef int8_t s8;\n typedef uint8_t u8;\n typedef int16_t s16;\n typedef uint16_t u16;\n typedef int32_t s32;\n typedef uint32_t u32;\n typedef float f32;\n typedef int64_t s64;\n typedef uint64_t u64;\n typedef double f64;\n\n typedef ptrdiff_t stride_t;\n\n enum CONVERT_POLICY\n {\n CONVERT_POLICY_WRAP,\n CONVERT_POLICY_SATURATE\n };\n\n enum BORDER_MODE\n {\n BORDER_MODE_UNDEFINED,\n BORDER_MODE_CONSTANT,\n BORDER_MODE_REPLICATE,\n BORDER_MODE_REFLECT,\n BORDER_MODE_REFLECT101,\n BORDER_MODE_WRAP\n };\n\n enum FLIP_MODE\n {\n FLIP_HORIZONTAL_MODE = 1,\n FLIP_VERTICAL_MODE = 2,\n FLIP_BOTH_MODE = FLIP_HORIZONTAL_MODE | FLIP_VERTICAL_MODE\n };\n\n enum COLOR_SPACE\n {\n COLOR_SPACE_BT601,\n COLOR_SPACE_BT709\n };\n\n struct Size2D {\n Size2D() : width(0), height(0) {}\n Size2D(size_t width_, size_t height_) : width(width_), height(height_) {}\n\n size_t width;\n size_t height;\n\n inline size_t total() const\n {\n return width * height;\n }\n };\n\n struct Margin {\n Margin() : left(0), right(0), top(0), bottom(0) {}\n Margin(size_t left_, size_t right_, size_t top_, size_t bottom_)\n : left(left_), right(right_), top(top_), bottom(bottom_) {}\n\n // these are measured in elements\n size_t left, right, top, bottom;\n };\n\n struct KeypointStore {\n virtual void push(f32 kpX, f32 kpY, f32 kpSize, f32 kpAngle=-1, f32 kpResponse=0, s32 kpOctave=0, s32 kpClass_id=-1) = 0;\n virtual ~KeypointStore() {}\n };\n}\n\n#endif\n", "source": "opencv", "added": "2026-11-08", "created": "", "token_count": 910, "license": "Apache-2.0", "author": "opencv contributors"}
{"id": "github:opencv:hal/carotene/src/in_range.cpp", "text": "/*\n * By downloading, copying, installing or using the software you agree to this license.\n * If you do not agree to this license, do not download, install,\n * copy or use the software.\n *\n *\n * License Agreement\n * For Open Source Computer Vision Library\n * (3-clause BSD License)\n *\n * Copyright (C) 2012-2015, NVIDIA Corporation, all rights reserved.\n * Third party copyrights are property of their respective owners.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n *\n * * Neither the names of the copyright holders nor the names of the contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * This software is provided by the copyright holders and contributors \"as is\" and\n * any express or implied warranties, including, but not limited to, the implied\n * warranties of merchantability and fitness for a particular purpose are disclaimed.\n * In no event shall copyright holders or contributors be liable for any direct,\n * indirect, incidental, special, exemplary, or consequential damages\n * (including, but not limited to, procurement of substitute goods or services;\n * loss of use, data, or profits; or business interruption) however caused\n * and on any theory of liability, whether in contract, strict liability,\n * or tort (including negligence or otherwise) arising in any way out of\n * the use of this software, even if advised of the possibility of such damage.\n */\n\n#include \"common.hpp\"\n\n#include \"vtransform.hpp\"\n\nnamespace CAROTENE_NS {\n\n#ifdef CAROTENE_NEON\n\nnamespace {\n\ninline void vnst(u8* dst, uint8x16_t v1, uint8x16_t v2) { vst1q_u8(dst, v1); vst1q_u8(dst+16, v2); }\ninline void vnst(u8* dst, uint16x8_t v1, uint16x8_t v2) { vst1q_u8(dst, vcombine_u8(vmovn_u16(v1), vmovn_u16(v2))); }\ninline void vnst(u8* dst, uint32x4_t v1, uint32x4_t v2) { vst1_u8(dst, vmovn_u16(vcombine_u16(vmovn_u32(v1), vmovn_u32(v2)))); }\n\ntemplate struct vtail\n{\n static inline void inRange(const T *, const T *, const T *,\n u8 *, size_t &, size_t)\n {\n //do nothing since there couldn't be enough data\n }\n};\ntemplate struct vtail\n{\n static inline void inRange(const T * src, const T * rng1, const T * rng2,\n u8 * dst, size_t &x, size_t width)\n {\n typedef typename internal::VecTraits::vec128 vec128;\n typedef typename internal::VecTraits::unsign::vec128 uvec128;\n //There no more than 15 elements in the tail, so we could handle 8 element vector only once\n if( x + 8 < width)\n {\n vec128 vs = internal::vld1q( src + x);\n vec128 vr1 = internal::vld1q(rng1 + x);\n vec128 vr2 = internal::vld1q(rng2 + x);\n uvec128 vd = internal::vandq(internal::vcgeq(vs, vr1), internal::vcgeq(vr2, vs));\n internal::vst1(dst + x, internal::vmovn(vd));\n x+=8;\n }\n }\n};\ntemplate struct vtail\n{\n static inline void inRange(const T * src, const T * rng1, const T * rng2,\n u8 * dst, size_t &x, size_t width)\n {\n typedef typename internal::VecTraits::vec128 vec128;\n typedef typename internal::VecTraits::unsign::vec128 uvec128;\n typedef typename internal::VecTraits::vec64 vec64;\n typedef typename internal::VecTraits::unsign::vec64 uvec64;\n //There no more than 31 elements in the tail, so we could handle once 16+8 or 16 or 8 elements\n if( x + 16 < width)\n {\n vec128 vs = internal::vld1q( src + x);\n vec128 vr1 = internal::vld1q(rng1 + x);\n vec128 vr2 = internal::vld1q(rng2 + x);\n uvec128 vd = internal::vandq(internal::vcgeq(vs, vr1), internal::vcgeq(vr2, vs));\n internal::vst1q(dst + x, vd);\n x+=16;\n }\n if( x + 8 < width)\n {\n vec64 vs = internal::vld1( src + x);\n vec64 vr1 = internal::vld1(rng1 + x);\n vec64 vr2 = internal::vld1(rng2 + x);\n uvec64 vd = internal::vand(internal::vcge(vs, vr1), internal::vcge(vr2, vs));\n internal::vst1(dst + x, vd);\n x+=8;\n }\n }\n};\n\ntemplate \ninline void inRangeCheck(const Size2D &_size,\n const T * srcBase, ptrdiff_t srcStride,\n const T * rng1Base, ptrdiff_t rng1Stride,\n const T * rng2Base, ptrdiff_t rng2Stride,\n u8 * dstBase, ptrdiff_t dstStride)\n{\n typedef typename internal::VecTraits::vec128 vec128;\n typedef typename internal::VecTraits::unsign::vec128 uvec128;\n\n Size2D size(_size);\n if (srcStride == dstStride &&\n srcStride == rng1Stride &&\n srcStride == rng2Stride &&\n srcStride == (ptrdiff_t)(size.width))\n {\n size.width *= size.height;\n size.height = 1;\n }\n const size_t width = size.width & ~( 32/sizeof(T) - 1 );\n\n for(size_t j = 0; j < size.height; ++j)\n {\n const T * src = internal::getRowPtr( srcBase, srcStride, j);\n const T * rng1 = internal::getRowPtr(rng1Base, rng1Stride, j);\n const T * rng2 = internal::getRowPtr(rng2Base, rng2Stride, j);\n u8 * dst = internal::getRowPtr( dstBase, dstStride, j);\n size_t i = 0;\n for( ; i < width; i += 32/sizeof(T) )\n {\n internal::prefetch(src + i);\n internal::prefetch(rng1 + i);\n internal::prefetch(rng2 + i);\n\n vec128 vs = internal::vld1q( src + i);\n vec128 vr1 = internal::vld1q(rng1 + i);\n vec128 vr2 = internal::vld1q(rng2 + i);\n uvec128 vd1 = internal::vandq(internal::vcgeq(vs, vr1), internal::vcgeq(vr2, vs));\n vs = internal::vld1q( src + i + 16/sizeof(T));\n vr1 = internal::vld1q(rng1 + i + 16/sizeof(T));\n vr2 = internal::vld1q(rng2 + i + 16/sizeof(T));\n uvec128 vd2 = internal::vandq(internal::vcgeq(vs, vr1), internal::vcgeq(vr2, vs));\n vnst(dst + i, vd1, vd2);\n }\n vtail::inRange(src, rng1, rng2, dst, i, size.width);\n for( ; i < size.width; i++ )\n dst[i] = (u8)(-(rng1[i] <= src[i] && src[i] <= rng2[i]));\n }\n}\n\n}\n\n#define INRANGEFUNC(T) \\\nvoid inRange(const Size2D &_size, \\\n const T * srcBase, ptrdiff_t srcStride, \\\n const T * rng1Base, ptrdiff_t rng1Stride, \\\n const T * rng2Base, ptrdiff_t rng2Stride, \\\n u8 * dstBase, ptrdiff_t dstStride) \\\n{ \\\n internal::assertSupportedConfiguration(); \\\n inRangeCheck(_size, srcBase, srcStride, \\\n rng1Base, rng1Stride, rng2Base, rng2Stride, \\\n dstBase, dstStride); \\\n}\n#else\n#define INRANGEFUNC(T) \\\nvoid inRange(const Size2D &, \\\n const T *, ptrdiff_t, \\\n const T *, ptrdiff_t, \\\n const T *, ptrdiff_t, \\\n u8 *, ptrdiff_t) \\\n{ \\\n internal::assertSupportedConfiguration(); \\\n}\n#endif\n\nINRANGEFUNC(u8)\nINRANGEFUNC(s8)\nINRANGEFUNC(u16)\nINRANGEFUNC(s16)\nINRANGEFUNC(s32)\nINRANGEFUNC(f32)\n\n} // namespace CAROTENE_NS\n", "source": "opencv", "added": "2026-11-08", "created": "", "token_count": 2125, "license": "Apache-2.0", "author": "opencv contributors"}
{"id": "github:opencv:hal/ipp/CMakeLists.txt", "text": "project(ipphal)\n\nset(IPP_HAL_VERSION 0.0.1 CACHE INTERNAL \"\")\nset(IPP_HAL_LIBRARIES \"ipphal\" CACHE INTERNAL \"\")\nset(IPP_HAL_INCLUDE_DIRS \"${CMAKE_CURRENT_SOURCE_DIR}/include\" CACHE INTERNAL \"\")\nset(IPP_HAL_HEADERS\n \"${CMAKE_CURRENT_SOURCE_DIR}/include/ipp_hal_core.hpp\"\n \"${CMAKE_CURRENT_SOURCE_DIR}/include/ipp_hal_imgproc.hpp\"\n CACHE INTERNAL \"\")\n\nadd_library(ipphal STATIC\n \"${CMAKE_CURRENT_SOURCE_DIR}/src/math_ipp.cpp\"\n \"${CMAKE_CURRENT_SOURCE_DIR}/src/mean_ipp.cpp\"\n \"${CMAKE_CURRENT_SOURCE_DIR}/src/minmax_ipp.cpp\"\n \"${CMAKE_CURRENT_SOURCE_DIR}/src/norm_ipp.cpp\"\n \"${CMAKE_CURRENT_SOURCE_DIR}/src/cart_polar_ipp.cpp\"\n \"${CMAKE_CURRENT_SOURCE_DIR}/src/color_ipp.cpp\"\n \"${CMAKE_CURRENT_SOURCE_DIR}/src/transforms_ipp.cpp\"\n \"${CMAKE_CURRENT_SOURCE_DIR}/src/warp_ipp.cpp\"\n \"${CMAKE_CURRENT_SOURCE_DIR}/src/deriv_ipp.cpp\"\n \"${CMAKE_CURRENT_SOURCE_DIR}/src/resize_ipp.cpp\"\n \"${CMAKE_CURRENT_SOURCE_DIR}/src/box_filter_ipp.cpp\"\n \"${CMAKE_CURRENT_SOURCE_DIR}/src/sum_ipp.cpp\"\n \"${CMAKE_CURRENT_SOURCE_DIR}/src/color_ipp.cpp\"\n \"${CMAKE_CURRENT_SOURCE_DIR}/src/filter_ipp.cpp\"\n \"${CMAKE_CURRENT_SOURCE_DIR}/src/matchtemplate_ipp.cpp\"\n \"${CMAKE_CURRENT_SOURCE_DIR}/src/canny_ipp.cpp\"\n \"${CMAKE_CURRENT_SOURCE_DIR}/src/threshold_ipp.cpp\"\n \"${CMAKE_CURRENT_SOURCE_DIR}/src/distancetransform_ipp.cpp\"\n \"${CMAKE_CURRENT_SOURCE_DIR}/src/bilateral_filter_ipp.cpp\"\n \"${CMAKE_CURRENT_SOURCE_DIR}/src/samplers_ipp.cpp\"\n)\n\n#TODO: HAVE_IPP_ICV and HAVE_IPP_IW added as private macro till OpenCV itself is\n# source of IPP and public definitions lead to redefinition warning\n# The macro should be redefined as PUBLIC when IPP part is removed from core\n# to make HAL the source of IPP integration. The same is true for WITH_IPP_CALLS_ENFORCED\nif(HAVE_IPP_ICV)\n target_compile_definitions(ipphal PRIVATE HAVE_IPP_ICV)\nendif()\n\nif(HAVE_IPP_IW)\n target_compile_definitions(ipphal PRIVATE HAVE_IPP_IW)\nendif()\n\nif(WITH_IPP_CALLS_ENFORCED)\n target_compile_definitions(ipphal PRIVATE IPP_CALLS_ENFORCED)\n message(\"WITH_IPP_CALLS_ENFORCED=${WITH_IPP_CALLS_ENFORCED}: enforced IPP calls are enabled in IPP HAL\")\nendif()\n\ntarget_include_directories(ipphal PRIVATE \"${CMAKE_CURRENT_SOURCE_DIR}/include\")\nocv_warnings_disable(CMAKE_CXX_FLAGS -Wno-suggest-override)\n\ntarget_include_directories(ipphal PRIVATE\n \"${CMAKE_CURRENT_SOURCE_DIR}/src\"\n ${CMAKE_SOURCE_DIR}/modules/core/include\n ${CMAKE_SOURCE_DIR}/modules/imgproc/include\n ${CMAKE_SOURCE_DIR}/modules/geometry/include\n ${IPP_INCLUDE_DIRS}\n)\n\ntarget_link_libraries(ipphal PUBLIC ${IPP_IW_LIBRARIES} ${IPP_LIBRARIES})\n\nset_target_properties(ipphal PROPERTIES ARCHIVE_OUTPUT_DIRECTORY ${3P_LIBRARY_OUTPUT_PATH} DEBUG_POSTFIX \"${OPENCV_DEBUG_POSTFIX}\")\n\nif(NOT BUILD_SHARED_LIBS)\n ocv_install_target(ipphal EXPORT OpenCVModules ARCHIVE DESTINATION ${OPENCV_3P_LIB_INSTALL_PATH} COMPONENT dev)\nendif()\n\nif(ENABLE_SOLUTION_FOLDERS)\n set_target_properties(ipphal PROPERTIES FOLDER \"3rdparty\")\nendif()\n", "source": "opencv", "added": "2026-11-08", "created": "", "token_count": 802, "license": "Apache-2.0", "author": "opencv contributors"}
{"id": "github:opencv:hal/ipp/include/ipp_hal_core.hpp", "text": "// This file is part of OpenCV project.\n// It is subject to the license terms in the LICENSE file found in the top-level directory\n// of this distribution and at http://opencv.org/license.html\n\n#ifndef __IPP_HAL_CORE_HPP__\n#define __IPP_HAL_CORE_HPP__\n\n#include \n#include \"ipp_utils.hpp\"\n\n#if (IPP_VERSION_X100 >= 700)\nint ipp_hal_meanStdDev(const uchar* src_data, size_t src_step, int width, int height, int src_type,\n double* mean_val, double* stddev_val, uchar* mask, size_t mask_step);\n\n// IPP version is less efficient than implementation with universtal intrinsics\n// See https://github.com/opencv/opencv/pull/29339\n//#undef cv_hal_meanStdDev\n//#define cv_hal_meanStdDev ipp_hal_meanStdDev\n\nint ipp_hal_minMaxIdxMaskStep(const uchar* src_data, size_t src_step, int width, int height, int depth,\n double* _minVal, double* _maxVal, int* _minIdx, int* _maxIdx, uchar* mask, size_t mask_step);\n\n#undef cv_hal_minMaxIdxMaskStep\n#define cv_hal_minMaxIdxMaskStep ipp_hal_minMaxIdxMaskStep\n\n#if (IPP_VERSION_X100 == 202200)\n# define IPP_DISABLE_NORM_8U 1 // accuracy difference in perf test sanity check\n# else\n# define IPP_DISABLE_NORM_8U 0\n#endif\n\n#if (IPP_VERSION_X100 >= 202200 && IPP_VERSION_X100 < 202220)\n# define IPP_DISABLE_NORM_INF_16U_C1MR 1 // segmentation fault in accuracy test\n# else\n# define IPP_DISABLE_NORM_INF_16U_C1MR 0\n#endif\n\nint ipp_hal_norm(const uchar* src, size_t src_step, const uchar* mask, size_t mask_step,\n int width, int height, int type, int norm_type, double* result);\n\n#undef cv_hal_norm\n#define cv_hal_norm ipp_hal_norm\n\nint ipp_hal_normDiff(const uchar* src1, size_t src1_step, const uchar* src2, size_t src2_step, const uchar* mask,\n size_t mask_step, int width, int height, int type, int norm_type, double* result);\n\n#undef cv_hal_normDiff\n#define cv_hal_normDiff ipp_hal_normDiff\n\nint ipp_hal_sum(const uchar *src_data, size_t src_step, int src_type, int width, int height, double *result);\n\n#undef cv_hal_sum\n#define cv_hal_sum ipp_hal_sum\n\n#endif\n\nint ipp_hal_polarToCart32f(const float* mag, const float* angle, float* x, float* y, int len, bool angleInDegrees);\nint ipp_hal_polarToCart64f(const double* mag, const double* angle, double* x, double* y, int len, bool angleInDegrees);\n\n#undef cv_hal_polarToCart32f\n#define cv_hal_polarToCart32f ipp_hal_polarToCart32f\n#undef cv_hal_polarToCart64f\n#define cv_hal_polarToCart64f ipp_hal_polarToCart64f\n\n#ifdef HAVE_IPP_IW\nint ipp_hal_flip(int src_type, const uchar* src_data, size_t src_step, int src_width, int src_height,\n uchar* dst_data, size_t dst_step, int flip_mode);\n\n#undef cv_hal_flip\n#define cv_hal_flip ipp_hal_flip\n#endif\n\nint ipp_hal_transpose2d(const uchar* src_data, size_t src_step, uchar* dst_data, size_t dst_step, int src_width,\n int src_height, int element_size);\n\n#undef cv_hal_transpose2d\n#define cv_hal_transpose2d ipp_hal_transpose2d\n\nint ipp_hal_invSqrt32f(const float* src, float* dst, int len);\nint ipp_hal_invSqrt64f(const double* src, double* dst, int len);\n\n#undef cv_hal_invSqrt32f\n#define cv_hal_invSqrt32f ipp_hal_invSqrt32f\n\n#undef cv_hal_invSqrt64f\n#define cv_hal_invSqrt64f ipp_hal_invSqrt64f\n\nint ipp_hal_exp32f(const float* src, float* dst, int len);\nint ipp_hal_exp64f(const double* src, double* dst, int len);\n\n#undef cv_hal_exp32f\n#define cv_hal_exp32f ipp_hal_exp32f\n\n#undef cv_hal_exp64f\n#define cv_hal_exp64f ipp_hal_exp64f\n\nint ipp_hal_log32f(const float* src, float* dst, int len);\nint ipp_hal_log64f(const double* src, double* dst, int len);\n\n#undef cv_hal_log32f\n#define cv_hal_log32f ipp_hal_log32f\n\n#undef cv_hal_log64f\n#define cv_hal_log64f ipp_hal_log64f\n\n//! @endcond\n\n#endif\n", "source": "opencv", "added": "2026-11-08", "created": "", "token_count": 1081, "license": "Apache-2.0", "author": "opencv contributors"}
{"id": "github:opencv:hal/ipp/src/cart_polar_ipp.cpp", "text": "// This file is part of OpenCV project.\n// It is subject to the license terms in the LICENSE file found in the top-level directory\n// of this distribution and at http://opencv.org/license.html\n\n#include \"ipp_hal_core.hpp\"\n\n#include \n#include \n\nint ipp_hal_polarToCart32f(const float* mag, const float* angle, float* x, float* y, int len, bool angleInDegrees)\n{\n CV_HAL_CHECK_USE_IPP();\n const bool isInPlace = (x == mag) || (x == angle) || (y == mag) || (y == angle);\n if (isInPlace || angleInDegrees)\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n\n if (CV_INSTRUMENT_FUN_IPP(ippsPolarToCart_32f, mag, angle, x, y, len) < 0)\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n\n return CV_HAL_ERROR_OK;\n}\n\nint ipp_hal_polarToCart64f(const double* mag, const double* angle, double* x, double* y, int len, bool angleInDegrees)\n{\n CV_HAL_CHECK_USE_IPP();\n const bool isInPlace = (x == mag) || (x == angle) || (y == mag) || (y == angle);\n if (isInPlace || angleInDegrees)\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n\n if (CV_INSTRUMENT_FUN_IPP(ippsPolarToCart_64f, mag, angle, x, y, len) < 0)\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n\n return CV_HAL_ERROR_OK;\n}\n", "source": "opencv", "added": "2026-11-08", "created": "", "token_count": 355, "license": "Apache-2.0", "author": "opencv contributors"}
{"id": "github:opencv:hal/ipp/src/color_ipp.cpp", "text": "// This file is part of OpenCV project.\n// It is subject to the license terms in the LICENSE file found in the top-level directory\n// of this distribution and at http://opencv.org/license.html\n\n#include \"ipp_hal_imgproc.hpp\"\n#include \n#include \"precomp_ipp.hpp\"\n\n#include \n\n#if IPP_VERSION_X100 >= 700\n\n#define MAX_IPP8u 255\n#define MAX_IPP16u 65535\n#define MAX_IPP32f 1.0\n\n#define IPP_DISABLE_CVTCOLOR_GRAY2BGR_8UC3 1\n\nnamespace {\n\ntypedef IppStatus (CV_STDCALL* ippiGeneralFunc)(const void *, int, void *, int, IppiSize);\ntypedef IppStatus (CV_STDCALL* ippiColor2GrayFunc)(const void *, int, void *, int, IppiSize, const Ipp32f *);\ntypedef IppStatus (CV_STDCALL* ippiReorderFunc)(const void *, int, void *, int, IppiSize, const int *);\n\n// BT.601 BGR->Y weights\nstatic const float B2YF = 0.114f;\nstatic const float G2YF = 0.587f;\nstatic const float R2YF = 0.299f;\n\ntemplate struct ColorChannel\n{\n static inline _Tp max() { return std::numeric_limits<_Tp>::max(); }\n};\ntemplate<> struct ColorChannel\n{\n static inline float max() { return 1.f; }\n};\n\ntemplate \nclass CvtColorIPPLoop_Invoker : public cv::ParallelLoopBody\n{\npublic:\n CvtColorIPPLoop_Invoker(const uchar * src_data_, size_t src_step_, uchar * dst_data_, size_t dst_step_,\n int width_, const Cvt& _cvt, bool *_ok) :\n ParallelLoopBody(), src_data(src_data_), src_step(src_step_), dst_data(dst_data_), dst_step(dst_step_),\n width(width_), cvt(_cvt), ok(_ok)\n {\n *ok = true;\n }\n\n virtual void operator()(const cv::Range& range) const CV_OVERRIDE\n {\n const void *yS = src_data + src_step * range.start;\n void *yD = dst_data + dst_step * range.start;\n if( !cvt(yS, static_cast(src_step), yD, static_cast(dst_step), width, range.end - range.start) )\n *ok = false;\n else\n {\n CV_IMPL_ADD(CV_IMPL_IPP|CV_IMPL_MT);\n }\n }\n\nprivate:\n const uchar * src_data;\n const size_t src_step;\n uchar * dst_data;\n const size_t dst_step;\n const int width;\n const Cvt& cvt;\n bool *ok;\n\n const CvtColorIPPLoop_Invoker& operator= (const CvtColorIPPLoop_Invoker&);\n};\n\ntemplate \nbool CvtColorIPPLoop(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step,\n int width, int height, const Cvt& cvt)\n{\n bool ok;\n cv::parallel_for_(cv::Range(0, height),\n CvtColorIPPLoop_Invoker(src_data, src_step, dst_data, dst_step, width, cvt, &ok),\n (width * height)/(double)(1<<16) );\n return ok;\n}\n\ntemplate \nbool CvtColorIPPLoopCopy(const uchar * src_data, size_t src_step, int src_type, uchar * dst_data, size_t dst_step,\n int width, int height, const Cvt& cvt)\n{\n cv::Mat temp;\n cv::Mat src(cv::Size(width, height), src_type, const_cast(src_data), src_step);\n cv::Mat source = src;\n if( src_data == dst_data )\n {\n src.copyTo(temp);\n source = temp;\n }\n bool ok;\n cv::parallel_for_(cv::Range(0, source.rows),\n CvtColorIPPLoop_Invoker(source.data, source.step, dst_data, dst_step,\n source.cols, cvt, &ok),\n source.total()/(double)(1<<16) );\n return ok;\n}\n\nstruct IPPGeneralFunctor\n{\n IPPGeneralFunctor(ippiGeneralFunc _func) : ippiColorConvertGeneral(_func){}\n bool operator()(const void *src, int srcStep, void *dst, int dstStep, int cols, int rows) const\n {\n return ippiColorConvertGeneral ? CV_INSTRUMENT_FUN_IPP(ippiColorConvertGeneral, src, srcStep, dst, dstStep, ippiSize(cols, rows)) >= 0 : false;\n }\nprivate:\n ippiGeneralFunc ippiColorConvertGeneral;\n};\n\nstruct IPPReorderFunctor\n{\n IPPReorderFunctor(ippiReorderFunc _func, int _order0, int _order1, int _order2) : ippiColorConvertReorder(_func)\n {\n order[0] = _order0;\n order[1] = _order1;\n order[2] = _order2;\n order[3] = 3;\n }\n bool operator()(const void *src, int srcStep, void *dst, int dstStep, int cols, int rows) const\n {\n return ippiColorConvertReorder ? CV_INSTRUMENT_FUN_IPP(ippiColorConvertReorder, src, srcStep, dst, dstStep, ippiSize(cols, rows), order) >= 0 : false;\n }\nprivate:\n ippiReorderFunc ippiColorConvertReorder;\n int order[4];\n};\n\nstruct IPPReorderGeneralFunctor\n{\n IPPReorderGeneralFunctor(ippiReorderFunc _func1, ippiGeneralFunc _func2, int _order0, int _order1, int _order2, int _depth) :\n ippiColorConvertReorder(_func1), ippiColorConvertGeneral(_func2), depth(_depth)\n {\n order[0] = _order0;\n order[1] = _order1;\n order[2] = _order2;\n order[3] = 3;\n }\n bool operator()(const void *src, int srcStep, void *dst, int dstStep, int cols, int rows) const\n {\n if (ippiColorConvertReorder == 0 || ippiColorConvertGeneral == 0)\n return false;\n\n cv::Mat temp;\n temp.create(rows, cols, CV_MAKETYPE(depth, 3));\n if(CV_INSTRUMENT_FUN_IPP(ippiColorConvertReorder, src, srcStep, temp.ptr(), (int)temp.step[0], ippiSize(cols, rows), order) < 0)\n return false;\n return CV_INSTRUMENT_FUN_IPP(ippiColorConvertGeneral, temp.ptr(), (int)temp.step[0], dst, dstStep, ippiSize(cols, rows)) >= 0;\n }\nprivate:\n ippiReorderFunc ippiColorConvertReorder;\n ippiGeneralFunc ippiColorConvertGeneral;\n int order[4];\n int depth;\n};\n\nstruct IPPGeneralReorderFunctor\n{\n IPPGeneralReorderFunctor(ippiGeneralFunc _func1, ippiReorderFunc _func2, int _order0, int _order1, int _order2, int _depth) :\n ippiColorConvertGeneral(_func1), ippiColorConvertReorder(_func2), depth(_depth)\n {\n order[0] = _order0;\n order[1] = _order1;\n order[2] = _order2;\n order[3] = 3;\n }\n bool operator()(const void *src, int srcStep, void *dst, int dstStep, int cols, int rows) const\n {\n if (ippiColorConvertGeneral == 0 || ippiColorConvertReorder == 0)\n return false;\n\n cv::Mat temp;\n temp.create(rows, cols, CV_MAKETYPE(depth, 3));\n if(CV_INSTRUMENT_FUN_IPP(ippiColorConvertGeneral, src, srcStep, temp.ptr(), (int)temp.step[0], ippiSize(cols, rows)) < 0)\n return false;\n return CV_INSTRUMENT_FUN_IPP(ippiColorConvertReorder, temp.ptr(), (int)temp.step[0], dst, dstStep, ippiSize(cols, rows), order) >= 0;\n }\nprivate:\n ippiGeneralFunc ippiColorConvertGeneral;\n ippiReorderFunc ippiColorConvertReorder;\n int order[4];\n int depth;\n};\n\nstruct IPPColor2GrayFunctor\n{\n IPPColor2GrayFunctor(ippiColor2GrayFunc _func) : ippiColorToGray(_func)\n {\n coeffs[0] = B2YF;\n coeffs[1] = G2YF;\n coeffs[2] = R2YF;\n }\n bool operator()(const void *src, int srcStep, void *dst, int dstStep, int cols, int rows) const\n {\n return ippiColorToGray ? CV_INSTRUMENT_FUN_IPP(ippiColorToGray, src, srcStep, dst, dstStep, ippiSize(cols, rows), coeffs) >= 0 : false;\n }\nprivate:\n ippiColor2GrayFunc ippiColorToGray;\n Ipp32f coeffs[3];\n};\n\n#if !IPP_DISABLE_CVTCOLOR_GRAY2BGR_8UC3\nstatic IppStatus ippiGrayToRGB_C1C3R(const Ipp8u* pSrc, int srcStep, Ipp8u* pDst, int dstStep, IppiSize roiSize)\n{\n return CV_INSTRUMENT_FUN_IPP(ippiGrayToRGB_8u_C1C3R, pSrc, srcStep, pDst, dstStep, roiSize);\n}\n#endif\nstatic IppStatus ippiGrayToRGB_C1C3R(const Ipp16u* pSrc, int srcStep, Ipp16u* pDst, int dstStep, IppiSize roiSize)\n{\n return CV_INSTRUMENT_FUN_IPP(ippiGrayToRGB_16u_C1C3R, pSrc, srcStep, pDst, dstStep, roiSize);\n}\nstatic IppStatus ippiGrayToRGB_C1C3R(const Ipp32f* pSrc, int srcStep, Ipp32f* pDst, int dstStep, IppiSize roiSize)\n{\n return CV_INSTRUMENT_FUN_IPP(ippiGrayToRGB_32f_C1C3R, pSrc, srcStep, pDst, dstStep, roiSize);\n}\n\nstatic IppStatus ippiGrayToRGB_C1C4R(const Ipp8u* pSrc, int srcStep, Ipp8u* pDst, int dstStep, IppiSize roiSize, Ipp8u aval)\n{\n return CV_INSTRUMENT_FUN_IPP(ippiGrayToRGB_8u_C1C4R, pSrc, srcStep, pDst, dstStep, roiSize, aval);\n}\nstatic IppStatus ippiGrayToRGB_C1C4R(const Ipp16u* pSrc, int srcStep, Ipp16u* pDst, int dstStep, IppiSize roiSize, Ipp16u aval)\n{\n return CV_INSTRUMENT_FUN_IPP(ippiGrayToRGB_16u_C1C4R, pSrc, srcStep, pDst, dstStep, roiSize, aval);\n}\nstatic IppStatus ippiGrayToRGB_C1C4R(const Ipp32f* pSrc, int srcStep, Ipp32f* pDst, int dstStep, IppiSize roiSize, Ipp32f aval)\n{\n return CV_INSTRUMENT_FUN_IPP(ippiGrayToRGB_32f_C1C4R, pSrc, srcStep, pDst, dstStep, roiSize, aval);\n}\n\ntemplate \nstruct IPPGray2BGRFunctor\n{\n IPPGray2BGRFunctor(){}\n bool operator()(const void *src, int srcStep, void *dst, int dstStep, int cols, int rows) const\n {\n return ippiGrayToRGB_C1C3R((T*)src, srcStep, (T*)dst, dstStep, ippiSize(cols, rows)) >= 0;\n }\n};\n\ntemplate \nstruct IPPGray2BGRAFunctor\n{\n IPPGray2BGRAFunctor()\n {\n alpha = ColorChannel::max();\n }\n bool operator()(const void *src, int srcStep, void *dst, int dstStep, int cols, int rows) const\n {\n return ippiGrayToRGB_C1C4R((T*)src, srcStep, (T*)dst, dstStep, ippiSize(cols, rows), alpha) >= 0;\n }\n T alpha;\n};\n\nstatic IppStatus CV_STDCALL ippiSwapChannels_8u_C3C4Rf(const Ipp8u* pSrc, int srcStep, Ipp8u* pDst, int dstStep,\n IppiSize roiSize, const int *dstOrder)\n{\n return CV_INSTRUMENT_FUN_IPP(ippiSwapChannels_8u_C3C4R, pSrc, srcStep, pDst, dstStep, roiSize, dstOrder, MAX_IPP8u);\n}\nstatic IppStatus CV_STDCALL ippiSwapChannels_16u_C3C4Rf(const Ipp16u* pSrc, int srcStep, Ipp16u* pDst, int dstStep,\n IppiSize roiSize, const int *dstOrder)\n{\n return CV_INSTRUMENT_FUN_IPP(ippiSwapChannels_16u_C3C4R, pSrc, srcStep, pDst, dstStep, roiSize, dstOrder, MAX_IPP16u);\n}\nstatic IppStatus CV_STDCALL ippiSwapChannels_32f_C3C4Rf(const Ipp32f* pSrc, int srcStep, Ipp32f* pDst, int dstStep,\n IppiSize roiSize, const int *dstOrder)\n{\n return CV_INSTRUMENT_FUN_IPP(ippiSwapChannels_32f_C3C4R, pSrc, srcStep, pDst, dstStep, roiSize, dstOrder, MAX_IPP32f);\n}\n\nstatic const ippiColor2GrayFunc ippiColor2GrayC3Tab[CV_DEPTH_MAX] =\n{\n (ippiColor2GrayFunc)ippiColorToGray_8u_C3C1R, 0, (ippiColor2GrayFunc)ippiColorToGray_16u_C3C1R, 0,\n 0, (ippiColor2GrayFunc)ippiColorToGray_32f_C3C1R, 0, 0\n};\n\nstatic const ippiColor2GrayFunc ippiColor2GrayC4Tab[CV_DEPTH_MAX] =\n{\n (ippiColor2GrayFunc)ippiColorToGray_8u_AC4C1R, 0, (ippiColor2GrayFunc)ippiColorToGray_16u_AC4C1R, 0,\n 0, (ippiColor2GrayFunc)ippiColorToGray_32f_AC4C1R, 0, 0\n};\n\nstatic const ippiGeneralFunc ippiRGB2GrayC3Tab[CV_DEPTH_MAX] =\n{\n (ippiGeneralFunc)ippiRGBToGray_8u_C3C1R, 0, (ippiGeneralFunc)ippiRGBToGray_16u_C3C1R, 0,\n 0, (ippiGeneralFunc)ippiRGBToGray_32f_C3C1R, 0, 0\n};\n\nstatic const ippiGeneralFunc ippiRGB2GrayC4Tab[CV_DEPTH_MAX] =\n{\n (ippiGeneralFunc)ippiRGBToGray_8u_AC4C1R, 0, (ippiGeneralFunc)ippiRGBToGray_16u_AC4C1R, 0,\n 0, (ippiGeneralFunc)ippiRGBToGray_32f_AC4C1R, 0, 0\n};\n\nstatic const ippiReorderFunc ippiSwapChannelsC3C4RTab[CV_DEPTH_MAX] =\n{\n (ippiReorderFunc)ippiSwapChannels_8u_C3C4Rf, 0, (ippiReorderFunc)ippiSwapChannels_16u_C3C4Rf, 0,\n 0, (ippiReorderFunc)ippiSwapChannels_32f_C3C4Rf, 0, 0\n};\n\nstatic const ippiGeneralFunc ippiCopyAC4C3RTab[CV_DEPTH_MAX] =\n{\n (ippiGeneralFunc)ippiCopy_8u_AC4C3R, 0, (ippiGeneralFunc)ippiCopy_16u_AC4C3R, 0,\n 0, (ippiGeneralFunc)ippiCopy_32f_AC4C3R, 0, 0\n};\n\nstatic const ippiReorderFunc ippiSwapChannelsC4C3RTab[CV_DEPTH_MAX] =\n{\n (ippiReorderFunc)ippiSwapChannels_8u_C4C3R, 0, (ippiReorderFunc)ippiSwapChannels_16u_C4C3R, 0,\n 0, (ippiReorderFunc)ippiSwapChannels_32f_C4C3R, 0, 0\n};\n\nstatic const ippiReorderFunc ippiSwapChannelsC3RTab[CV_DEPTH_MAX] =\n{\n (ippiReorderFunc)ippiSwapChannels_8u_C3R, 0, (ippiReorderFunc)ippiSwapChannels_16u_C3R, 0,\n 0, (ippiReorderFunc)ippiSwapChannels_32f_C3R, 0, 0\n};\n\n#if IPP_VERSION_X100 >= 810\nstatic const ippiReorderFunc ippiSwapChannelsC4RTab[CV_DEPTH_MAX] =\n{\n (ippiReorderFunc)ippiSwapChannels_8u_C4R, 0, (ippiReorderFunc)ippiSwapChannels_16u_C4R, 0,\n 0, (ippiReorderFunc)ippiSwapChannels_32f_C4R, 0, 0\n};\n#endif\n\n#if !IPP_DISABLE_RGB_HSV\nstatic const ippiGeneralFunc ippiRGB2HSVTab[CV_DEPTH_MAX] =\n{\n (ippiGeneralFunc)ippiRGBToHSV_8u_C3R, 0, (ippiGeneralFunc)ippiRGBToHSV_16u_C3R, 0,\n 0, 0, 0, 0\n};\n#endif\n\nstatic const ippiGeneralFunc ippiHSV2RGBTab[CV_DEPTH_MAX] =\n{\n (ippiGeneralFunc)ippiHSVToRGB_8u_C3R, 0, (ippiGeneralFunc)ippiHSVToRGB_16u_C3R, 0,\n 0, 0, 0, 0\n};\n\nstatic const ippiGeneralFunc ippiRGB2HLSTab[CV_DEPTH_MAX] =\n{\n (ippiGeneralFunc)ippiRGBToHLS_8u_C3R, 0, (ippiGeneralFunc)ippiRGBToHLS_16u_C3R, 0,\n 0, (ippiGeneralFunc)ippiRGBToHLS_32f_C3R, 0, 0\n};\n\nstatic const ippiGeneralFunc ippiHLS2RGBTab[CV_DEPTH_MAX] =\n{\n (ippiGeneralFunc)ippiHLSToRGB_8u_C3R, 0, (ippiGeneralFunc)ippiHLSToRGB_16u_C3R, 0,\n 0, (ippiGeneralFunc)ippiHLSToRGB_32f_C3R, 0, 0\n};\n\n#if !IPP_DISABLE_RGB_XYZ\nstatic const ippiGeneralFunc ippiRGB2XYZTab[CV_DEPTH_MAX] =\n{\n (ippiGeneralFunc)ippiRGBToXYZ_8u_C3R, 0, (ippiGeneralFunc)ippiRGBToXYZ_16u_C3R, 0,\n 0, (ippiGeneralFunc)ippiRGBToXYZ_32f_C3R, 0, 0\n};\n#endif\n\n#if !IPP_DISABLE_XYZ_RGB\nstatic const ippiGeneralFunc ippiXYZ2RGBTab[CV_DEPTH_MAX] =\n{\n (ippiGeneralFunc)ippiXYZToRGB_8u_C3R, 0, (ippiGeneralFunc)ippiXYZToRGB_16u_C3R, 0,\n 0, (ippiGeneralFunc)ippiXYZToRGB_32f_C3R, 0, 0\n};\n#endif\n\n#if !IPP_DISABLE_RGB_LAB\nstatic const ippiGeneralFunc ippiRGBToLUVTab[CV_DEPTH_MAX] =\n{\n (ippiGeneralFunc)ippiRGBToLUV_8u_C3R, 0, (ippiGeneralFunc)ippiRGBToLUV_16u_C3R, 0,\n 0, (ippiGeneralFunc)ippiRGBToLUV_32f_C3R, 0, 0\n};\n#endif\n\n#if !IPP_DISABLE_LAB_RGB\nstatic const ippiGeneralFunc ippiLUVToRGBTab[CV_DEPTH_MAX] =\n{\n (ippiGeneralFunc)ippiLUVToRGB_8u_C3R, 0, (ippiGeneralFunc)ippiLUVToRGB_16u_C3R, 0,\n 0, (ippiGeneralFunc)ippiLUVToRGB_32f_C3R, 0, 0\n};\n#endif\n\n} // namespace\n\nint ipp_hal_cvtBGRtoBGR(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step,\n int width, int height, int depth, int scn, int dcn, bool swapBlue)\n{\n CV_HAL_CHECK_USE_IPP();\n\n if(scn == 3 && dcn == 4 && !swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPReorderFunctor(ippiSwapChannelsC3C4RTab[depth], 0, 1, 2)) )\n return CV_HAL_ERROR_OK;\n }\n else if(scn == 4 && dcn == 3 && !swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPGeneralFunctor(ippiCopyAC4C3RTab[depth])) )\n return CV_HAL_ERROR_OK;\n }\n else if(scn == 3 && dcn == 4 && swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPReorderFunctor(ippiSwapChannelsC3C4RTab[depth], 2, 1, 0)) )\n return CV_HAL_ERROR_OK;\n }\n else if(scn == 4 && dcn == 3 && swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPReorderFunctor(ippiSwapChannelsC4C3RTab[depth], 2, 1, 0)) )\n return CV_HAL_ERROR_OK;\n }\n else if(scn == 3 && dcn == 3 && swapBlue)\n {\n if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKETYPE(depth, scn), dst_data, dst_step, width, height,\n IPPReorderFunctor(ippiSwapChannelsC3RTab[depth], 2, 1, 0)) )\n return CV_HAL_ERROR_OK;\n }\n#if IPP_VERSION_X100 >= 810\n else if(scn == 4 && dcn == 4 && swapBlue)\n {\n if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKETYPE(depth, scn), dst_data, dst_step, width, height,\n IPPReorderFunctor(ippiSwapChannelsC4RTab[depth], 2, 1, 0)) )\n return CV_HAL_ERROR_OK;\n }\n#endif\n\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n}\n\nint ipp_hal_cvtGraytoBGR(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step,\n int width, int height, int depth, int dcn)\n{\n CV_HAL_CHECK_USE_IPP();\n\n bool ippres = false;\n if(dcn == 3)\n {\n if( depth == CV_8U )\n {\n#if !IPP_DISABLE_CVTCOLOR_GRAY2BGR_8UC3\n ippres = CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, IPPGray2BGRFunctor());\n#endif\n }\n else if( depth == CV_16U )\n ippres = CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, IPPGray2BGRFunctor());\n else\n ippres = CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, IPPGray2BGRFunctor());\n }\n else if(dcn == 4)\n {\n if( depth == CV_8U )\n ippres = CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, IPPGray2BGRAFunctor());\n else if( depth == CV_16U )\n ippres = CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, IPPGray2BGRAFunctor());\n else\n ippres = CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, IPPGray2BGRAFunctor());\n }\n\n return ippres ? CV_HAL_ERROR_OK : CV_HAL_ERROR_NOT_IMPLEMENTED;\n}\n\nint ipp_hal_cvtBGRtoGray(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step,\n int width, int height, int depth, int scn, bool swapBlue)\n{\n CV_HAL_CHECK_USE_IPP();\n\n // preserves original cvtBGRtoGray routing: only 32f was sent to IPP, other depths use the dispatch path\n if (depth != CV_32F)\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n\n if(scn == 3 && !swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPColor2GrayFunctor(ippiColor2GrayC3Tab[depth])) )\n return CV_HAL_ERROR_OK;\n }\n else if(scn == 3 && swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPGeneralFunctor(ippiRGB2GrayC3Tab[depth])) )\n return CV_HAL_ERROR_OK;\n }\n else if(scn == 4 && !swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPColor2GrayFunctor(ippiColor2GrayC4Tab[depth])) )\n return CV_HAL_ERROR_OK;\n }\n else if(scn == 4 && swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPGeneralFunctor(ippiRGB2GrayC4Tab[depth])) )\n return CV_HAL_ERROR_OK;\n }\n\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n}\n\nint ipp_hal_cvtBGRtoHSV(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step,\n int width, int height, int depth, int scn, bool swapBlue, bool isFullRange, bool isHSV)\n{\n CV_HAL_CHECK_USE_IPP();\n\n if(depth == CV_8U && isFullRange)\n {\n if (isHSV)\n {\n#if !IPP_DISABLE_RGB_HSV // breaks OCL accuracy tests\n if(scn == 3 && !swapBlue)\n {\n if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKE_TYPE(depth, scn), dst_data, dst_step, width, height,\n IPPReorderGeneralFunctor(ippiSwapChannelsC3RTab[depth], ippiRGB2HSVTab[depth], 2, 1, 0, depth)) )\n return CV_HAL_ERROR_OK;\n }\n else if(scn == 4 && !swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], ippiRGB2HSVTab[depth], 2, 1, 0, depth)) )\n return CV_HAL_ERROR_OK;\n }\n else if(scn == 4 && swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], ippiRGB2HSVTab[depth], 0, 1, 2, depth)) )\n return CV_HAL_ERROR_OK;\n }\n#endif\n }\n else\n {\n if(scn == 3 && !swapBlue)\n {\n if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKE_TYPE(depth, scn), dst_data, dst_step, width, height,\n IPPReorderGeneralFunctor(ippiSwapChannelsC3RTab[depth], ippiRGB2HLSTab[depth], 2, 1, 0, depth)) )\n return CV_HAL_ERROR_OK;\n }\n else if(scn == 4 && !swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], ippiRGB2HLSTab[depth], 2, 1, 0, depth)) )\n return CV_HAL_ERROR_OK;\n }\n else if(scn == 3 && swapBlue)\n {\n if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKE_TYPE(depth, scn), dst_data, dst_step, width, height,\n IPPGeneralFunctor(ippiRGB2HLSTab[depth])) )\n return CV_HAL_ERROR_OK;\n }\n else if(scn == 4 && swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], ippiRGB2HLSTab[depth], 0, 1, 2, depth)) )\n return CV_HAL_ERROR_OK;\n }\n }\n }\n\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n}\n\nint ipp_hal_cvtHSVtoBGR(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step,\n int width, int height, int depth, int dcn, bool swapBlue, bool isFullRange, bool isHSV)\n{\n CV_HAL_CHECK_USE_IPP();\n\n if (depth == CV_8U && isFullRange)\n {\n if (isHSV)\n {\n if(dcn == 3 && !swapBlue)\n {\n if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKETYPE(depth, 3), dst_data, dst_step, width, height,\n IPPGeneralReorderFunctor(ippiHSV2RGBTab[depth], ippiSwapChannelsC3RTab[depth], 2, 1, 0, depth)) )\n return CV_HAL_ERROR_OK;\n }\n else if(dcn == 4 && !swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPGeneralReorderFunctor(ippiHSV2RGBTab[depth], ippiSwapChannelsC3C4RTab[depth], 2, 1, 0, depth)) )\n return CV_HAL_ERROR_OK;\n }\n else if(dcn == 3 && swapBlue)\n {\n if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKETYPE(depth, 3), dst_data, dst_step, width, height,\n IPPGeneralFunctor(ippiHSV2RGBTab[depth])) )\n return CV_HAL_ERROR_OK;\n }\n else if(dcn == 4 && swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPGeneralReorderFunctor(ippiHSV2RGBTab[depth], ippiSwapChannelsC3C4RTab[depth], 0, 1, 2, depth)) )\n return CV_HAL_ERROR_OK;\n }\n }\n else\n {\n if(dcn == 3 && !swapBlue)\n {\n if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKETYPE(depth, 3), dst_data, dst_step, width, height,\n IPPGeneralReorderFunctor(ippiHLS2RGBTab[depth], ippiSwapChannelsC3RTab[depth], 2, 1, 0, depth)) )\n return CV_HAL_ERROR_OK;\n }\n else if(dcn == 4 && !swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPGeneralReorderFunctor(ippiHLS2RGBTab[depth], ippiSwapChannelsC3C4RTab[depth], 2, 1, 0, depth)) )\n return CV_HAL_ERROR_OK;\n }\n else if(dcn == 3 && swapBlue)\n {\n if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKETYPE(depth, 3), dst_data, dst_step, width, height,\n IPPGeneralFunctor(ippiHLS2RGBTab[depth])) )\n return CV_HAL_ERROR_OK;\n }\n else if(dcn == 4 && swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPGeneralReorderFunctor(ippiHLS2RGBTab[depth], ippiSwapChannelsC3C4RTab[depth], 0, 1, 2, depth)) )\n return CV_HAL_ERROR_OK;\n }\n }\n }\n\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n}\n\nint ipp_hal_cvtRGBAtoMultipliedRGBA(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step,\n int width, int height)\n{\n CV_HAL_CHECK_USE_IPP();\n\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPGeneralFunctor((ippiGeneralFunc)ippiAlphaPremul_8u_AC4R)) )\n return CV_HAL_ERROR_OK;\n\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n}\n\n#if !IPP_DISABLE_RGB_YUV\nint ipp_hal_cvtBGRtoYUV(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step,\n int width, int height, int depth, int scn, bool swapBlue, bool isCbCr)\n{\n CV_HAL_CHECK_USE_IPP();\n\n if (scn == 3 && depth == CV_8U && swapBlue && !isCbCr)\n {\n if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPGeneralFunctor((ippiGeneralFunc)ippiRGBToYUV_8u_C3R)))\n return CV_HAL_ERROR_OK;\n }\n else if (scn == 3 && depth == CV_8U && !swapBlue && !isCbCr)\n {\n if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPReorderGeneralFunctor(ippiSwapChannelsC3RTab[depth],\n (ippiGeneralFunc)ippiRGBToYUV_8u_C3R, 2, 1, 0, depth)))\n return CV_HAL_ERROR_OK;\n }\n else if (scn == 4 && depth == CV_8U && swapBlue && !isCbCr)\n {\n if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth],\n (ippiGeneralFunc)ippiRGBToYUV_8u_C3R, 0, 1, 2, depth)))\n return CV_HAL_ERROR_OK;\n }\n else if (scn == 4 && depth == CV_8U && !swapBlue && !isCbCr)\n {\n if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth],\n (ippiGeneralFunc)ippiRGBToYUV_8u_C3R, 2, 1, 0, depth)))\n return CV_HAL_ERROR_OK;\n }\n\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n}\n#endif // !IPP_DISABLE_RGB_YUV\n\n#if !IPP_DISABLE_YUV_RGB\nint ipp_hal_cvtYUVtoBGR(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step,\n int width, int height, int depth, int dcn, bool swapBlue, bool isCbCr)\n{\n CV_HAL_CHECK_USE_IPP();\n\n if (dcn == 3 && depth == CV_8U && swapBlue && !isCbCr)\n {\n if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPGeneralFunctor((ippiGeneralFunc)ippiYUVToRGB_8u_C3R)))\n return CV_HAL_ERROR_OK;\n }\n else if (dcn == 3 && depth == CV_8U && !swapBlue && !isCbCr)\n {\n if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPGeneralReorderFunctor((ippiGeneralFunc)ippiYUVToRGB_8u_C3R,\n ippiSwapChannelsC3RTab[depth], 2, 1, 0, depth)))\n return CV_HAL_ERROR_OK;\n }\n else if (dcn == 4 && depth == CV_8U && swapBlue && !isCbCr)\n {\n if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPGeneralReorderFunctor((ippiGeneralFunc)ippiYUVToRGB_8u_C3R,\n ippiSwapChannelsC3C4RTab[depth], 0, 1, 2, depth)))\n return CV_HAL_ERROR_OK;\n }\n else if (dcn == 4 && depth == CV_8U && !swapBlue && !isCbCr)\n {\n if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPGeneralReorderFunctor((ippiGeneralFunc)ippiYUVToRGB_8u_C3R,\n ippiSwapChannelsC3C4RTab[depth], 2, 1, 0, depth)))\n return CV_HAL_ERROR_OK;\n }\n\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n}\n#endif // !IPP_DISABLE_YUV_RGB\n\n#if !IPP_DISABLE_RGB_XYZ\nint ipp_hal_cvtBGRtoXYZ(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step,\n int width, int height, int depth, int scn, bool swapBlue)\n{\n CV_HAL_CHECK_USE_IPP();\n\n if(scn == 3 && depth != CV_32F && !swapBlue)\n {\n if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKETYPE(depth, scn), dst_data, dst_step, width, height,\n IPPReorderGeneralFunctor(ippiSwapChannelsC3RTab[depth], ippiRGB2XYZTab[depth], 2, 1, 0, depth)) )\n return CV_HAL_ERROR_OK;\n }\n else if(scn == 4 && depth != CV_32F && !swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], ippiRGB2XYZTab[depth], 2, 1, 0, depth)) )\n return CV_HAL_ERROR_OK;\n }\n else if(scn == 3 && depth != CV_32F && swapBlue)\n {\n if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKETYPE(depth, scn), dst_data, dst_step, width, height,\n IPPGeneralFunctor(ippiRGB2XYZTab[depth])) )\n return CV_HAL_ERROR_OK;\n }\n else if(scn == 4 && depth != CV_32F && swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], ippiRGB2XYZTab[depth], 0, 1, 2, depth)) )\n return CV_HAL_ERROR_OK;\n }\n\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n}\n#endif // !IPP_DISABLE_RGB_XYZ\n\n#if !IPP_DISABLE_XYZ_RGB\nint ipp_hal_cvtXYZtoBGR(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step,\n int width, int height, int depth, int dcn, bool swapBlue)\n{\n CV_HAL_CHECK_USE_IPP();\n\n if(dcn == 3 && depth != CV_32F && !swapBlue)\n {\n if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKETYPE(depth, 3), dst_data, dst_step, width, height,\n IPPGeneralReorderFunctor(ippiXYZ2RGBTab[depth], ippiSwapChannelsC3RTab[depth], 2, 1, 0, depth)) )\n return CV_HAL_ERROR_OK;\n }\n else if(dcn == 4 && depth != CV_32F && !swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPGeneralReorderFunctor(ippiXYZ2RGBTab[depth], ippiSwapChannelsC3C4RTab[depth], 2, 1, 0, depth)) )\n return CV_HAL_ERROR_OK;\n }\n if(dcn == 3 && depth != CV_32F && swapBlue)\n {\n if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKETYPE(depth, 3), dst_data, dst_step, width, height,\n IPPGeneralFunctor(ippiXYZ2RGBTab[depth])) )\n return CV_HAL_ERROR_OK;\n }\n else if(dcn == 4 && depth != CV_32F && swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPGeneralReorderFunctor(ippiXYZ2RGBTab[depth], ippiSwapChannelsC3C4RTab[depth], 0, 1, 2, depth)) )\n return CV_HAL_ERROR_OK;\n }\n\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n}\n#endif // !IPP_DISABLE_XYZ_RGB\n\n#if !IPP_DISABLE_RGB_LAB\nint ipp_hal_cvtBGRtoLab(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step,\n int width, int height, int depth, int scn, bool swapBlue, bool isLab, bool srgb)\n{\n CV_HAL_CHECK_USE_IPP();\n\n if (!srgb)\n {\n if (isLab)\n {\n if (scn == 3 && depth == CV_8U && !swapBlue)\n {\n if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPGeneralFunctor((ippiGeneralFunc)ippiBGRToLab_8u_C3R)))\n return CV_HAL_ERROR_OK;\n }\n else if (scn == 4 && depth == CV_8U && !swapBlue)\n {\n if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth],\n (ippiGeneralFunc)ippiBGRToLab_8u_C3R, 0, 1, 2, depth)))\n return CV_HAL_ERROR_OK;\n }\n else if (scn == 3 && depth == CV_8U && swapBlue) // slower than OpenCV\n {\n if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPReorderGeneralFunctor(ippiSwapChannelsC3RTab[depth],\n (ippiGeneralFunc)ippiBGRToLab_8u_C3R, 2, 1, 0, depth)))\n return CV_HAL_ERROR_OK;\n }\n else if (scn == 4 && depth == CV_8U && swapBlue) // slower than OpenCV\n {\n if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth],\n (ippiGeneralFunc)ippiBGRToLab_8u_C3R, 2, 1, 0, depth)))\n return CV_HAL_ERROR_OK;\n }\n }\n else\n {\n if (scn == 3 && swapBlue)\n {\n if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPGeneralFunctor(ippiRGBToLUVTab[depth])))\n return CV_HAL_ERROR_OK;\n }\n else if (scn == 4 && swapBlue)\n {\n if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth],\n ippiRGBToLUVTab[depth], 0, 1, 2, depth)))\n return CV_HAL_ERROR_OK;\n }\n else if (scn == 3 && !swapBlue)\n {\n if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPReorderGeneralFunctor(ippiSwapChannelsC3RTab[depth],\n ippiRGBToLUVTab[depth], 2, 1, 0, depth)))\n return CV_HAL_ERROR_OK;\n }\n else if (scn == 4 && !swapBlue)\n {\n if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth],\n ippiRGBToLUVTab[depth], 2, 1, 0, depth)))\n return CV_HAL_ERROR_OK;\n }\n }\n }\n\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n}\n#endif // !IPP_DISABLE_RGB_LAB\n\n#if !IPP_DISABLE_LAB_RGB\nint ipp_hal_cvtLabtoBGR(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step,\n int width, int height, int depth, int dcn, bool swapBlue, bool isLab, bool srgb)\n{\n CV_HAL_CHECK_USE_IPP();\n\n if (!srgb)\n {\n if (isLab)\n {\n if( dcn == 3 && depth == CV_8U && !swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPGeneralFunctor((ippiGeneralFunc)ippiLabToBGR_8u_C3R)) )\n return CV_HAL_ERROR_OK;\n }\n else if( dcn == 4 && depth == CV_8U && !swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPGeneralReorderFunctor((ippiGeneralFunc)ippiLabToBGR_8u_C3R,\n ippiSwapChannelsC3C4RTab[depth], 0, 1, 2, depth)) )\n return CV_HAL_ERROR_OK;\n }\n if( dcn == 3 && depth == CV_8U && swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPGeneralReorderFunctor((ippiGeneralFunc)ippiLabToBGR_8u_C3R,\n ippiSwapChannelsC3RTab[depth], 2, 1, 0, depth)) )\n return CV_HAL_ERROR_OK;\n }\n else if( dcn == 4 && depth == CV_8U && swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPGeneralReorderFunctor((ippiGeneralFunc)ippiLabToBGR_8u_C3R,\n ippiSwapChannelsC3C4RTab[depth], 2, 1, 0, depth)) )\n return CV_HAL_ERROR_OK;\n }\n }\n else\n {\n if( dcn == 3 && swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPGeneralFunctor(ippiLUVToRGBTab[depth])) )\n return CV_HAL_ERROR_OK;\n }\n else if( dcn == 4 && swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPGeneralReorderFunctor(ippiLUVToRGBTab[depth],\n ippiSwapChannelsC3C4RTab[depth], 0, 1, 2, depth)) )\n return CV_HAL_ERROR_OK;\n }\n if( dcn == 3 && !swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPGeneralReorderFunctor(ippiLUVToRGBTab[depth],\n ippiSwapChannelsC3RTab[depth], 2, 1, 0, depth)) )\n return CV_HAL_ERROR_OK;\n }\n else if( dcn == 4 && !swapBlue)\n {\n if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height,\n IPPGeneralReorderFunctor(ippiLUVToRGBTab[depth],\n ippiSwapChannelsC3C4RTab[depth], 2, 1, 0, depth)) )\n return CV_HAL_ERROR_OK;\n }\n }\n }\n\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n}\n#endif // !IPP_DISABLE_LAB_RGB\n\n#endif // IPP_VERSION_X100 >= 700\n", "source": "opencv", "added": "2026-11-08", "created": "", "token_count": 11391, "license": "Apache-2.0", "author": "opencv contributors"}
{"id": "github:opencv:hal/ndsrvp/src/cvutils.hpp", "text": "// This file is part of OpenCV project.\n// It is subject to the license terms in the LICENSE file found in the top-level directory\n// of this distribution and at http://opencv.org/license.html.\n\n#ifndef OPENCV_NDSRVP_CVUTILS_HPP\n#define OPENCV_NDSRVP_CVUTILS_HPP\n\n#include \n\n#include \"opencv2/core/hal/interface.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n// misc functions that not exposed to public interface\n\nnamespace cv {\n\nnamespace ndsrvp {\n\nvoid* fastMalloc(size_t size);\nvoid fastFree(void* ptr);\nint borderInterpolate(int p, int len, int borderType);\nint16x4_t borderInterpolate_vector(int16x4_t vp, short len, int borderType);\n\n#ifndef MAX\n# define MAX(a,b) ((a) < (b) ? (b) : (a))\n#endif\n\n#ifndef MIN\n# define MIN(a,b) ((a) > (b) ? (b) : (a))\n#endif\n\n#define CV_MAT_CN_MASK ((CV_CN_MAX - 1) << CV_CN_SHIFT)\n#define CV_MAT_CN(flags) ((((flags) & CV_MAT_CN_MASK) >> CV_CN_SHIFT) + 1)\n\n#define CV_ELEM_SIZE1(type) ((0x28442211 >> CV_MAT_DEPTH(type)*4) & 15)\n#define CV_ELEM_SIZE(type) (CV_MAT_CN(type)*CV_ELEM_SIZE1(type))\n\n#define CV_MALLOC_ALIGN 64\n\ninline size_t getElemSize(int type) { return (size_t)CV_ELEM_SIZE(type); }\n\n// error codes\n\nenum Error{\n StsNoMem = -4,\n StsBadArg = -5,\n StsAssert = -215\n};\n\n// output error\n\n#define ndsrvp_assert(expr) { if(!(expr)) ndsrvp_error(Error::StsAssert, std::string(#expr)); }\n\ninline void ndsrvp_error(int code, std::string msg = \"\")\n{\n std::cerr << \"NDSRVP Error: code \" << code << std::endl;\n if(!msg.empty())\n std::cerr << msg << std::endl;\n if(code < 0)\n throw code;\n}\n\n// clip & vclip\n\ninline int clip(int x, int a, int b)\n{\n return x >= a ? (x < b ? x : b - 1) : a;\n}\n\ninline int32x2_t vclip(int32x2_t x, int32x2_t a, int32x2_t b)\n{\n return (int32x2_t)__nds__bpick((long)a, __nds__bpick((long)(b - 1), (long)x, (long)(x < b)), (long)(x >= a));\n}\n\n// expand\n\n/*\n [0] [1] [2] [3] [4] [5] [6] [7]\n810 [ 0 ] [ 1 ] [ 4 ] [ 5 ]\n832 [ 2 ] [ 3 ] [ 6 ] [ 7 ]\nbb [ 0 ] [ 1 ] [ 2 ] [ 3 ]\ntt [ 4 ] [ 5 ] [ 6 ] [ 7 ]\n*/\n\ninline void ndsrvp_u8_u16_expand8(const unsigned long vs, ushort* dst)\n{\n unsigned long vs810 = __nds__zunpkd810(vs);\n unsigned long vs832 = __nds__zunpkd832(vs);\n *(unsigned long*)dst = __nds__pkbb32(vs832, vs810);\n *(unsigned long*)(dst + 4) = __nds__pktt32(vs832, vs810);\n}\n\n/*\n [0] [1] [2] [3] [4] [5] [6] [7]\n820 [ 0 ] [ 2 ] [ 4 ] [ 6 ]\n831 [ 1 ] [ 3 ] [ 5 ] [ 7 ]\nbb [ 0 ] [ 2 ] [ 1 ] [ 3 ]\ntt [ 4 ] [ 6 ] [ 5 ] [ 7 ]\n*/\n\ninline void ndsrvp_u8_u16_eswap8(const unsigned long vs, ushort* dst)\n{\n unsigned long vs820 = __nds__zunpkd820(vs);\n unsigned long vs831 = __nds__zunpkd831(vs);\n *(unsigned long*)dst = __nds__pkbb32(vs831, vs820);\n *(unsigned long*)(dst + 4) = __nds__pktt32(vs831, vs820);\n}\n\n/*\n [0] [1] [2] [3] [4] [5] [6] [7]\n820 [ 0 ] [ 2 ] [ 4 ] [ 6 ]\n831 [ 1 ] [ 3 ] [ 5 ] [ 7 ]\nbb [ 0 ] [ 2 ] [ 1 ] [ 3 ]\ntt [ 4 ] [ 6 ] [ 5 ] [ 7 ]\nbbbb[ 0 ] [ 1 ]\nbbtt[ 2 ] [ 3 ]\nttbb[ 4 ] [ 5 ]\ntttt[ 6 ] [ 7 ]\n*/\n\n\ninline void ndsrvp_u8_u32_expand8(const unsigned long vs, uint* dst)\n{\n unsigned long vs820 = __nds__zunpkd820(vs);\n unsigned long vs831 = __nds__zunpkd831(vs);\n unsigned long vsbb = __nds__pkbb32(vs831, vs820);\n unsigned long vstt = __nds__pktt32(vs831, vs820);\n *(unsigned long*)dst = __nds__pkbb16(0, vsbb);\n *(unsigned long*)(dst + 2) = __nds__pktt16(0, vsbb);\n *(unsigned long*)(dst + 4) = __nds__pkbb16(0, vstt);\n *(unsigned long*)(dst + 6) = __nds__pktt16(0, vstt);\n}\n\n// float replacement\n\ninline void ndsrvp_f32_add8(const float* a, const float* b, float* c)\n{\n c[0] = a[0] + b[0];\n c[1] = a[1] + b[1];\n c[2] = a[2] + b[2];\n c[3] = a[3] + b[3];\n c[4] = a[4] + b[4];\n c[5] = a[5] + b[5];\n c[6] = a[6] + b[6];\n c[7] = a[7] + b[7];\n}\n\n/*\n [1] [8] [23]\n [24] [8]\n*/\n\ninline void ndsrvp_f32_u8_mul8(const float* a, const unsigned long b, float* c) // experimental, not bit exact\n{\n const int mask_frac = 0x007FFFFF;\n const int mask_sign = 0x7FFFFFFF;\n const int mask_lead = 0x40000000;\n const int ofs_exp = 23;\n\n uint32x2_t va01 = *(uint32x2_t*)a;\n uint32x2_t va23 = *(uint32x2_t*)(a + 2);\n uint32x2_t va45 = *(uint32x2_t*)(a + 4);\n uint32x2_t va67 = *(uint32x2_t*)(a + 6);\n\n uint32x2_t vaexp01 = va01 >> ofs_exp;\n uint32x2_t vaexp23 = va23 >> ofs_exp;\n uint32x2_t vaexp45 = va45 >> ofs_exp;\n uint32x2_t vaexp67 = va67 >> ofs_exp;\n\n uint32x2_t vafrac01 = ((va01 << 7) & mask_sign) | mask_lead;\n uint32x2_t vafrac23 = ((va23 << 7) & mask_sign) | mask_lead;\n uint32x2_t vafrac45 = ((va45 << 7) & mask_sign) | mask_lead;\n uint32x2_t vafrac67 = ((va67 << 7) & mask_sign) | mask_lead;\n\n int16x4_t vb[2]; // fake signed for signed multiply\n ndsrvp_u8_u16_eswap8(b, (ushort*)vb);\n\n vafrac01 = (uint32x2_t)__nds__kmmwb2_u((long)vafrac01, (unsigned long)vb[0]);\n vafrac23 = (uint32x2_t)__nds__kmmwt2_u((long)vafrac23, (unsigned long)vb[0]);\n vafrac45 = (uint32x2_t)__nds__kmmwb2_u((long)vafrac45, (unsigned long)vb[1]);\n vafrac67 = (uint32x2_t)__nds__kmmwt2_u((long)vafrac67, (unsigned long)vb[1]);\n\n uint32x2_t vaclz01 = __nds__v_clz32(vafrac01) - 8;\n uint32x2_t vaclz23 = __nds__v_clz32(vafrac23) - 8;\n uint32x2_t vaclz45 = __nds__v_clz32(vafrac45) - 8;\n uint32x2_t vaclz67 = __nds__v_clz32(vafrac67) - 8;\n\n vaexp01 += 8 - vaclz01;\n vaexp23 += 8 - vaclz23;\n vaexp45 += 8 - vaclz45;\n vaexp67 += 8 - vaclz67;\n\n vafrac01 <<= vaclz01;\n vafrac23 <<= vaclz23;\n vafrac45 <<= vaclz45;\n vafrac67 <<= vaclz67;\n\n *(uint32x2_t*)c = (vaexp01 << ofs_exp) | (vafrac01 & mask_frac);\n *(uint32x2_t*)(c + 2) = (vaexp23 << ofs_exp) | (vafrac23 & mask_frac);\n *(uint32x2_t*)(c + 4) = (vaexp45 << ofs_exp) | (vafrac45 & mask_frac);\n *(uint32x2_t*)(c + 6) = (vaexp67 << ofs_exp) | (vafrac67 & mask_frac);\n}\n\n// saturate\n\ntemplate static inline _Tp saturate_cast(int v) { return _Tp(v); }\ntemplate static inline _Tp saturate_cast(float v) { return _Tp(v); }\ntemplate static inline _Tp saturate_cast(double v) { return _Tp(v); }\n\ntemplate<> inline uchar saturate_cast(int v) { return __nds__uclip32(v, 8); }\ntemplate<> inline uchar saturate_cast(float v) { return saturate_cast((int)lrintf(v)); }\ntemplate<> inline uchar saturate_cast(double v) { return saturate_cast((int)lrint(v)); }\n\ntemplate<> inline char saturate_cast(int v) { return __nds__sclip32(v, 7); }\ntemplate<> inline char saturate_cast(float v) { return saturate_cast((int)lrintf(v)); }\ntemplate<> inline char saturate_cast(double v) { return saturate_cast((int)lrint(v)); }\n\ntemplate<> inline ushort saturate_cast(int v) { return __nds__uclip32(v, 16); }\ntemplate<> inline ushort saturate_cast(float v) { return saturate_cast((int)lrintf(v)); }\ntemplate<> inline ushort saturate_cast(double v) { return saturate_cast((int)lrint(v)); }\n\ntemplate<> inline short saturate_cast(int v) { return __nds__sclip32(v, 15); }\ntemplate<> inline short saturate_cast(float v) { return saturate_cast((int)lrintf(v)); }\ntemplate<> inline short saturate_cast(double v) { return saturate_cast((int)lrint(v)); }\n\ntemplate<> inline int saturate_cast(float v) { return (int)lrintf(v); }\ntemplate<> inline int saturate_cast(double v) { return (int)lrint(v); }\n\ninline double cast_ptr_to_double(const uchar* v, int depth) {\n switch (depth) {\n case CV_8U: return (double)*(uchar*)v;\n case CV_8S: return (double)*(char*)v;\n case CV_16U: return (double)*(ushort*)v;\n case CV_16S: return (double)*(short*)v;\n case CV_32S: return (double)*(int*)v;\n case CV_32F: return (double)*(float*)v;\n case CV_64F: return (double)*(double*)v;\n case CV_16F: return (double)*(float*)v;\n default: return 0;\n }\n}\n\ntemplate \ninline _Tp data_at(const uchar* data, int step, int y, int x, int cn)\n{\n return ((_Tp*)(data + y * step))[x * cn];\n}\n\n// align\n\ninline long align(size_t v, int n)\n{\n return (v + n - 1) & -n;\n}\n\n} // namespace ndsrvp\n\n} // namespace cv\n\n#endif\n", "source": "opencv", "added": "2026-11-08", "created": "", "token_count": 3117, "license": "Apache-2.0", "author": "opencv contributors"}
{"id": "github:opencv:hal/riscv-rvv/src/core/convert_scale.cpp", "text": "// This file is part of OpenCV project.\n// It is subject to the license terms in the LICENSE file found in the top-level directory\n// of this distribution and at http://opencv.org/license.html.\n\n// Copyright (C) 2025, Institute of Software, Chinese Academy of Sciences.\n\n#include \"rvv_hal.hpp\"\n\nnamespace cv { namespace rvv_hal { namespace core {\n\n#if CV_HAL_RVV_1P0_ENABLED\n\ninline int convertScale_8U8U(const uchar* src, size_t src_step, uchar* dst, size_t dst_step, int width, int height, double alpha, double beta)\n{\n int vlmax = __riscv_vsetvlmax_e32m8();\n auto vec_b = __riscv_vfmv_v_f_f32m8(beta, vlmax);\n float a = alpha;\n\n for (int i = 0; i < height; i++)\n {\n const uchar* src_row = src + i * src_step;\n uchar* dst_row = dst + i * dst_step;\n int vl;\n for (int j = 0; j < width; j += vl)\n {\n vl = __riscv_vsetvl_e8m2(width - j);\n auto vec_src = __riscv_vle8_v_u8m2(src_row + j, vl);\n auto vec_src_u16 = __riscv_vzext_vf2(vec_src, vl);\n auto vec_src_f32 = __riscv_vfwcvt_f(vec_src_u16, vl);\n auto vec_fma = __riscv_vfmadd(vec_src_f32, a, vec_b, vl);\n auto vec_dst_u16 = __riscv_vfncvt_xu(vec_fma, vl);\n auto vec_dst = __riscv_vnclipu(vec_dst_u16, 0, __RISCV_VXRM_RNU, vl);\n __riscv_vse8_v_u8m2(dst_row + j, vec_dst, vl);\n }\n }\n\n return CV_HAL_ERROR_OK;\n}\n\ninline int convertScale_8U32F(const uchar* src, size_t src_step, uchar* dst, size_t dst_step, int width, int height, double alpha, double beta)\n{\n int vlmax = __riscv_vsetvlmax_e32m8();\n auto vec_b = __riscv_vfmv_v_f_f32m8(beta, vlmax);\n float a = alpha;\n\n for (int i = 0; i < height; i++)\n {\n const uchar* src_row = src + i * src_step;\n float* dst_row = reinterpret_cast(dst + i * dst_step);\n int vl;\n for (int j = 0; j < width; j += vl)\n {\n vl = __riscv_vsetvl_e8m2(width - j);\n auto vec_src = __riscv_vle8_v_u8m2(src_row + j, vl);\n auto vec_src_u16 = __riscv_vzext_vf2(vec_src, vl);\n auto vec_src_f32 = __riscv_vfwcvt_f(vec_src_u16, vl);\n auto vec_fma = __riscv_vfmadd(vec_src_f32, a, vec_b, vl);\n __riscv_vse32_v_f32m8(dst_row + j, vec_fma, vl);\n }\n }\n\n return CV_HAL_ERROR_OK;\n}\n\ninline int convertScale_8U16U(const uchar* src, size_t src_step, uchar* dst, size_t dst_step, int width, int height, double alpha, double beta)\n{\n if (alpha == 1.0 && beta == 0.0)\n {\n for (int i = 0; i < height; i++)\n {\n const uchar* src_row = src + i * src_step;\n ushort* dst_row = reinterpret_cast(dst + i * dst_step);\n int vl;\n for (int j = 0; j < width; j += vl)\n {\n vl = __riscv_vsetvl_e8m2(width - j);\n auto vec_src = __riscv_vle8_v_u8m2(src_row + j, vl);\n auto vec_dst = __riscv_vzext_vf2(vec_src, vl);\n __riscv_vse16_v_u16m4(dst_row + j, vec_dst, vl);\n }\n }\n\n return CV_HAL_ERROR_OK;\n }\n\n int vlmax = __riscv_vsetvlmax_e32m8();\n auto vec_b = __riscv_vfmv_v_f_f32m8(beta, vlmax);\n float a = alpha;\n\n for (int i = 0; i < height; i++)\n {\n const uchar* src_row = src + i * src_step;\n ushort* dst_row = reinterpret_cast(dst + i * dst_step);\n int vl;\n for (int j = 0; j < width; j += vl)\n {\n vl = __riscv_vsetvl_e8m2(width - j);\n auto vec_src = __riscv_vle8_v_u8m2(src_row + j, vl);\n auto vec_src_u16 = __riscv_vzext_vf2(vec_src, vl);\n auto vec_src_f32 = __riscv_vfwcvt_f(vec_src_u16, vl);\n auto vec_fma = __riscv_vfmadd(vec_src_f32, a, vec_b, vl);\n auto vec_dst = __riscv_vfncvt_xu(vec_fma, vl);\n __riscv_vse16_v_u16m4(dst_row + j, vec_dst, vl);\n }\n }\n\n return CV_HAL_ERROR_OK;\n}\n\ninline int convertScale_8U16S(const uchar* src, size_t src_step, uchar* dst, size_t dst_step, int width, int height, double alpha, double beta)\n{\n if (alpha == 1.0 && beta == 0.0)\n {\n for (int i = 0; i < height; i++)\n {\n const uchar* src_row = src + i * src_step;\n short* dst_row = reinterpret_cast(dst + i * dst_step);\n int vl;\n for (int j = 0; j < width; j += vl)\n {\n vl = __riscv_vsetvl_e8m2(width - j);\n auto vec_src = __riscv_vle8_v_u8m2(src_row + j, vl);\n auto vec_dst = __riscv_vreinterpret_v_u16m4_i16m4(__riscv_vzext_vf2(vec_src, vl));\n __riscv_vse16_v_i16m4(dst_row + j, vec_dst, vl);\n }\n }\n\n return CV_HAL_ERROR_OK;\n }\n\n int vlmax = __riscv_vsetvlmax_e32m8();\n auto vec_b = __riscv_vfmv_v_f_f32m8(beta, vlmax);\n float a = alpha;\n\n for (int i = 0; i < height; i++)\n {\n const uchar* src_row = src + i * src_step;\n short* dst_row = reinterpret_cast(dst + i * dst_step);\n int vl;\n for (int j = 0; j < width; j += vl)\n {\n vl = __riscv_vsetvl_e8m2(width - j);\n auto vec_src = __riscv_vle8_v_u8m2(src_row + j, vl);\n auto vec_src_u16 = __riscv_vzext_vf2(vec_src, vl);\n auto vec_src_f32 = __riscv_vfwcvt_f(vec_src_u16, vl);\n auto vec_fma = __riscv_vfmadd(vec_src_f32, a, vec_b, vl);\n auto vec_dst = __riscv_vfncvt_x(vec_fma, vl);\n __riscv_vse16_v_i16m4(dst_row + j, vec_dst, vl);\n }\n }\n\n return CV_HAL_ERROR_OK;\n}\n\ninline int convertScale_16U8U(const uchar* src, size_t src_step, uchar* dst, size_t dst_step, int width, int height, double alpha, double beta)\n{\n if (alpha == 1.0 && beta == 0.0)\n {\n for (int i = 0; i < height; i++)\n {\n const ushort* src_row = reinterpret_cast(src + i * src_step);\n uchar* dst_row = dst + i * dst_step;\n int vl;\n for (int j = 0; j < width; j += vl)\n {\n vl = __riscv_vsetvl_e16m4(width - j);\n auto vec_src = __riscv_vle16_v_u16m4(src_row + j, vl);\n auto vec_dst = __riscv_vnclipu(vec_src, 0, __RISCV_VXRM_RNU, vl);\n __riscv_vse8_v_u8m2(dst_row + j, vec_dst, vl);\n }\n }\n\n return CV_HAL_ERROR_OK;\n }\n\n int vlmax = __riscv_vsetvlmax_e32m8();\n auto vec_b = __riscv_vfmv_v_f_f32m8(beta, vlmax);\n float a = alpha;\n\n for (int i = 0; i < height; i++)\n {\n const ushort* src_row = reinterpret_cast(src + i * src_step);\n uchar* dst_row = dst + i * dst_step;\n int vl;\n for (int j = 0; j < width; j += vl)\n {\n vl = __riscv_vsetvl_e16m4(width - j);\n auto vec_src = __riscv_vle16_v_u16m4(src_row + j, vl);\n auto vec_src_f32 = __riscv_vfwcvt_f(vec_src, vl);\n auto vec_fma = __riscv_vfmadd(vec_src_f32, a, vec_b, vl);\n auto vec_dst_u16 = __riscv_vfncvt_xu(vec_fma, vl);\n auto vec_dst = __riscv_vnclipu(vec_dst_u16, 0, __RISCV_VXRM_RNU, vl);\n __riscv_vse8_v_u8m2(dst_row + j, vec_dst, vl);\n }\n }\n\n return CV_HAL_ERROR_OK;\n}\n\ninline int convertScale_16U32F(const uchar* src, size_t src_step, uchar* dst, size_t dst_step, int width, int height, double alpha, double beta)\n{\n int vlmax = __riscv_vsetvlmax_e32m8();\n auto vec_b = __riscv_vfmv_v_f_f32m8(beta, vlmax);\n float a = alpha;\n\n for (int i = 0; i < height; i++)\n {\n const ushort* src_row = reinterpret_cast(src + i * src_step);\n float* dst_row = reinterpret_cast(dst + i * dst_step);\n int vl;\n for (int j = 0; j < width; j += vl)\n {\n vl = __riscv_vsetvl_e16m4(width - j);\n auto vec_src = __riscv_vle16_v_u16m4(src_row + j, vl);\n auto vec_src_f32 = __riscv_vfwcvt_f(vec_src, vl);\n auto vec_fma = __riscv_vfmadd(vec_src_f32, a, vec_b, vl);\n __riscv_vse32_v_f32m8(dst_row + j, vec_fma, vl);\n }\n }\n\n return CV_HAL_ERROR_OK;\n}\n\ninline int convertScale_16S32F(const uchar* src, size_t src_step, uchar* dst, size_t dst_step, int width, int height, double alpha, double beta)\n{\n int vlmax = __riscv_vsetvlmax_e32m8();\n auto vec_b = __riscv_vfmv_v_f_f32m8(beta, vlmax);\n float a = alpha;\n\n for (int i = 0; i < height; i++)\n {\n const short* src_row = reinterpret_cast(src + i * src_step);\n float* dst_row = reinterpret_cast(dst + i * dst_step);\n int vl;\n for (int j = 0; j < width; j += vl)\n {\n vl = __riscv_vsetvl_e16m4(width - j);\n auto vec_src = __riscv_vle16_v_i16m4(src_row + j, vl);\n auto vec_src_f32 = __riscv_vfwcvt_f(vec_src, vl);\n auto vec_fma = __riscv_vfmadd(vec_src_f32, a, vec_b, vl);\n __riscv_vse32_v_f32m8(dst_row + j, vec_fma, vl);\n }\n }\n\n return CV_HAL_ERROR_OK;\n}\n\ninline int convertScale_32F8U(const uchar* src, size_t src_step, uchar* dst, size_t dst_step, int width, int height, double alpha, double beta)\n{\n int vlmax = __riscv_vsetvlmax_e32m8();\n auto vec_b = __riscv_vfmv_v_f_f32m8(beta, vlmax);\n float a = alpha;\n\n for (int i = 0; i < height; i++)\n {\n const float* src_row = reinterpret_cast(src + i * src_step);\n uchar* dst_row = dst + i * dst_step;\n int vl;\n for (int j = 0; j < width; j += vl)\n {\n vl = __riscv_vsetvl_e32m8(width - j);\n auto vec_src = __riscv_vle32_v_f32m8(src_row + j, vl);\n auto vec_fma = __riscv_vfmadd(vec_src, a, vec_b, vl);\n auto vec_dst_u16 = __riscv_vfncvt_xu(vec_fma, vl);\n auto vec_dst = __riscv_vnclipu(vec_dst_u16, 0, __RISCV_VXRM_RNU, vl);\n __riscv_vse8_v_u8m2(dst_row + j, vec_dst, vl);\n }\n }\n\n return CV_HAL_ERROR_OK;\n}\n\ninline int convertScale_32F32F(const uchar* src, size_t src_step, uchar* dst, size_t dst_step, int width, int height, double alpha, double beta)\n{\n int vlmax = __riscv_vsetvlmax_e32m8();\n auto vec_b = __riscv_vfmv_v_f_f32m8(beta, vlmax);\n float a = alpha;\n\n for (int i = 0; i < height; i++)\n {\n const float* src_row = reinterpret_cast(src + i * src_step);\n float* dst_row = reinterpret_cast(dst + i * dst_step);\n int vl;\n for (int j = 0; j < width; j += vl)\n {\n vl = __riscv_vsetvl_e32m8(width - j);\n auto vec_src = __riscv_vle32_v_f32m8(src_row + j, vl);\n auto vec_fma = __riscv_vfmadd(vec_src, a, vec_b, vl);\n __riscv_vse32_v_f32m8(dst_row + j, vec_fma, vl);\n }\n }\n\n return CV_HAL_ERROR_OK;\n}\n\ninline int convertScale_32F16S(const uchar* src, size_t src_step,\n uchar* dst, size_t dst_step,\n int width, int height,\n double alpha, double beta)\n{\n if (alpha == 1.0 && beta == 0.0)\n {\n for (int i = 0; i < height; i++)\n {\n const float* src_row =\n reinterpret_cast(src + i * src_step);\n\n short* dst_row =\n reinterpret_cast(dst + i * dst_step);\n\n int vl;\n\n for (int j = 0; j < width; j += vl)\n {\n vl = __riscv_vsetvl_e32m8(width - j);\n\n auto vec_src =\n __riscv_vle32_v_f32m8(src_row + j, vl);\n\n auto vec_dst =\n __riscv_vfncvt_x(vec_src, vl);\n\n __riscv_vse16_v_i16m4(\n dst_row + j, vec_dst, vl);\n }\n }\n\n return CV_HAL_ERROR_OK;\n }\n\n int vlmax = __riscv_vsetvlmax_e32m8();\n auto vec_b = __riscv_vfmv_v_f_f32m8(beta, vlmax);\n float a = alpha;\n\n for (int i = 0; i < height; i++)\n {\n const float* src_row =\n reinterpret_cast(src + i * src_step);\n\n short* dst_row =\n reinterpret_cast(dst + i * dst_step);\n\n int vl;\n\n for (int j = 0; j < width; j += vl)\n {\n vl = __riscv_vsetvl_e32m8(width - j);\n\n auto vec_src =\n __riscv_vle32_v_f32m8(src_row + j, vl);\n\n auto vec_fma =\n __riscv_vfmadd(vec_src, a, vec_b, vl);\n\n auto vec_dst =\n __riscv_vfncvt_x(vec_fma, vl);\n\n __riscv_vse16_v_i16m4(\n dst_row + j, vec_dst, vl);\n }\n }\n\n return CV_HAL_ERROR_OK;\n}\n\nint convertScale(const uchar* src, size_t src_step, uchar* dst, size_t dst_step,\n int width, int height, int sdepth, int ddepth, double alpha, double beta)\n{\n if (!dst)\n return CV_HAL_ERROR_OK;\n\n if ((unsigned)ddepth >= CV_DEPTH_MAX)\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n\n // Column-shaped sources can target row-shaped continuous vectors.\n if (width == 1 && height > 1 && dst_step != CV_ELEM_SIZE1(ddepth))\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n\n switch (sdepth)\n {\n case CV_8U:\n switch (ddepth)\n {\n case CV_8U:\n return convertScale_8U8U(src, src_step, dst, dst_step, width, height, alpha, beta);\n case CV_16U:\n return convertScale_8U16U(src, src_step, dst, dst_step, width, height, alpha, beta);\n case CV_16S:\n return convertScale_8U16S(src, src_step, dst, dst_step, width, height, alpha, beta);\n case CV_32F:\n return convertScale_8U32F(src, src_step, dst, dst_step, width, height, alpha, beta);\n }\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n case CV_16U:\n switch (ddepth)\n {\n case CV_8U:\n return convertScale_16U8U(src, src_step, dst, dst_step, width, height, alpha, beta);\n case CV_32F:\n return convertScale_16U32F(src, src_step, dst, dst_step, width, height, alpha, beta);\n }\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n case CV_16S:\n switch (ddepth)\n {\n case CV_32F:\n return convertScale_16S32F(src, src_step, dst, dst_step, width, height, alpha, beta);\n }\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n case CV_32F:\n switch (ddepth)\n {\n case CV_8U:\n return convertScale_32F8U(src, src_step, dst, dst_step, width, height, alpha, beta);\n case CV_16S:\n return convertScale_32F16S(src, src_step, dst, dst_step, width, height, alpha, beta);\n case CV_32F:\n return convertScale_32F32F(src, src_step, dst, dst_step, width, height, alpha, beta);\n }\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n }\n\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n}\n\n#endif // CV_HAL_RVV_1P0_ENABLED\n\n}}} // cv::rvv_hal::core\n", "source": "opencv", "added": "2026-11-08", "created": "", "token_count": 4598, "license": "Apache-2.0", "author": "opencv contributors"}
{"id": "github:opencv:hal/riscv-rvv/src/core/lu.cpp", "text": "// This file is part of OpenCV project.\n// It is subject to the license terms in the LICENSE file found in the top-level directory\n// of this distribution and at http://opencv.org/license.html.\n\n// Copyright (C) 2025, Institute of Software, Chinese Academy of Sciences.\n\n#include \"rvv_hal.hpp\"\n#include \n#include \n#include \n\nnamespace cv { namespace rvv_hal { namespace core {\n\n#if CV_HAL_RVV_1P0_ENABLED\n\nnamespace {\n\n// the algorithm is copied from core/src/matrix_decomp.cpp,\n// in the function template static int cv::LUImpl\ntemplate\ninline int LU(T* src1, size_t src1_step, int m, T* src2, size_t src2_step, int n, int* info)\n{\n T eps;\n if( typeid(T) == typeid(float) )\n eps = FLT_EPSILON*10;\n else if( typeid(T) == typeid(double) )\n eps = DBL_EPSILON*100;\n else\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n\n int i, j, k, p = 1;\n src1_step /= sizeof(src1[0]);\n src2_step /= sizeof(src2[0]);\n\n int vlmax = RVV_T::setvlmax(), vl;\n if( src2 )\n {\n for( i = 0; i < m; i++ )\n {\n k = i;\n\n for( j = i+1; j < m; j++ )\n if( std::abs(src1[j*src1_step + i]) > std::abs(src1[k*src1_step + i]) )\n k = j;\n\n if( std::abs(src1[k*src1_step + i]) < eps )\n {\n *info = 0;\n return CV_HAL_ERROR_OK;\n }\n\n if( k != i )\n {\n for( j = i; j < m; j += vl )\n {\n vl = RVV_T::setvl(m - j);\n auto vec_src1 = RVV_T::vload(src1 + i * src1_step + j, vl);\n auto vec_src2 = RVV_T::vload(src1 + k * src1_step + j, vl);\n RVV_T::vstore(src1 + k * src1_step + j, vec_src1, vl);\n RVV_T::vstore(src1 + i * src1_step + j, vec_src2, vl);\n }\n for( j = 0; j < n; j += vl )\n {\n vl = RVV_T::setvl(n - j);\n auto vec_src1 = RVV_T::vload(src2 + i * src2_step + j, vl);\n auto vec_src2 = RVV_T::vload(src2 + k * src2_step + j, vl);\n RVV_T::vstore(src2 + k * src2_step + j, vec_src1, vl);\n RVV_T::vstore(src2 + i * src2_step + j, vec_src2, vl);\n }\n p = -p;\n }\n\n T d = -1/src1[i*src1_step + i];\n\n for( j = i+1; j < m; j++ )\n {\n T alpha = src1[j*src1_step + i]*d;\n\n for( k = i+1; k < m; k += vl )\n {\n vl = RVV_T::setvl(m - k);\n auto vec_src = RVV_T::vload(src1 + i * src1_step + k, vl);\n auto vec_dst = RVV_T::vload(src1 + j * src1_step + k, vl);\n vec_dst = __riscv_vfmacc(vec_dst, alpha, vec_src, vl);\n RVV_T::vstore(src1 + j * src1_step + k, vec_dst, vl);\n }\n for( k = 0; k < n; k += vl )\n {\n vl = RVV_T::setvl(n - k);\n auto vec_src = RVV_T::vload(src2 + i * src2_step + k, vl);\n auto vec_dst = RVV_T::vload(src2 + j * src2_step + k, vl);\n vec_dst = __riscv_vfmacc(vec_dst, alpha, vec_src, vl);\n RVV_T::vstore(src2 + j * src2_step + k, vec_dst, vl);\n }\n }\n }\n\n for( i = m-1; i >= 0; i-- )\n for( j = 0; j < n; j++ )\n {\n T s = src2[i*src2_step + j];\n auto vec_sum = RVV_T::vmv(0, vlmax);\n for( k = i+1; k < m; k += vl )\n {\n vl = RVV_T::setvl(m - k);\n auto vec_src1 = RVV_T::vload(src1 + i * src1_step + k, vl);\n auto vec_src2 = RVV_T::vload_stride(src2 + k * src2_step + j, sizeof(T) * src2_step, vl);\n vec_sum = __riscv_vfmacc_tu(vec_sum, vec_src1, vec_src2, vl);\n }\n s -= __riscv_vfmv_f(__riscv_vfredosum(vec_sum, RVV_BaseType::vmv_s(0, vlmax), vlmax));\n src2[i*src2_step + j] = s/src1[i*src1_step + i];\n }\n }\n else\n {\n for( i = 0; i < m; i++ )\n {\n k = i;\n\n for( j = i+1; j < m; j++ )\n if( std::abs(src1[j*src1_step + i]) > std::abs(src1[k*src1_step + i]) )\n k = j;\n\n if( std::abs(src1[k*src1_step + i]) < eps )\n {\n *info = 0;\n return CV_HAL_ERROR_OK;\n }\n\n if( k != i )\n {\n for( j = i; j < m; j += vl )\n {\n vl = RVV_T::setvl(m - j);\n auto vec_src1 = RVV_T::vload(src1 + i * src1_step + j, vl);\n auto vec_src2 = RVV_T::vload(src1 + k * src1_step + j, vl);\n RVV_T::vstore(src1 + k * src1_step + j, vec_src1, vl);\n RVV_T::vstore(src1 + i * src1_step + j, vec_src2, vl);\n }\n p = -p;\n }\n\n T d = -1/src1[i*src1_step + i];\n\n for( j = i+1; j < m; j++ )\n {\n T alpha = src1[j*src1_step + i]*d;\n\n for( k = i+1; k < m; k += vl )\n {\n vl = RVV_T::setvl(m - k);\n auto vec_src = RVV_T::vload(src1 + i * src1_step + k, vl);\n auto vec_dst = RVV_T::vload(src1 + j * src1_step + k, vl);\n vec_dst = __riscv_vfmacc(vec_dst, alpha, vec_src, vl);\n RVV_T::vstore(src1 + j * src1_step + k, vec_dst, vl);\n }\n }\n }\n }\n\n *info = p;\n return CV_HAL_ERROR_OK;\n}\n\n} // anonymous\n\nint LU32f(float* src1, size_t src1_step, int m, float* src2, size_t src2_step, int n, int* info) {\n return LU(src1, src1_step, m, src2, src2_step, n, info);\n}\nint LU64f(double* src1, size_t src1_step, int m, double* src2, size_t src2_step, int n, int* info) {\n return LU(src1, src1_step, m, src2, src2_step, n, info);\n}\n\n#endif // CV_HAL_RVV_1P0_ENABLED\n\n}}} // cv::rvv_hal::core\n", "source": "opencv", "added": "2026-11-08", "created": "", "token_count": 1868, "license": "Apache-2.0", "author": "opencv contributors"}
{"id": "github:opencv:hal/riscv-rvv/src/imgproc/scharr.cpp", "text": "// This file is part of OpenCV project.\n// It is subject to the license terms in the LICENSE file found in the top-level directory\n// of this distribution and at http://opencv.org/license.html .\n\n// Copyright (C) 2025, SpaceMIT Inc., all rights reserved.\n\n#include \"rvv_hal.hpp\"\n#include \"common.hpp\"\n\nnamespace cv\n{\n namespace rvv_hal\n {\n namespace imgproc\n {\n\n#if CV_HAL_RVV_1P0_ENABLED\n\n#define borderValue 0\n\n static inline int scharr_dx0(int start, int end, const uint8_t *src_data, size_t src_step,\n uint8_t *dst_data, size_t dst_step,\n int width, int height,\n int src_depth __attribute__((unused)), int dst_depth, int cn __attribute__((unused)),\n int margin_left __attribute__((unused)), int margin_top __attribute__((unused)),\n int margin_right __attribute__((unused)), int margin_bottom __attribute__((unused)),\n double scale __attribute__((unused)), double delta __attribute__((unused)),\n int border_type)\n {\n int dx0, dx1, dx2, dy0, dy1, dy2;\n\n dy0 = -1;\n dx0 = 3;\n\n dy1 = 0;\n dx1 = 10;\n\n dy2 = 1;\n dx2 = 3;\n\n int16_t trow[width];\n\n static thread_local std::vector zero_row;\n if (zero_row.size() < static_cast(width))\n {\n zero_row.clear();\n zero_row.resize(width, 0);\n }\n\n if (dst_depth == CV_8U)\n {\n for (int y = start; y < end; ++y)\n {\n const uint8_t *srow1 = src_data + y * src_step;\n const uint8_t *srow0;\n const uint8_t *srow2;\n\n if (y != 0)\n {\n srow0 = src_data + (y - 1) * src_step;\n }\n else\n {\n if (border_type == BORDER_REPLICATE)\n {\n srow0 = srow1;\n }\n else\n {\n srow0 = zero_row.data();\n }\n }\n\n if (y != height - 1)\n {\n srow2 = src_data + (y + 1) * src_step;\n }\n else\n {\n if (border_type == BORDER_REPLICATE)\n {\n srow2 = srow1;\n }\n else\n {\n srow2 = zero_row.data();\n }\n }\n\n trow[0] = (dy0 * srow0[0] + dy1 * srow1[0] + dy2 * srow2[0]);\n\n // Last pixel\n\n trow[width - 1] = dy0 * srow0[width - 1] + dy1 * srow1[width - 1] + dy2 * srow2[width - 1];\n\n size_t vl = 0;\n\n // Vector processing\n\n for (int x = 1; x < width - 1; x += vl)\n {\n vl = __riscv_vsetvl_e8m4(width - x - 1);\n\n vint16m8_t vsrow0 = __riscv_vreinterpret_v_u16m8_i16m8(__riscv_vwcvtu_x_x_v_u16m8(__riscv_vle8_v_u8m4(srow0 + x, vl), vl));\n vint16m8_t vsrow2 = __riscv_vreinterpret_v_u16m8_i16m8(__riscv_vwcvtu_x_x_v_u16m8(__riscv_vle8_v_u8m4(srow2 + x, vl), vl));\n\n vint16m8_t vrowx = __riscv_vsub_vv_i16m8(vsrow2, vsrow0, vl);\n\n __riscv_vse16_v_i16m8(trow + x, vrowx, vl);\n }\n\n int x = 0;\n\n uint8_t *drow = (uint8_t *)(dst_data + y * dst_step);\n\n int16_t temp = trow[0] * dx1 + trow[1] * dx2;\n\n if (border_type == BORDER_REPLICATE)\n {\n temp += trow[0] * dx0;\n }\n\n drow[x] = (uint8_t)(temp > 0 ? (temp < 255 ? temp : 255) : 0);\n\n x = 1;\n for (; x < width - 1; x += vl)\n {\n vl = __riscv_vsetvl_e16m8(width - x - 1);\n vint16m8_t vleft = __riscv_vle16_v_i16m8(trow + x - 1, vl);\n vint16m8_t vcenter = __riscv_vle16_v_i16m8(trow + x, vl);\n vint16m8_t vright = __riscv_vle16_v_i16m8(trow + x + 1, vl);\n\n vint16m8_t vres = __riscv_vmul_vx_i16m8(vcenter, dx1, vl);\n vcenter = __riscv_vadd_vv_i16m8(vleft, vright, vl);\n vres = __riscv_vmacc_vx_i16m8(vres, dx0, vcenter, vl);\n\n vres = __riscv_vmax_vx_i16m8(vres, 0, vl);\n vres = __riscv_vmin_vx_i16m8(vres, 255, vl);\n\n __riscv_vse8_v_u8m4(drow + x, __riscv_vncvt_x_x_w_u8m4(__riscv_vreinterpret_v_i16m8_u16m8(vres), vl), vl);\n }\n\n x = width - 1;\n\n temp = trow[width - 2] * dx0 + trow[width - 1] * dx1;\n\n if (border_type == BORDER_REPLICATE)\n {\n temp += trow[width - 1] * dx2;\n }\n\n drow[x] = (uint8_t)(temp > 0 ? (temp < 255 ? temp : 255) : 0);\n }\n }\n\n else if (dst_depth == CV_16S)\n {\n\n for (int y = start; y < end; ++y)\n {\n const uint8_t *srow1 = src_data + y * src_step;\n const uint8_t *srow0;\n const uint8_t *srow2;\n\n if (y != 0)\n {\n srow0 = src_data + (y - 1) * src_step;\n }\n else\n {\n if (border_type == BORDER_REPLICATE)\n {\n srow0 = srow1;\n }\n else\n {\n srow0 = zero_row.data();\n }\n }\n\n if (y != height - 1)\n {\n srow2 = src_data + (y + 1) * src_step;\n }\n else\n {\n if (border_type == BORDER_REPLICATE)\n {\n srow2 = srow1;\n }\n else\n {\n srow2 = zero_row.data();\n }\n }\n\n if (y == 0)\n {\n if (border_type == BORDER_REPLICATE)\n {\n srow0 = srow1;\n }\n else\n {\n srow0 = zero_row.data();\n }\n }\n else if (y == height - 1)\n {\n if (border_type == BORDER_REPLICATE)\n {\n srow2 = srow1;\n }\n else\n {\n srow2 = zero_row.data();\n }\n }\n\n size_t vl = 0;\n\n // Vector processing\n\n for (int x = 0; x < width; x += vl)\n {\n vl = __riscv_vsetvl_e8m4(width - x);\n\n vint16m8_t vsrow0 = __riscv_vreinterpret_v_u16m8_i16m8(__riscv_vwcvtu_x_x_v_u16m8(__riscv_vle8_v_u8m4(srow0 + x, vl), vl));\n vint16m8_t vsrow2 = __riscv_vreinterpret_v_u16m8_i16m8(__riscv_vwcvtu_x_x_v_u16m8(__riscv_vle8_v_u8m4(srow2 + x, vl), vl));\n\n vint16m8_t vrowx = __riscv_vsub_vv_i16m8(vsrow2, vsrow0, vl);\n\n __riscv_vse16_v_i16m8(trow + x, vrowx, vl);\n }\n\n int x = 0;\n\n int16_t *drow = (int16_t *)(dst_data + y * dst_step);\n\n drow[0] = trow[0] * dx1 + trow[1] * dx2;\n\n if (border_type == BORDER_REPLICATE)\n {\n drow[x] += trow[0] * dx0;\n }\n\n x = 1;\n for (; x < width - 1; x += vl)\n {\n vl = __riscv_vsetvl_e16m8(width - x - 1);\n vint16m8_t vleft = __riscv_vle16_v_i16m8(trow + x - 1, vl);\n vint16m8_t vcenter = __riscv_vle16_v_i16m8(trow + x, vl);\n vint16m8_t vright = __riscv_vle16_v_i16m8(trow + x + 1, vl);\n\n vint16m8_t vres = __riscv_vmul_vx_i16m8(vcenter, dx1, vl);\n vcenter = __riscv_vadd_vv_i16m8(vleft, vright, vl);\n vres = __riscv_vmacc_vx_i16m8(vres, dx0, vcenter, vl);\n\n __riscv_vse16_v_i16m8(drow + x, vres, vl);\n }\n\n x = width - 1;\n\n drow[x] = trow[width - 2] * dx0 + trow[width - 1] * dx1;\n\n if (border_type == BORDER_REPLICATE)\n {\n drow[x] += trow[width - 1] * dx2;\n }\n }\n }\n\n else if (dst_depth == CV_32F)\n {\n for (int y = start; y < end; ++y)\n {\n const uint8_t *srow1 = src_data + y * src_step;\n const uint8_t *srow0;\n const uint8_t *srow2;\n\n if (y != 0)\n {\n srow0 = src_data + (y - 1) * src_step;\n }\n else\n {\n if (border_type == BORDER_REPLICATE)\n {\n srow0 = srow1;\n }\n else\n {\n srow0 = zero_row.data();\n }\n }\n\n if (y != height - 1)\n {\n srow2 = src_data + (y + 1) * src_step;\n }\n else\n {\n if (border_type == BORDER_REPLICATE)\n {\n srow2 = srow1;\n }\n else\n {\n srow2 = zero_row.data();\n }\n }\n\n if (y == 0)\n {\n if (border_type == BORDER_REPLICATE)\n {\n srow0 = srow1;\n }\n else\n {\n srow0 = zero_row.data();\n }\n }\n else if (y == height - 1)\n {\n if (border_type == BORDER_REPLICATE)\n {\n srow2 = srow1;\n }\n else\n {\n srow2 = zero_row.data();\n }\n }\n\n size_t vl = 0;\n\n // Vector processing\n for (int x = 0; x < width; x += vl)\n {\n vl = __riscv_vsetvl_e8m4(width - x);\n\n vint16m8_t vsrow0 = __riscv_vreinterpret_v_u16m8_i16m8(__riscv_vwcvtu_x_x_v_u16m8(__riscv_vle8_v_u8m4(srow0 + x, vl), vl));\n vint16m8_t vsrow2 = __riscv_vreinterpret_v_u16m8_i16m8(__riscv_vwcvtu_x_x_v_u16m8(__riscv_vle8_v_u8m4(srow2 + x, vl), vl));\n\n vint16m8_t vrowx = __riscv_vsub_vv_i16m8(vsrow2, vsrow0, vl);\n\n __riscv_vse16_v_i16m8(trow + x, vrowx, vl);\n }\n\n int x = 0;\n\n float *drow = (float *)(dst_data + y * dst_step);\n\n drow[x] = trow[0] * dx1 + trow[1] * dx2;\n\n if (border_type == BORDER_REPLICATE)\n {\n drow[x] += trow[0] * dx0;\n }\n\n x = 1;\n\n for (; x < width - 1; x += vl)\n {\n vl = __riscv_vsetvl_e16m4(width - x - 1);\n vint16m4_t vleft = __riscv_vle16_v_i16m4(trow + x - 1, vl);\n vint16m4_t vcenter = __riscv_vle16_v_i16m4(trow + x, vl);\n vint16m4_t vright = __riscv_vle16_v_i16m4(trow + x + 1, vl);\n\n vint16m4_t vres = __riscv_vmul_vx_i16m4(vcenter, dx1, vl);\n vcenter = __riscv_vadd_vv_i16m4(vleft, vright, vl);\n vres = __riscv_vmacc_vx_i16m4(vres, dx0, vcenter, vl);\n\n __riscv_vse32_v_f32m8(drow + x, __riscv_vfwcvt_f_x_v_f32m8(vres, vl), vl);\n }\n\n x = width - 1;\n\n drow[x] = trow[width - 2] * dx0 + trow[width - 1] * dx1;\n\n if (border_type == BORDER_REPLICATE)\n {\n drow[x] += trow[width - 1] * dx2;\n }\n }\n }\n return CV_HAL_ERROR_OK;\n }\n\n static inline int scharr_dx1(int start, int end, const uint8_t *src_data, size_t src_step,\n uint8_t *dst_data, size_t dst_step,\n int width, int height,\n int src_depth __attribute__((unused)), int dst_depth, int cn __attribute__((unused)),\n int margin_left __attribute__((unused)), int margin_top __attribute__((unused)),\n int margin_right __attribute__((unused)), int margin_bottom __attribute__((unused)),\n double scale __attribute__((unused)), double delta __attribute__((unused)),\n int border_type)\n {\n int dx0, dx1, dx2, dy0, dy1, dy2;\n dx0 = -1;\n dy0 = 3;\n\n dx1 = 0;\n dy1 = 10;\n\n dx2 = 1;\n dy2 = 3;\n\n int16_t trow[width];\n\n static thread_local std::vector zero_row;\n if (zero_row.size() < static_cast(width))\n {\n zero_row.clear();\n zero_row.resize(width, 0);\n }\n\n if (dst_depth == CV_8U)\n {\n for (int y = start; y < end; ++y)\n {\n const uint8_t *srow1 = src_data + y * src_step;\n const uint8_t *srow0;\n const uint8_t *srow2;\n\n if (y != 0)\n {\n srow0 = src_data + (y - 1) * src_step;\n }\n else\n {\n if (border_type == BORDER_REPLICATE)\n {\n srow0 = srow1;\n }\n else\n {\n srow0 = zero_row.data();\n }\n }\n\n if (y != height - 1)\n {\n srow2 = src_data + (y + 1) * src_step;\n }\n else\n {\n if (border_type == BORDER_REPLICATE)\n {\n srow2 = srow1;\n }\n else\n {\n srow2 = zero_row.data();\n }\n }\n\n if (y == 0)\n {\n if (border_type == BORDER_REPLICATE)\n {\n srow0 = srow1;\n }\n else\n {\n srow0 = zero_row.data();\n }\n }\n else if (y == height - 1)\n {\n if (border_type == BORDER_REPLICATE)\n {\n srow2 = srow1;\n }\n else\n {\n srow2 = zero_row.data();\n }\n }\n\n trow[0] = (dy0 * srow0[0] + dy1 * srow1[0] + dy2 * srow2[0]);\n\n // Last pixel\n\n trow[width - 1] = dy0 * srow0[width - 1] + dy1 * srow1[width - 1] + dy2 * srow2[width - 1];\n\n size_t vl = 0;\n\n // Vector processing\n\n for (int x = 1; x < width - 1; x += vl)\n {\n vl = __riscv_vsetvl_e8m4(width - x - 1);\n\n vuint8m4_t vsrow0 = __riscv_vle8_v_u8m4(srow0 + x, vl);\n vuint8m4_t vsrow1 = __riscv_vle8_v_u8m4(srow1 + x, vl);\n vuint8m4_t vsrow2 = __riscv_vle8_v_u8m4(srow2 + x, vl);\n\n vuint16m8_t vrowx = __riscv_vwmulu_vx_u16m8(vsrow1, dy1, vl);\n vuint16m8_t vtemp = __riscv_vwaddu_vv_u16m8(vsrow0, vsrow2, vl);\n vrowx = __riscv_vmacc_vx_u16m8(vrowx, dy0, vtemp, vl);\n\n __riscv_vse16_v_i16m8(trow + x, __riscv_vreinterpret_v_u16m8_i16m8(vrowx), vl);\n }\n\n int x = 0;\n\n uint8_t *drow = (uint8_t *)(dst_data + y * dst_step);\n\n int16_t temp = trow[0] * dx1 + trow[1] * dx2;\n\n if (border_type == BORDER_REPLICATE)\n {\n temp += trow[0] * dx0;\n }\n\n drow[x] = (uint8_t)(temp > 0 ? (temp < 255 ? temp : 255) : 0);\n\n x = 1;\n\n for (; x < width - 1; x += vl)\n {\n vl = __riscv_vsetvl_e16m8(width - x - 1);\n vint16m8_t vleft = __riscv_vle16_v_i16m8(trow + x - 1, vl);\n\n vint16m8_t vright = __riscv_vle16_v_i16m8(trow + x + 1, vl);\n vint16m8_t vres = __riscv_vsub_vv_i16m8(vright, vleft, vl);\n\n vres = __riscv_vmax_vx_i16m8(vres, 0, vl);\n vres = __riscv_vmin_vx_i16m8(vres, 255, vl);\n\n __riscv_vse8_v_u8m4(drow + x, __riscv_vncvt_x_x_w_u8m4(__riscv_vreinterpret_v_i16m8_u16m8(vres), vl), vl);\n }\n\n x = width - 1;\n\n temp = trow[width - 2] * dx0 + trow[width - 1] * dx1;\n\n if (border_type == BORDER_REPLICATE)\n {\n temp += trow[width - 1] * dx2;\n }\n\n drow[x] = (uint8_t)(temp > 0 ? (temp < 255 ? temp : 255) : 0);\n }\n }\n\n else if (dst_depth == CV_16S)\n {\n for (int y = start; y < end; ++y)\n {\n const uint8_t *srow1 = src_data + y * src_step;\n const uint8_t *srow0;\n const uint8_t *srow2;\n\n if (y != 0)\n {\n srow0 = src_data + (y - 1) * src_step;\n }\n else\n {\n if (border_type == BORDER_REPLICATE)\n {\n srow0 = srow1;\n }\n else\n {\n srow0 = zero_row.data();\n }\n }\n\n if (y != height - 1)\n {\n srow2 = src_data + (y + 1) * src_step;\n }\n else\n {\n if (border_type == BORDER_REPLICATE)\n {\n srow2 = srow1;\n }\n else\n {\n srow2 = zero_row.data();\n }\n }\n\n if (y == 0)\n {\n if (border_type == BORDER_REPLICATE)\n {\n srow0 = srow1;\n }\n else\n {\n srow0 = zero_row.data();\n }\n }\n else if (y == height - 1)\n {\n if (border_type == BORDER_REPLICATE)\n {\n srow2 = srow1;\n }\n else\n {\n srow2 = zero_row.data();\n }\n }\n\n size_t vl = 0;\n\n // Vector processing\n\n for (int x = 0; x < width; x += vl)\n {\n vl = __riscv_vsetvl_e8m4(width - x);\n\n vuint8m4_t vsrow0 = __riscv_vle8_v_u8m4(srow0 + x, vl);\n vuint8m4_t vsrow1 = __riscv_vle8_v_u8m4(srow1 + x, vl);\n vuint8m4_t vsrow2 = __riscv_vle8_v_u8m4(srow2 + x, vl);\n\n vuint16m8_t vrowx = __riscv_vwmulu_vx_u16m8(vsrow1, dy1, vl);\n vuint16m8_t vtemp = __riscv_vwaddu_vv_u16m8(vsrow0, vsrow2, vl);\n vrowx = __riscv_vmacc_vx_u16m8(vrowx, dy0, vtemp, vl);\n\n __riscv_vse16_v_i16m8(trow + x, __riscv_vreinterpret_v_u16m8_i16m8(vrowx), vl);\n }\n\n int x = 0;\n\n int16_t *drow = (int16_t *)(dst_data + y * dst_step);\n\n drow[x] = trow[0] * dx1 + trow[1] * dx2;\n\n if (border_type == BORDER_REPLICATE)\n {\n drow[x] += trow[0] * dx0;\n }\n\n x = 1;\n for (; x < width - 1; x += vl)\n {\n vl = __riscv_vsetvl_e16m8(width - x - 1);\n vint16m8_t vleft = __riscv_vle16_v_i16m8(trow + x - 1, vl);\n\n vint16m8_t vright = __riscv_vle16_v_i16m8(trow + x + 1, vl);\n vint16m8_t vres = __riscv_vsub_vv_i16m8(vright, vleft, vl);\n\n __riscv_vse16_v_i16m8(drow + x, vres, vl);\n }\n\n x = width - 1;\n\n drow[x] = trow[width - 2] * dx0 + trow[width - 1] * dx1;\n\n if (border_type == BORDER_REPLICATE)\n {\n drow[x] += trow[width - 1] * dx2;\n }\n }\n }\n\n else if (dst_depth == CV_32F)\n {\n for (int y = start; y < end; ++y)\n {\n const uint8_t *srow1 = src_data + y * src_step;\n const uint8_t *srow0;\n const uint8_t *srow2;\n\n if (y != 0)\n {\n srow0 = src_data + (y - 1) * src_step;\n }\n else\n {\n if (border_type == BORDER_REPLICATE)\n {\n srow0 = srow1;\n }\n else\n {\n srow0 = zero_row.data();\n }\n }\n\n if (y != height - 1)\n {\n srow2 = src_data + (y + 1) * src_step;\n }\n else\n {\n if (border_type == BORDER_REPLICATE)\n {\n srow2 = srow1;\n }\n else\n {\n srow2 = zero_row.data();\n }\n }\n\n if (y == 0)\n {\n if (border_type == BORDER_REPLICATE)\n {\n srow0 = srow1;\n }\n else\n {\n srow0 = zero_row.data();\n }\n }\n else if (y == height - 1)\n {\n if (border_type == BORDER_REPLICATE)\n {\n srow2 = srow1;\n }\n else\n {\n srow2 = zero_row.data();\n }\n }\n\n size_t vl = 0;\n\n // Vector processing\n for (int x = 0; x < width; x += vl)\n {\n vl = __riscv_vsetvl_e8m4(width - x);\n\n vuint8m4_t vsrow0 = __riscv_vle8_v_u8m4(srow0 + x, vl);\n vuint8m4_t vsrow1 = __riscv_vle8_v_u8m4(srow1 + x, vl);\n vuint8m4_t vsrow2 = __riscv_vle8_v_u8m4(srow2 + x, vl);\n\n vuint16m8_t vrowx = __riscv_vwmulu_vx_u16m8(vsrow1, dy1, vl);\n vuint16m8_t vtemp = __riscv_vwaddu_vv_u16m8(vsrow0, vsrow2, vl);\n vrowx = __riscv_vmacc_vx_u16m8(vrowx, dy0, vtemp, vl);\n\n __riscv_vse16_v_i16m8(trow + x, __riscv_vreinterpret_v_u16m8_i16m8(vrowx), vl);\n }\n\n int x = 0;\n\n float *drow = (float *)(dst_data + y * dst_step);\n\n drow[x] = trow[0] * dx1 + trow[1] * dx2;\n\n if (border_type == BORDER_REPLICATE)\n {\n drow[x] += trow[0] * dx0;\n }\n\n x = 1;\n\n for (; x < width - 1; x += vl)\n {\n vl = __riscv_vsetvl_e16m4(width - x - 1);\n vint16m4_t vleft = __riscv_vle16_v_i16m4(trow + x - 1, vl);\n\n vint16m4_t vright = __riscv_vle16_v_i16m4(trow + x + 1, vl);\n vint16m4_t vres = __riscv_vsub_vv_i16m4(vright, vleft, vl);\n\n __riscv_vse32_v_f32m8(drow + x, __riscv_vfwcvt_f_x_v_f32m8(vres, vl), vl);\n }\n\n x = width - 1;\n\n drow[x] = trow[width - 2] * dx0 + trow[width - 1] * dx1;\n\n if (border_type == BORDER_REPLICATE)\n {\n drow[x] += trow[width - 1] * dx2;\n }\n }\n }\n\n return CV_HAL_ERROR_OK;\n }\n\n class ScharrInvoker : public ParallelLoopBody\n {\n public:\n explicit ScharrInvoker(std::function _func)\n : func(std::move(_func)) {}\n\n void operator()(const Range &range) const override\n {\n func(range.start, range.end);\n }\n\n private:\n std::function func;\n };\n\n template \n inline int invoke(int height,\n int (*f)(int, int, Args...),\n Args... args)\n {\n using namespace std::placeholders;\n auto bound = std::bind(f, _1, _2, std::forward(args)...);\n cv::parallel_for_(Range(1, height), ScharrInvoker(bound), cv::getNumThreads());\n return f(0, 1, std::forward(args)...);\n }\n\n int scharr(const uint8_t *src_data, size_t src_step,\n uint8_t *dst_data, size_t dst_step,\n int width, int height,\n int src_depth, int dst_depth, int cn,\n int margin_left, int margin_top,\n int margin_right, int margin_bottom,\n int dx, int dy __attribute__((unused)),\n double scale, double delta,\n int border_type)\n {\n if (src_depth != CV_8U ||\n (dst_depth != CV_8U && dst_depth != CV_16S && dst_depth != CV_32F) ||\n cn != 1 || width < 3)\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n\n if (scale != 1 || delta != 0)\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n\n if (border_type != BORDER_REPLICATE && border_type != BORDER_CONSTANT)\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n\n if (margin_left != 0 || margin_top != 0 || margin_right != 0 || margin_bottom != 0)\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n\n // This is copied from opencv/modules/imgproc/src/deriv.cpp\n // if (!(dx >= 0 && dy >= 0 && dx + dy == 1))\n // {\n // return CV_HAL_ERROR_NOT_IMPLEMENTED;\n // }\n\n int size = 1;\n if (dst_depth == CV_16S)\n {\n size = 2;\n }\n else if (dst_depth == CV_32F)\n {\n size = 4;\n }\n\n std::vector temp_buffer;\n uint8_t *actual_dst_data = dst_data;\n if (src_data == dst_data)\n {\n temp_buffer.resize(height * dst_step);\n actual_dst_data = temp_buffer.data();\n }\n\n int res = invoke(height,\n dx == 1 ? &scharr_dx1 : &scharr_dx0,\n src_data, src_step,\n actual_dst_data, dst_step,\n width, height,\n src_depth, dst_depth, cn,\n margin_left, margin_top,\n margin_right, margin_bottom,\n scale, delta,\n border_type);\n if (src_data == dst_data && res == CV_HAL_ERROR_OK)\n {\n for (int y = 0; y < height; ++y)\n {\n memcpy(dst_data + y * dst_step,\n actual_dst_data + y * dst_step,\n width * size);\n }\n }\n\n return res;\n }\n#endif // CV_HAL_RVV_1P0_ENABLED\n }\n }\n} // cv::rvv_hal::imgproc\n", "source": "opencv", "added": "2026-11-08", "created": "", "token_count": 7395, "license": "Apache-2.0", "author": "opencv contributors"}
{"id": "github:opencv:hal/riscv-rvv/src/imgproc/threshold.cpp", "text": "// This file is part of OpenCV project.\n// It is subject to the license terms in the LICENSE file found in the top-level directory\n// of this distribution and at http://opencv.org/license.html.\n\n// Copyright (C) 2025, Institute of Software, Chinese Academy of Sciences.\n\n#include \"rvv_hal.hpp\"\n#include \"common.hpp\"\n#include \n\nnamespace cv { namespace rvv_hal { namespace imgproc {\n\n#if CV_HAL_RVV_1P0_ENABLED\n\nnamespace {\n\nclass ThresholdInvoker : public ParallelLoopBody\n{\npublic:\n template\n ThresholdInvoker(std::function _func, Args&&... args)\n {\n func = std::bind(_func, std::placeholders::_1, std::placeholders::_2, std::forward(args)...);\n }\n\n virtual void operator()(const Range& range) const override\n {\n func(range.start, range.end);\n }\n\nprivate:\n std::function func;\n};\n\ntemplate\nstatic inline int invoke(int width, int height, std::function func, Args&&... args)\n{\n cv::parallel_for_(Range(1, height), ThresholdInvoker(func, std::forward(args)...), static_cast((width - 1) * height) / (1 << 15));\n return func(0, 1, std::forward(args)...);\n}\n\ntemplate struct rvv;\ntemplate<> struct rvv\n{\n static inline vuint8m4_t vmerge(vuint8m4_t a, uchar b, vbool2_t c, size_t d) { return __riscv_vmerge(a, b, c, d); }\n};\ntemplate<> struct rvv\n{\n static inline vint16m4_t vmerge(vint16m4_t a, short b, vbool4_t c, size_t d) { return __riscv_vmerge(a, b, c, d); }\n};\ntemplate<> struct rvv\n{\n static inline vfloat32m4_t vmerge(vfloat32m4_t a, float b, vbool8_t c, size_t d) { return __riscv_vfmerge(a, b, c, d); }\n};\ntemplate<> struct rvv\n{\n static inline vfloat64m4_t vmerge(vfloat64m4_t a, double b, vbool16_t c, size_t d) { return __riscv_vfmerge(a, b, c, d); }\n};\n\n// the algorithm is copied from imgproc/src/thresh.cpp,\n// in the functor ThresholdRunner\ntemplate\nstatic inline int threshold(int start, int end, const uchar* src_data, size_t src_step, uchar* dst_data, size_t dst_step, int width, T tval, T mval)\n{\n auto zero = helper::vmv(0, helper::setvlmax());\n for (int i = start; i < end; i++)\n {\n const T* src = reinterpret_cast(src_data + i * src_step);\n T* dst = reinterpret_cast(dst_data + i * dst_step);\n int vl0, vl1;\n for (int j = 0; j < width; j += vl0 + vl1)\n {\n vl0 = helper::setvl(width - j);\n vl1 = helper::setvl(width - j - vl0);\n auto src0 = helper::vload(src + j, vl0);\n auto src1 = helper::vload(src + j + vl0, vl1);\n\n typename helper::VecType dst0, dst1;\n switch (type)\n {\n case CV_HAL_THRESH_BINARY:\n dst0 = rvv::vmerge(zero, mval, helper::vmgt(src0, tval, vl0), vl0);\n dst1 = rvv::vmerge(zero, mval, helper::vmgt(src1, tval, vl1), vl1);\n break;\n case CV_HAL_THRESH_BINARY_INV:\n dst0 = rvv::vmerge(zero, mval, helper::vmle(src0, tval, vl0), vl0);\n dst1 = rvv::vmerge(zero, mval, helper::vmle(src1, tval, vl1), vl1);\n break;\n case CV_HAL_THRESH_TRUNC:\n dst0 = rvv::vmerge(src0, tval, helper::vmgt(src0, tval, vl0), vl0);\n dst1 = rvv::vmerge(src1, tval, helper::vmgt(src1, tval, vl1), vl1);\n break;\n case CV_HAL_THRESH_TOZERO:\n dst0 = rvv::vmerge(src0, 0, helper::vmle(src0, tval, vl0), vl0);\n dst1 = rvv::vmerge(src1, 0, helper::vmle(src1, tval, vl1), vl1);\n break;\n case CV_HAL_THRESH_TOZERO_INV:\n dst0 = rvv::vmerge(src0, 0, helper::vmgt(src0, tval, vl0), vl0);\n dst1 = rvv::vmerge(src1, 0, helper::vmgt(src1, tval, vl1), vl1);\n break;\n }\n helper::vstore(dst + j, dst0, vl0);\n helper::vstore(dst + j + vl0, dst1, vl1);\n }\n }\n\n return CV_HAL_ERROR_OK;\n}\n\nstatic inline int threshold_range(int start, int end, const uchar* src_data, size_t src_step, uchar* dst_data, size_t dst_step, int width, int depth, int cn, double thresh, double maxValue, int thresholdType)\n{\n auto saturate_8u = [](double x){ return static_cast(std::min(std::max(x, static_cast(std::numeric_limits::lowest())), static_cast(std::numeric_limits::max()))); };\n auto saturate_16s = [](double x){ return static_cast(std::min(std::max(x, static_cast(std::numeric_limits::lowest())), static_cast(std::numeric_limits::max()))); };\n\n width *= cn;\n switch (depth)\n {\n case CV_8U:\n switch (thresholdType)\n {\n case CV_HAL_THRESH_BINARY:\n return threshold(start, end, src_data, src_step, dst_data, dst_step, width, saturate_8u(std::floor(thresh)), saturate_8u(std::round(maxValue)));\n case CV_HAL_THRESH_BINARY_INV:\n return threshold(start, end, src_data, src_step, dst_data, dst_step, width, saturate_8u(std::floor(thresh)), saturate_8u(std::round(maxValue)));\n case CV_HAL_THRESH_TRUNC:\n return threshold(start, end, src_data, src_step, dst_data, dst_step, width, saturate_8u(std::floor(thresh)), saturate_8u(std::round(maxValue)));\n case CV_HAL_THRESH_TOZERO:\n return threshold(start, end, src_data, src_step, dst_data, dst_step, width, saturate_8u(std::floor(thresh)), saturate_8u(std::round(maxValue)));\n case CV_HAL_THRESH_TOZERO_INV:\n return threshold(start, end, src_data, src_step, dst_data, dst_step, width, saturate_8u(std::floor(thresh)), saturate_8u(std::round(maxValue)));\n }\n break;\n case CV_16S:\n switch (thresholdType)\n {\n case CV_HAL_THRESH_BINARY:\n return threshold(start, end, src_data, src_step, dst_data, dst_step, width, saturate_16s(std::floor(thresh)), saturate_16s(std::round(maxValue)));\n case CV_HAL_THRESH_BINARY_INV:\n return threshold(start, end, src_data, src_step, dst_data, dst_step, width, saturate_16s(std::floor(thresh)), saturate_16s(std::round(maxValue)));\n case CV_HAL_THRESH_TRUNC:\n return threshold(start, end, src_data, src_step, dst_data, dst_step, width, saturate_16s(std::floor(thresh)), saturate_16s(std::round(maxValue)));\n case CV_HAL_THRESH_TOZERO:\n return threshold(start, end, src_data, src_step, dst_data, dst_step, width, saturate_16s(std::floor(thresh)), saturate_16s(std::round(maxValue)));\n case CV_HAL_THRESH_TOZERO_INV:\n return threshold(start, end, src_data, src_step, dst_data, dst_step, width, saturate_16s(std::floor(thresh)), saturate_16s(std::round(maxValue)));\n }\n break;\n case CV_32F:\n switch (thresholdType)\n {\n case CV_HAL_THRESH_BINARY:\n return threshold(start, end, src_data, src_step, dst_data, dst_step, width, static_cast(thresh), static_cast(maxValue));\n case CV_HAL_THRESH_BINARY_INV:\n return threshold(start, end, src_data, src_step, dst_data, dst_step, width, static_cast(thresh), static_cast(maxValue));\n case CV_HAL_THRESH_TRUNC:\n return threshold(start, end, src_data, src_step, dst_data, dst_step, width, static_cast(thresh), static_cast(maxValue));\n case CV_HAL_THRESH_TOZERO:\n return threshold(start, end, src_data, src_step, dst_data, dst_step, width, static_cast(thresh), static_cast(maxValue));\n case CV_HAL_THRESH_TOZERO_INV:\n return threshold(start, end, src_data, src_step, dst_data, dst_step, width, static_cast(thresh), static_cast(maxValue));\n }\n break;\n case CV_64F:\n switch (thresholdType)\n {\n case CV_HAL_THRESH_BINARY:\n return threshold(start, end, src_data, src_step, dst_data, dst_step, width, thresh, maxValue);\n case CV_HAL_THRESH_BINARY_INV:\n return threshold(start, end, src_data, src_step, dst_data, dst_step, width, thresh, maxValue);\n case CV_HAL_THRESH_TRUNC:\n return threshold(start, end, src_data, src_step, dst_data, dst_step, width, thresh, maxValue);\n case CV_HAL_THRESH_TOZERO:\n return threshold(start, end, src_data, src_step, dst_data, dst_step, width, thresh, maxValue);\n case CV_HAL_THRESH_TOZERO_INV:\n return threshold(start, end, src_data, src_step, dst_data, dst_step, width, thresh, maxValue);\n }\n break;\n }\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n}\n\nstatic inline int otsu(int start, int end, const uchar* src_data, size_t src_step, int width, std::atomic* cnt, int N, int* h)\n{\n const int c = cnt->fetch_add(1) % cv::getNumThreads();\n h += c * N;\n\n for (int i = start; i < end; i++)\n {\n for (int j = 0; j < width; j++)\n h[src_data[i * src_step + j]]++;\n }\n return CV_HAL_ERROR_OK;\n}\n\n// the algorithm is copied from imgproc/src/thresh.cpp,\n// in the function void cv::adaptiveThreshold\ntemplate\nstatic inline int adaptiveThreshold(int start, int end, const uchar* src_data, size_t src_step, uchar* dst_data, size_t dst_step, int width, int height, double maxValue, double C)\n{\n auto saturate = [](double x){ return static_cast(std::min(std::max(x, static_cast(std::numeric_limits::lowest())), static_cast(std::numeric_limits::max()))); };\n uchar mval = saturate(std::round(maxValue));\n\n if (method == CV_HAL_ADAPTIVE_THRESH_MEAN_C)\n {\n int cval = static_cast(std::round(C));\n if (cval != C)\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n\n std::vector res(width * ksize);\n auto process = [&](int x, int y) {\n int sum = 0;\n for (int i = 0; i < ksize; i++)\n {\n int q = std::min(std::max(y + i - ksize / 2, 0), width - 1);\n sum += src_data[x * src_step + q];\n }\n res[(x % ksize) * width + y] = sum;\n };\n\n const int left = ksize - 1, right = width - (ksize - 1);\n for (int i = start - ksize / 2; i < end + ksize / 2; i++)\n {\n if (i >= 0 && i < height)\n {\n for (int j = 0; j < left; j++)\n process(i, j);\n for (int j = right; j < width; j++)\n process(i, j);\n\n int vl;\n for (int j = left; j < right; j += vl)\n {\n vl = __riscv_vsetvl_e8m4(right - j);\n const uchar* row = src_data + i * src_step + j - ksize / 2;\n auto src = __riscv_vreinterpret_v_u16m8_i16m8(__riscv_vzext_vf2(__riscv_vle8_v_u8m4(row, vl), vl));\n auto sum = src;\n src = __riscv_vslide1down(src, row[vl], vl);\n sum = __riscv_vadd(sum, src, vl);\n src = __riscv_vslide1down(src, row[vl + 1], vl);\n sum = __riscv_vadd(sum, src, vl);\n if (ksize == 5)\n {\n src = __riscv_vslide1down(src, row[vl + 2], vl);\n sum = __riscv_vadd(sum, src, vl);\n src = __riscv_vslide1down(src, row[vl + 3], vl);\n sum = __riscv_vadd(sum, src, vl);\n }\n __riscv_vse16(res.data() + (i % ksize) * width + j, sum, vl);\n }\n }\n\n int cur = i - ksize / 2;\n if (cur >= start)\n {\n const short* row0 = res.data() + std::min(std::max(cur - ksize / 2, 0), height - 1) % ksize * width;\n const short* row1 = res.data() + std::min(std::max(cur + 1 - ksize / 2, 0), height - 1) % ksize * width;\n const short* row2 = res.data() + std::min(std::max(cur + 2 - ksize / 2, 0), height - 1) % ksize * width;\n const short* row3 = res.data() + std::min(std::max(cur + 3 - ksize / 2, 0), height - 1) % ksize * width;\n const short* row4 = res.data() + std::min(std::max(cur + 4 - ksize / 2, 0), height - 1) % ksize * width;\n int vl;\n for (int j = 0; j < width; j += vl)\n {\n vl = __riscv_vsetvl_e16m8(width - j);\n auto sum = __riscv_vle16_v_i16m8(row0 + j, vl);\n sum = __riscv_vadd(sum, __riscv_vle16_v_i16m8(row1 + j, vl), vl);\n sum = __riscv_vadd(sum, __riscv_vle16_v_i16m8(row2 + j, vl), vl);\n if (ksize == 5)\n {\n sum = __riscv_vadd(sum, __riscv_vle16_v_i16m8(row3 + j, vl), vl);\n sum = __riscv_vadd(sum, __riscv_vle16_v_i16m8(row4 + j, vl), vl);\n }\n auto mean = __riscv_vsub(__riscv_vdiv(sum, ksize * ksize, vl), cval, vl);\n auto cmp = __riscv_vmsgt(__riscv_vreinterpret_v_u16m8_i16m8(__riscv_vzext_vf2(__riscv_vle8_v_u8m4(src_data + cur * src_step + j, vl), vl)), mean, vl);\n if (type == CV_HAL_THRESH_BINARY)\n {\n __riscv_vse8(dst_data + cur * dst_step + j, __riscv_vmerge(__riscv_vmv_v_x_u8m4(0, vl), mval, cmp, vl), vl);\n }\n else\n {\n __riscv_vse8(dst_data + cur * dst_step + j, __riscv_vmerge(__riscv_vmv_v_x_u8m4(mval, vl), 0, cmp, vl), vl);\n }\n }\n }\n }\n }\n else\n {\n constexpr float kernel[2][5] = {{0.25f, 0.5f, 0.25f}, {0.0625f, 0.25f, 0.375f, 0.25f, 0.0625f}};\n std::vector res(width * ksize);\n auto process = [&](int x, int y) {\n float sum = 0;\n for (int i = 0; i < ksize; i++)\n {\n int q = std::min(std::max(y + i - ksize / 2, 0), width - 1);\n sum += kernel[ksize == 5][i] * src_data[x * src_step + q];\n }\n res[(x % ksize) * width + y] = sum;\n };\n\n const int left = ksize - 1, right = width - (ksize - 1);\n for (int i = start - ksize / 2; i < end + ksize / 2; i++)\n {\n if (i >= 0 && i < height)\n {\n for (int j = 0; j < left; j++)\n process(i, j);\n for (int j = right; j < width; j++)\n process(i, j);\n\n int vl;\n for (int j = left; j < right; j += vl)\n {\n vl = __riscv_vsetvl_e8m2(right - j);\n const uchar* row = src_data + i * src_step + j - ksize / 2;\n auto src = __riscv_vfwcvt_f(__riscv_vzext_vf2(__riscv_vle8_v_u8m2(row, vl), vl), vl);\n auto sum = __riscv_vfmul(src, kernel[ksize == 5][0], vl);\n src = __riscv_vfslide1down(src, row[vl], vl);\n sum = __riscv_vfmacc(sum, kernel[ksize == 5][1], src, vl);\n src = __riscv_vfslide1down(src, row[vl + 1], vl);\n sum = __riscv_vfmacc(sum, kernel[ksize == 5][2], src, vl);\n if (ksize == 5)\n {\n src = __riscv_vfslide1down(src, row[vl + 2], vl);\n sum = __riscv_vfmacc(sum, kernel[1][3], src, vl);\n src = __riscv_vfslide1down(src, row[vl + 3], vl);\n sum = __riscv_vfmacc(sum, kernel[1][4], src, vl);\n }\n __riscv_vse32(res.data() + (i % ksize) * width + j, sum, vl);\n }\n }\n\n int cur = i - ksize / 2;\n if (cur >= start)\n {\n const float* row0 = res.data() + std::min(std::max(cur - ksize / 2, 0), height - 1) % ksize * width;\n const float* row1 = res.data() + std::min(std::max(cur + 1 - ksize / 2, 0), height - 1) % ksize * width;\n const float* row2 = res.data() + std::min(std::max(cur + 2 - ksize / 2, 0), height - 1) % ksize * width;\n const float* row3 = res.data() + std::min(std::max(cur + 3 - ksize / 2, 0), height - 1) % ksize * width;\n const float* row4 = res.data() + std::min(std::max(cur + 4 - ksize / 2, 0), height - 1) % ksize * width;\n int vl;\n for (int j = 0; j < width; j += vl)\n {\n vl = __riscv_vsetvl_e32m8(width - j);\n auto sum = __riscv_vfmv_v_f_f32m8(-C, vl);\n sum = __riscv_vfmacc(sum, kernel[ksize == 5][0], __riscv_vle32_v_f32m8(row0 + j, vl), vl);\n sum = __riscv_vfmacc(sum, kernel[ksize == 5][1], __riscv_vle32_v_f32m8(row1 + j, vl), vl);\n sum = __riscv_vfmacc(sum, kernel[ksize == 5][2], __riscv_vle32_v_f32m8(row2 + j, vl), vl);\n if (ksize == 5)\n {\n sum = __riscv_vfmacc(sum, kernel[1][3], __riscv_vle32_v_f32m8(row3 + j, vl), vl);\n sum = __riscv_vfmacc(sum, kernel[1][4], __riscv_vle32_v_f32m8(row4 + j, vl), vl);\n }\n auto mean = __riscv_vnclipu(__riscv_vfncvt_rtz_xu(sum, vl), 0, __RISCV_VXRM_RNU, vl);\n auto cmp = __riscv_vmsgtu(__riscv_vle8_v_u8m2(src_data + cur * src_step + j, vl), mean, vl);\n if (type == CV_HAL_THRESH_BINARY)\n {\n __riscv_vse8(dst_data + cur * dst_step + j, __riscv_vmerge(__riscv_vmv_v_x_u8m2(0, vl), mval, cmp, vl), vl);\n }\n else\n {\n __riscv_vse8(dst_data + cur * dst_step + j, __riscv_vmerge(__riscv_vmv_v_x_u8m2(mval, vl), 0, cmp, vl), vl);\n }\n }\n }\n }\n }\n\n return CV_HAL_ERROR_OK;\n}\n\n} // anonymous\n\nint threshold(const uchar* src_data, size_t src_step, uchar* dst_data, size_t dst_step, int width, int height, int depth, int cn, double thresh, double maxValue, int thresholdType)\n{\n return threshold_range(0, height, src_data, src_step, dst_data, dst_step, width, depth, cn, thresh, maxValue, thresholdType);\n}\n\n// the algorithm is copied from imgproc/src/thresh.cpp,\n// in the function template static double getThreshVal_Otsu\nint threshold_otsu(const uchar* src_data, size_t src_step, uchar* dst_data, size_t dst_step, int width, int height, int depth, double maxValue, int thresholdType, double* thresh)\n{\n if (depth != CV_8UC1 || width * height < (1 << 15))\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n\n const int N = std::numeric_limits::max() + 1;\n const int nums = cv::getNumThreads();\n std::vector _h(N * nums, 0);\n int* h = _h.data();\n\n std::atomic cnt(0);\n cv::parallel_for_(Range(0, height), ThresholdInvoker({otsu}, src_data, src_step, width, &cnt, N, h), nums);\n for (int i = N; i < nums * N; i++)\n {\n h[i % N] += h[i];\n }\n\n double mu = 0, scale = 1. / (width*height);\n for (int i = 0; i < N; i++)\n {\n mu += i*(double)h[i];\n }\n\n mu *= scale;\n double mu1 = 0, q1 = 0;\n double max_sigma = 0, max_val = 0;\n\n for (int i = 0; i < N; i++)\n {\n double p_i, q2, mu2, sigma;\n\n p_i = h[i]*scale;\n mu1 *= q1;\n q1 += p_i;\n q2 = 1. - q1;\n\n if (std::min(q1,q2) < FLT_EPSILON || std::max(q1,q2) > 1. - FLT_EPSILON)\n continue;\n\n mu1 = (mu1 + i*p_i)/q1;\n mu2 = (mu - q1*mu1)/q2;\n sigma = q1*q2*(mu1 - mu2)*(mu1 - mu2);\n if (sigma > max_sigma)\n {\n max_sigma = sigma;\n max_val = i;\n }\n }\n\n *thresh = max_val;\n if (dst_data == nullptr)\n return CV_HAL_ERROR_OK;\n\n return invoke(width, height, {threshold_range}, src_data, src_step, dst_data, dst_step, width, depth, 1, max_val, maxValue, thresholdType);\n}\n\nint adaptiveThreshold(const uchar* src_data, size_t src_step, uchar* dst_data, size_t dst_step, int width, int height, double maxValue, int adaptiveMethod, int thresholdType, int blockSize, double C)\n{\n if (thresholdType != CV_HAL_THRESH_BINARY && thresholdType != CV_HAL_THRESH_BINARY_INV)\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n if (adaptiveMethod != CV_HAL_ADAPTIVE_THRESH_MEAN_C && adaptiveMethod != CV_HAL_ADAPTIVE_THRESH_GAUSSIAN_C)\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n if ((blockSize != 3 && blockSize != 5) || width < blockSize * 2)\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n\n switch (blockSize*100 + adaptiveMethod*10 + thresholdType)\n {\n case 300 + CV_HAL_ADAPTIVE_THRESH_MEAN_C*10 + CV_HAL_THRESH_BINARY:\n return invoke(width, height, {adaptiveThreshold<3, CV_HAL_ADAPTIVE_THRESH_MEAN_C, CV_HAL_THRESH_BINARY>}, src_data, src_step, dst_data, dst_step, width, height, maxValue, C);\n case 300 + CV_HAL_ADAPTIVE_THRESH_MEAN_C*10 + CV_HAL_THRESH_BINARY_INV:\n return invoke(width, height, {adaptiveThreshold<3, CV_HAL_ADAPTIVE_THRESH_MEAN_C, CV_HAL_THRESH_BINARY_INV>}, src_data, src_step, dst_data, dst_step, width, height, maxValue, C);\n case 500 + CV_HAL_ADAPTIVE_THRESH_MEAN_C*10 + CV_HAL_THRESH_BINARY:\n return invoke(width, height, {adaptiveThreshold<5, CV_HAL_ADAPTIVE_THRESH_MEAN_C, CV_HAL_THRESH_BINARY>}, src_data, src_step, dst_data, dst_step, width, height, maxValue, C);\n case 500 + CV_HAL_ADAPTIVE_THRESH_MEAN_C*10 + CV_HAL_THRESH_BINARY_INV:\n return invoke(width, height, {adaptiveThreshold<5, CV_HAL_ADAPTIVE_THRESH_MEAN_C, CV_HAL_THRESH_BINARY_INV>}, src_data, src_step, dst_data, dst_step, width, height, maxValue, C);\n case 300 + CV_HAL_ADAPTIVE_THRESH_GAUSSIAN_C*10 + CV_HAL_THRESH_BINARY:\n return invoke(width, height, {adaptiveThreshold<3, CV_HAL_ADAPTIVE_THRESH_GAUSSIAN_C, CV_HAL_THRESH_BINARY>}, src_data, src_step, dst_data, dst_step, width, height, maxValue, C);\n case 300 + CV_HAL_ADAPTIVE_THRESH_GAUSSIAN_C*10 + CV_HAL_THRESH_BINARY_INV:\n return invoke(width, height, {adaptiveThreshold<3, CV_HAL_ADAPTIVE_THRESH_GAUSSIAN_C, CV_HAL_THRESH_BINARY_INV>}, src_data, src_step, dst_data, dst_step, width, height, maxValue, C);\n case 500 + CV_HAL_ADAPTIVE_THRESH_GAUSSIAN_C*10 + CV_HAL_THRESH_BINARY:\n return invoke(width, height, {adaptiveThreshold<5, CV_HAL_ADAPTIVE_THRESH_GAUSSIAN_C, CV_HAL_THRESH_BINARY>}, src_data, src_step, dst_data, dst_step, width, height, maxValue, C);\n case 500 + CV_HAL_ADAPTIVE_THRESH_GAUSSIAN_C*10 + CV_HAL_THRESH_BINARY_INV:\n return invoke(width, height, {adaptiveThreshold<5, CV_HAL_ADAPTIVE_THRESH_GAUSSIAN_C, CV_HAL_THRESH_BINARY_INV>}, src_data, src_step, dst_data, dst_step, width, height, maxValue, C);\n }\n\n return CV_HAL_ERROR_NOT_IMPLEMENTED;\n}\n\n#endif // CV_HAL_RVV_1P0_ENABLED\n\n}}} /// cv::rvv_hal::imgproc\n", "source": "opencv", "added": "2026-11-08", "created": "", "token_count": 6927, "license": "Apache-2.0", "author": "opencv contributors"}
{"id": "github:opencv:modules/calib/CMakeLists.txt", "text": "set(the_description \"Camera Calibration and 3D Reconstruction\")\n\nset(debug_modules \"\")\nif(DEBUG_opencv_calib)\n list(APPEND debug_modules opencv_highgui)\nendif()\nocv_define_module(calib opencv_imgproc opencv_objdetect opencv_flann opencv_geometry opencv_stereo ${debug_modules}\n WRAP java objc python js\n)\n", "source": "opencv", "added": "2026-11-08", "created": "", "token_count": 74, "license": "Apache-2.0", "author": "opencv contributors"}
{"id": "github:opencv:modules/core/include/opencv2/core/bindings_utils.hpp", "text": "// This file is part of OpenCV project.\n// It is subject to the license terms in the LICENSE file found in the top-level directory\n// of this distribution and at http://opencv.org/license.html.\n\n#ifndef OPENCV_CORE_BINDINGS_UTILS_HPP\n#define OPENCV_CORE_BINDINGS_UTILS_HPP\n\n#include \n#include \n#include \n\n#include \n\nnamespace cv { namespace utils {\n//! @addtogroup core_utils\n//! @{\n\nCV_EXPORTS_W String dumpInputArray(InputArray argument);\n\nCV_EXPORTS_W String dumpInputArrayOfArrays(InputArrayOfArrays argument);\n\nCV_EXPORTS_W String dumpInputOutputArray(InputOutputArray argument);\n\nCV_EXPORTS_W String dumpInputOutputArrayOfArrays(InputOutputArrayOfArrays argument);\n\nCV_WRAP inline\nString dumpBool(bool argument)\n{\n return (argument) ? String(\"Bool: True\") : String(\"Bool: False\");\n}\n\nCV_WRAP inline\nString dumpInt(int argument)\n{\n return cv::format(\"Int: %d\", argument);\n}\n\nCV_WRAP inline\nString dumpInt64(int64 argument)\n{\n std::ostringstream oss(\"Int64: \", std::ios::ate);\n oss << argument;\n return oss.str();\n}\n\nCV_WRAP inline\nString dumpSizeT(size_t argument)\n{\n std::ostringstream oss(\"size_t: \", std::ios::ate);\n oss << argument;\n return oss.str();\n}\n\nCV_WRAP inline\nString dumpFloat(float argument)\n{\n return cv::format(\"Float: %.2f\", argument);\n}\n\nCV_WRAP inline\nString dumpDouble(double argument)\n{\n return cv::format(\"Double: %.2f\", argument);\n}\n\nCV_WRAP inline\nString dumpCString(const char* argument)\n{\n return cv::format(\"String: %s\", argument);\n}\n\nCV_WRAP inline\nString dumpString(const String& argument)\n{\n return cv::format(\"String: %s\", argument.c_str());\n}\n\nCV_WRAP inline\nString dumpRect(const Rect& argument)\n{\n return format(\"rect: (x=%d, y=%d, w=%d, h=%d)\", argument.x, argument.y,\n argument.width, argument.height);\n}\n\nCV_WRAP inline\nString dumpTermCriteria(const TermCriteria& argument)\n{\n return format(\"term_criteria: (type=%d, max_count=%d, epsilon=%lf\",\n argument.type, argument.maxCount, argument.epsilon);\n}\n\nCV_WRAP inline\nString dumpRotatedRect(const RotatedRect& argument)\n{\n return format(\"rotated_rect: (c_x=%f, c_y=%f, w=%f, h=%f, a=%f)\",\n argument.center.x, argument.center.y, argument.size.width,\n argument.size.height, argument.angle);\n}\n\nCV_WRAP inline\nString dumpRange(const Range& argument)\n{\n if (argument == Range::all())\n {\n return \"range: all\";\n }\n else\n {\n return format(\"range: (s=%d, e=%d)\", argument.start, argument.end);\n }\n}\n\nCV_EXPORTS_W String dumpVectorOfInt(const std::vector& vec);\n\nCV_EXPORTS_W String dumpVectorOfDouble(const std::vector& vec);\n\nCV_EXPORTS_W String dumpVectorOfRect(const std::vector& vec);\n\n\n//! @cond IGNORED\n\nCV_WRAP inline\nString testOverloadResolution(int value, const Point& point = Point(42, 24))\n{\n return format(\"overload (int=%d, point=(x=%d, y=%d))\", value, point.x,\n point.y);\n}\n\nCV_WRAP inline\nString testOverloadResolution(const Rect& rect)\n{\n return format(\"overload (rect=(x=%d, y=%d, w=%d, h=%d))\", rect.x, rect.y,\n rect.width, rect.height);\n}\n\nCV_WRAP inline\nRotatedRect testRotatedRect(float x, float y, float w, float h, float angle)\n{\n return RotatedRect(Point2f(x, y), Size2f(w, h), angle);\n}\n\nCV_WRAP inline\nstd::vector testRotatedRectVector(float x, float y, float w, float h, float angle)\n{\n std::vector result;\n for (int i = 0; i < 10; i++)\n result.push_back(RotatedRect(Point2f(x + i, y + 2 * i), Size2f(w, h), angle + 10 * i));\n return result;\n}\n\nCV_WRAP inline\nint testOverwriteNativeMethod(int argument)\n{\n return argument;\n}\n\nCV_WRAP inline\nString testReservedKeywordConversion(int positional_argument, int lambda = 2, int from = 3)\n{\n return format(\"arg=%d, lambda=%d, from=%d\", positional_argument, lambda, from);\n}\n\nCV_WRAP inline\nvoid generateVectorOfRect(size_t len, CV_OUT std::vector& vec)\n{\n vec.resize(len);\n if (len > 0)\n {\n RNG rng(12345);\n Mat tmp(static_cast(len), 1, CV_32SC4);\n rng.fill(tmp, RNG::UNIFORM, 10, 20);\n tmp.copyTo(vec);\n }\n}\n\nCV_WRAP inline\nvoid generateVectorOfInt(size_t len, CV_OUT std::vector& vec)\n{\n vec.resize(len);\n if (len > 0)\n {\n RNG rng(554433);\n Mat tmp(static_cast(len), 1, CV_32SC1);\n rng.fill(tmp, RNG::UNIFORM, -10, 10);\n tmp.copyTo(vec);\n }\n}\n\nCV_WRAP inline\nvoid generateVectorOfMat(size_t len, int rows, int cols, int dtype, CV_OUT std::vector& vec)\n{\n vec.resize(len);\n if (len > 0)\n {\n RNG rng(65431);\n for (size_t i = 0; i < len; ++i)\n {\n vec[i].create(rows, cols, dtype);\n rng.fill(vec[i], RNG::UNIFORM, 0, 10);\n }\n }\n}\n\nCV_WRAP inline\nvoid testRaiseGeneralException()\n{\n throw std::runtime_error(\"exception text\");\n}\n\nCV_WRAP inline\nAsyncArray testAsyncArray(InputArray argument)\n{\n AsyncPromise p;\n p.setValue(argument);\n return p.getArrayResult();\n}\n\nCV_WRAP inline\nAsyncArray testAsyncException()\n{\n AsyncPromise p;\n try\n {\n CV_Error(Error::StsOk, \"Test: Generated async error\");\n }\n catch (const cv::Exception& e)\n {\n p.setException(e);\n }\n return p.getArrayResult();\n}\n\nCV_WRAP inline\nString dumpVec2i(const cv::Vec2i value = cv::Vec2i(42, 24)) {\n return format(\"Vec2i(%d, %d)\", value[0], value[1]);\n}\n\nstruct CV_EXPORTS_W_SIMPLE ClassWithKeywordProperties {\n CV_PROP_RW int lambda;\n CV_PROP int except;\n\n CV_WRAP explicit ClassWithKeywordProperties(int lambda_arg = 24, int except_arg = 42)\n {\n lambda = lambda_arg;\n except = except_arg;\n }\n};\n\nstruct CV_EXPORTS_W_PARAMS FunctionParams\n{\n CV_PROP_RW int lambda = -1;\n CV_PROP_RW float sigma = 0.0f;\n\n FunctionParams& setLambda(int value) CV_NOEXCEPT\n {\n lambda = value;\n return *this;\n }\n\n FunctionParams& setSigma(float value) CV_NOEXCEPT\n {\n sigma = value;\n return *this;\n }\n};\n\nCV_WRAP inline String\ncopyMatAndDumpNamedArguments(InputArray src, OutputArray dst,\n const FunctionParams& params = FunctionParams())\n{\n src.copyTo(dst);\n return format(\"lambda=%d, sigma=%.1f\", params.lambda,\n params.sigma);\n}\n\nnamespace nested {\nCV_WRAP inline bool testEchoBooleanFunction(bool flag) {\n return flag;\n}\n\nclass CV_EXPORTS_W CV_WRAP_AS(ExportClassName) OriginalClassName\n{\npublic:\n struct CV_EXPORTS_W_SIMPLE Params\n {\n CV_PROP_RW int int_value;\n CV_PROP_RW float float_value;\n\n CV_WRAP explicit Params(int int_param = 123, float float_param = 3.5f)\n {\n int_value = int_param;\n float_value = float_param;\n }\n };\n\n explicit OriginalClassName(const OriginalClassName::Params& params = OriginalClassName::Params())\n {\n params_ = params;\n }\n\n CV_WRAP int getIntParam() const\n {\n return params_.int_value;\n }\n\n CV_WRAP float getFloatParam() const\n {\n return params_.float_value;\n }\n\n CV_WRAP static std::string originalName()\n {\n return \"OriginalClassName\";\n }\n\n CV_WRAP static Ptr