c++ - 如何延长OpenCV中绘制的线?

标签 c++ opencv drawing face-detection

我有一个创建人脸检测程序的项目。其中一个要求是我要在脸部中心画一条线。

现在我这样做的方法是首先在两只眼睛之间画一条线(通过获取每只眼睛的坐标并将它们用作线点),然后画一条与之垂直的线。这样我也可以考虑面部旋转。

但是这条线与穿过眼睛的线的长度相同。如果可能的话,我希望这条垂直线能够穿过整个脸部。附件是我的旋转面部图像的输出示例。我需要更长的绿线。

最佳答案

不幸的是,您的图像是 jpeg,因此它具有压缩伪影。

我首先尝试提取线条,但这没有提供良好的角度信息,因此我在绿色区域分割后使用 cv::minAreaRect。

cv::Mat green;
cv::inRange(input, cv::Scalar(0,100,0), cv::Scalar(100,255,100),green);


// instead of this, maybe try to find contours and choose the right one, if there are more green "objects" in the image
std::vector<cv::Point2i> locations; 
cv::findNonZero(green, locations);

// find the used color to draw in same color later
cv::Vec3d averageColorTmp(0,0,0);
for(unsigned int i=0; i<locations.size(); ++i)
{
    averageColorTmp += input.at<cv::Vec3b>(locations[i]);
}
averageColorTmp *= 1.0/locations.size();

// compute direction of the segmented region
cv::RotatedRect line = cv::minAreaRect(locations);

// extract directions:
cv::Point2f start = line.center;
cv::Point2f rect_points[4];
line.points(rect_points);
cv::Point2f direction1 = rect_points[0] - rect_points[1];
cv::Point2f direction2 = rect_points[0] - rect_points[3];

// use dominant direction
cv::Point2f lineWidthDirection;
lineWidthDirection = (cv::norm(direction1) < cv::norm(direction2)) ? direction1 : direction2;
double lineWidth = cv::norm(lineWidthDirection);
cv::Point2f lineLengthDirection;
lineLengthDirection = (cv::norm(direction1) > cv::norm(direction2)) ? direction1 : direction2;
lineLengthDirection = 0.5*lineLengthDirection; // because we operate from center;

// input parameter:
// how much do you like to increase the line size?
// value of 1.0 is original size
// value of > 1 is increase of line
double scaleFactor = 3.0;

// draw the line
cv::line(input, start- scaleFactor*lineLengthDirection, start+ scaleFactor*lineLengthDirection, cv::Scalar(averageColorTmp[0],averageColorTmp[1],averageColorTmp[2]), lineWidth);

给出这个结果:

enter image description here

如果图像中没有其他绿色而只有绿线,则此方法应该非常稳健。如果图像中还有其他绿色部分,您应该首先提取轮廓并选择正确的轮廓来分配变量locations

关于c++ - 如何延长OpenCV中绘制的线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34023551/

相关文章:

C++从文件的一部分加载数据

c++ - OpenCV 最后的凸性缺陷不对

c++ - 获取霍夫线opencv c++的交点

c# - .NET C# 绘图缓慢

objective-c - UIImage drawInRect : is very slow; is there a faster way?

python - 在pyglet(python)中按像素绘制

c++ - 从 xml 获取整数和 float

c++ - 如何构建具有所有依赖项的 C++ 以在另一台机器上运行

c++ - 为什么我的 C++ Winsock 服务器无法从客户端接收数据?

c++ - Qt OpenCV 网络摄像头流打开和关闭