使用Qt+OpenCV写一个旋转/抠图/mask生成工具
1、旋转功能
cpp
void FormRotate::rotateImage(const cv::Mat &src, cv::Mat &dst, double degree) //旋转
{
if (fabs(degree) < 0.001)
{
dst = src;
return;
}
//center旋转的中心点坐标
//degree旋转的角度,不是弧度,>0逆时针,<0顺时针
//scale图像缩放比例
int width = src.cols;
int height = src.rows;
cv::Point2f center(width / 2, height / 2);
cv::Mat M = cv::getRotationMatrix2D(center, degree, 1.0);
//旋转,保持分辨率不变,周边涂黑
cv::warpAffine(src, dst, M, cv::Size(width, height));
}
2、抠图功能
支持roi矩形,框选之后,抠图
cpp
CUtil uti;
cv::Rect r = cv::Rect(vtRect[0].x(), vtRect[0].y(), vtRect[0].width(), vtRect[0].height());
cv::Rect big = cv::Rect(0, 0, m_matSrc.cols, m_matSrc.rows);
if (!uti.isRectInside(r, big))
{
QMessageBox bbox(QMessageBox::Critical, tr("错误"), QObject::tr("抠图失败!矩形ROI不能在图片范围之外!"));
bbox.setButtonText(QMessageBox::Ok, QObject::tr("确定"));
bbox.exec();
return;
}
try
{
cv::Mat crop = m_matSrc(r);
QImage image = uti.cvMat2QImage(crop);
ui->widget_dst->setImage(image, true);
}
catch (...)
{
QImage image;
ui->widget_dst->setImage(image, true);
QMessageBox bbox(QMessageBox::Critical, tr("错误"), QObject::tr("抠图失败!算法异常!"));
bbox.setButtonText(QMessageBox::Ok, QObject::tr("确定"));
bbox.exec();
return;
}
3、mask生成功能
支持roi矩形,圆形和多边形,指定区域生成mask图片
cpp
int sz3 = (int)vtPy.size(); //多边形
for (int k = 0; k < sz3; k++)
{
cv::Mat mask = cv::Mat::zeros(m_matSrc.rows, m_matSrc.cols, m_matSrc.type());
std::vector<cv::Point> pp;
for (int m = 0; m < vtPy[k].size(); m++)
{
pp.push_back(cv::Point(vtPy[k][m].x(), vtPy[k][m].y()));
}
cv::fillPoly(mask, pp, cv::Scalar(255, 255, 255));
cv::Rect r = cv::boundingRect(pp); //最小外接矩形
cv::Rect big = cv::Rect(0, 0, m_matSrc.cols, m_matSrc.rows);
if (!uti.isRectInside(r, big))
{
QMessageBox bbox(QMessageBox::Critical, tr("错误"), QObject::tr("生成mask失败!ROI不能在图片范围之外!"));
bbox.setButtonText(QMessageBox::Ok, QObject::tr("确定"));
bbox.exec();
return;
}
cv::bitwise_or(dst, mask, dst); //合并mask
}