如何在 C++ 中获取边界框(矩形)内的像素值和坐标?有啥方法吗?
Posted
技术标签:
【中文标题】如何在 C++ 中获取边界框(矩形)内的像素值和坐标?有啥方法吗?【英文标题】:How can I get the pixels values and coordinates inside bounding box (rect) in c++? is there any method?如何在 C++ 中获取边界框(矩形)内的像素值和坐标?有什么方法吗? 【发布时间】:2021-11-01 09:44:15 【问题描述】:我正在尝试在对象的边界框内获取像素的值及其 x 和 y 坐标。
这是我的部分代码:
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;
Rect rect(xmin, ymin, width, height); //The upper left coordinates (x, y) and the length (x) and width (y) of the rectangle
cv::rectangle(osrc, rect, Scalar(200, 200, 10), 1, LINE_8, 0); // set rectangle color
// std::cout << "\n coord: \n" << rect;
//std::cout << "# of contour points: " << rect.size() << std::endl;
int xmax = xmin + width;
int ymax = ymin + height;
for (size_t x = xmin; x < xmax; x++)
for (size_t y = ymin; y < ymax; y++)
感谢任何帮助!
【问题讨论】:
创建 5 个像素作为示例。每边4个,中间1个。看看他们的坐标。看到模式了吗? 【参考方案1】:v::Mat BoxValues = cv::Mat::zeros(detected_objects[i].rect.Height, detected_objects[i].rect.Width,type());
BoxValues = osrc(cv::Range(int(detected_objects[i].rect.y()),int(detected_objects[i].rect.y())+detected_objects[i].rect.Height),cv::Range(int(detected_objects[i].rect.x()),int(detected_objects[i].rect.x())+detected_objects[i].rect.Wigth));
结果 BoxValues 将保存边界框内像素值。
关于坐标希望我们可以通过cv::Range
得到。
【讨论】:
谢谢!我试试看【参考方案2】:我找到了解决办法!
这是提取 yolo 边界框内的像素值和坐标的部分代码:
for (i = 0; i < detected_objects.size(); ++i)
xmin = detected_objects[i].rect.x;
ymin = detected_objects[i].rect.y;
width = detected_objects[i].rect.width;
height = detected_objects[i].rect.height;
xmax = xmin + width;
ymax = ymin + height;
Rect rect(xmin, ymin, width, height); //The upper left coordinates (x, y) and the length (x) and width (y) of the rectangle
cv::rectangle(osrc, rect, Scalar(200, 200, 10), 1, LINE_8, 0); // set rectangle color
std::cout << "rect number:" << rect << "[" << i << "]" << "\n"; // print the number of detected objects
for (x = xmin; x < xmax; x++)
for (y = ymin; y < ymax; y++)
// pixel_values = osrc.at<Vec3b>(x, y); // for 3 channels output
// Scalar intensity = osrc.at<uchar>(y, x);
Scalar intensity = osrc.at<uchar>(Point(x, y)); //get pixel intensity from one channel (Grayscale image)
std::cout << "Pixel intensity: " << intensity << "[" << i << "]" << "\n";
//allocate the array
int** arr = new int* [xmax];
for (int k = 0; k < xmax; k++)
arr[k] = new int[ymax];
// use the array
cout << "coords: "<<"[" << x << "," << y << "]: \n ";
//cout << arr[x][y] << endl;
//deallocate the array
for (int k = 0; k < xmax; k++)
delete[] arr[k];
delete[] arr;
// std::cout << " \npixel: \n " << Point(x,y);
// pixelValue = GetPixel(hDC, pos.x, pos.y);
// std::cout << " \pixelValue: \n" << pixelValue;
【讨论】:
以上是关于如何在 C++ 中获取边界框(矩形)内的像素值和坐标?有啥方法吗?的主要内容,如果未能解决你的问题,请参考以下文章
如何在不包含(或少量)背景像素的情况下调整对象内的矩形或调整其大小?