opencv怎么用qt填充轮廓
时间: 2023-05-23 20:06:02 浏览: 92
A:
使用OpenCV和Qt可以很方便地对轮廓进行填充,具体步骤如下:
1. 使用OpenCV中的findContours函数查找轮廓。
```cpp
std::vector<std::vector<cv::Point>> contours;
cv::findContours(image, contours, cv::RETR_LIST, cv::CHAIN_APPROX_SIMPLE);
```
2. 创建一个QPixmap对象并将其转换为QImage。
```cpp
QPixmap pixmap;
pixmap.convertFromImage(QImage(image.data, image.cols, image.rows, image.step, QImage::Format_RGB888));
```
3. 创建一个QPainter对象,并设置其背景颜色。可以使用任何想要的颜色。
```cpp
QPainter painter(&pixmap);
painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
painter.setBackground(QBrush(Qt::white));
painter.eraseRect(0, 0, pixmap.width(), pixmap.height());
```
4. 遍历所有轮廓,并使用QPainter的drawPolygon函数来填充区域。
```cpp
for (int i = 0; i < contours.size(); i++)
{
painter.setBrush(QBrush(Qt::red));
painter.drawPolygon(QPolygonF(QVector<QPointF>::fromStdVector(contours[i])));
}
```
5. 最后将QPixmap对象显示在QWidget中。
```cpp
ui->label->setPixmap(pixmap);
```
完整代码:
```cpp
std::vector<std::vector<cv::Point>> contours;
cv::findContours(image, contours, cv::RETR_LIST, cv::CHAIN_APPROX_SIMPLE);
QPixmap pixmap;
pixmap.convertFromImage(QImage(image.data, image.cols, image.rows, image.step, QImage::Format_RGB888));
QPainter painter(&pixmap);
painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
painter.setBackground(QBrush(Qt::white));
painter.eraseRect(0, 0, pixmap.width(), pixmap.height());
for (int i = 0; i < contours.size(); i++)
{
painter.setBrush(QBrush(Qt::red));
painter.drawPolygon(QPolygonF(QVector<QPointF>::fromStdVector(contours[i])));
}
ui->label->setPixmap(pixmap);
```
阅读全文