C++如何获取边界框(rect)内的像素值及对应坐标?有哪些实现方法?
实现方案
你可以直接通过OpenCV的cv::Mat的at()方法读取边界框范围内的像素值,对应坐标就是循环中遍历的x、y值,注意OpenCV像素读取的参数顺序是先y(行索引)后x(列索引),不要写反。
修改后的完整代码示例
#include <vector> #include <opencv2/opencv.hpp> // 可选:定义结构体存储像素坐标和对应数值 struct PixelInfo { int x; int y; cv::Vec3b bgr_val; // 三通道图用这个,单通道图可以换成uchar }; int main() { cv::Mat osrc; // 你的输入图像 std::vector<Detector::Object> detected_objects; for (int i = 0; i < detected_objects.size(); ++i) { int xmin = detected_objects[i].rect.x; int ymin = detected_objects[i].rect.y; int width = detected_objects[i].rect.width; int height = detected_objects[i].rect.height; // 先做边界截断,避免框超出图像范围导致越界崩溃 xmin = std::max(0, xmin); ymin = std::max(0, ymin); int xmax = std::min(osrc.cols, xmin + width); int ymax = std::min(osrc.rows, ymin + height); cv::Rect rect(xmin, ymin, xmax - xmin, ymax - ymin); cv::rectangle(osrc, rect, cv::Scalar(200, 200, 10), 1, cv::LINE_8, 0); std::vector<PixelInfo> current_obj_pixels; // 存储当前目标的所有像素信息 // 遍历边界框内所有像素 for (int x = xmin; x < xmax; x++) { for (int y = ymin; y < ymax; y++) { // 读取三通道BGR像素,单通道图改为 osrc.at<uchar>(y, x) cv::Vec3b pixel = osrc.at<cv::Vec3b>(y, x); // 存入容器/直接打印都可以 current_obj_pixels.push_back({x, y, pixel}); // 打印示例 // std::cout << "坐标(x,y):(" << x << "," << y << ") 像素值(B,G,R):(" // << (int)pixel[0] << "," << (int)pixel[1] << "," << (int)pixel[2] << ")\n"; } } } return 0; }
注意事项
- 如果你的输入是单通道灰度图,把像素读取的代码换成
uchar pixel = osrc.at<uchar>(y, x)即可。 - 边界截断步骤不可省略,否则如果检测框超出图像边缘,会触发内存越界导致程序崩溃。
- 如果你不需要存储所有像素,直接在内层循环中处理对应
x、y和像素值即可。
内容的提问来源于stack exchange,提问作者ベスマ・ゲスミ
相关产品推荐
相关产品推荐

