OpenCV 分段错误(核心转储)在使用 cv::Mat::at 时



我正在尝试将cv::Mat像素映射到 CUDA 计算的float4*

cv::Mat frame = cv::imread("peds-007.png", cv::IMREAD_COLOR);
cudaAllocMapped((void**) cpu, (void**) gpu,
frame.cols * frame.rows * sizeof(float) * 4);
float4* cpuPtr = *cpu;
for (uint32_t y = 0; y < frame.rows; y++) {
for (uint32_t x = 0; x < frame.cols; x++) {
std::cout << x << ", " << y << std::endl;
const float4 px = make_float4(float(frame.at<cv::Vec3b>(x, y)[2]),
float(frame.at<cv::Vec3b>(x, y)[1]),
float(frame.at<cv::Vec3b>(x, y)[0]),
float(255));
//float(frame.at<cv::Vec4b>(x, y)[3]));         
cpuPtr[y*imgWidth+x] = px;
}
}

如果我运行上面的代码,我会得到Segmentation fault (core dumped).

代码访问的最后一个像素位于 (1662, 0(。

如果我直接访问循环外的像素:

frame.at<cv::Vec3b>(1662, 0);

它也会导致Segmentation fault (core dumped)

为什么会发生这种情况,我该如何解决这个问题?

cv::Mat 按行主顺序编制索引。颠倒你的 x 和 y。

const float4 px = make_float4(float(frame.at<cv::Vec3b>(y,x)[2]),
float(frame.at<cv::Vec3b>(y,x)[1]),
float(frame.at<cv::Vec3b>(y,x)[0]),
float(255));

最新更新