You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Simulink中使用houghlines提取point1字段时遇mxArray错误

问题说明

在Simulink的MATLAB Function模块做直线检测仿真,直接调用houghlines时触发动态内存分配提示,添加coder.extrinsic后能打印lines结构体,但提取lines(1).point1时报错:Attempt to extract field 'point1' from 'mxArray'。试过预创建结构体,没解决,怀疑是lines尺寸动态变化导致。

原代码

function masked_image = fcn(image)

[r,g,b]=imsplit(image);

masked_image=r==255 & g==0 & b==0;
masked_image=edge(masked_image);
%imshow(masked_image);
[H,T,R]=hough(masked_image);
peaks = houghpeaks(H)

assert(length(peaks) < 100);
coder.extrinsic("houghlines");
lines=houghlines(masked_image,T,R,peaks);
if ~isempty(lines)
    disp(lines(1).point1)
end

错误信息

Attempt to extract field 'point1' from 'mxArray'.

Function 'Image Processing System/detectColorBox' (#27.338.346), line 19, column 10:
"lines(1)"
Launch diagnostic report. 

解决思路与修改代码

问题核心:用coder.extrinsic声明的函数,其输出在代码生成环境中会被视为mxArray类型,MATLAB Coder无法直接解析该类型的结构体字段,必须先将其转换为Coder可识别的结构体类型。

修改步骤:

  1. 提前定义固定结构的直线结构体模板,明确所有字段的数据类型;
  2. 创建足够容量的结构体数组(利用assert限制的peaks数量,设100足够);
  3. 将houghlines返回的mxArray类型数据,逐个字段复制到预定义的结构体数组中。

修改后的代码:

function masked_image = fcn(image)
% 预定义直线结构体模板,明确字段和数据类型
lineTemplate = struct('point1', [0 0], 'point2', [0 0], 'theta', 0, 'rho', 0);
% 创建最大容量的结构体数组(对应assert限制的peaks<100)
lines = repmat(lineTemplate, 1, 100);

[r,g,b]=imsplit(image);

masked_image=r==255 & g==0 & b==0;
masked_image=edge(masked_image);
[H,T,R]=hough(masked_image);
peaks = houghpeaks(H);

assert(length(peaks) < 100);
coder.extrinsic("houghlines");
% 调用houghlines,返回结果暂存为mxArray类型
tempLines = houghlines(masked_image,T,R,peaks);

if ~isempty(tempLines)
    numLines = length(tempLines);
    % 逐个字段复制,转换为Coder可识别的结构体
    for i = 1:numLines
        lines(i).point1 = tempLines(i).point1;
        lines(i).point2 = tempLines(i).point2;
        lines(i).theta = tempLines(i).theta;
        lines(i).rho = tempLines(i).rho;
    end
    % 现在可正常访问结构体字段
    disp(lines(1).point1);
end

关键要点

  • coder.extrinsic标记的函数输出无法直接解析结构体字段,必须手动转换;
  • 预创建结构体数组时,容量要覆盖所有可能的情况(这里用assert限制了peaks数量,所以设100足够),避免动态尺寸问题;
  • 逐个字段复制能让MATLAB Coder明确每个字段的类型和尺寸,消除动态内存分配的不确定性。

内容的提问来源于stack exchange,提问作者gill bates

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 14:47:40