I write code and i want How to expand the rectangle after the detection of the faces to up to the head and neck of human
#include <opencv2/imgproc/imgproc.hpp> //this code detetced faces ///
#include <opencv2/objdetect/objdetect.hpp>///////////
#include <opencv2/highgui/highgui.hpp>
////////////////////
using namespace cv;
using namespace std;
int main()
{
CascadeClassifier cascade;
if (!cascade.load("haarcascade_frontalface_alt2.xml")) //load harcascade xml
return -1;
Mat src = imread("11.jpg"); //read image
if (src.empty())
return -1;
cv::resize(src,src,cv::Size(600,600)); resize image
Mat gray;
cvtColor(src, gray, CV_BGR2GRAY);
equalizeHist(gray, gray);
vector<Rect> faces;
cascade.detectMultiScale(gray, faces, 1.2, 3,0,Size(30,30));
for (size_t i = 0; i < faces.size(); i++)
{
/////////////////////////////
Rect r = faces[i];
//////////////////////////////
Mat faceROI = gray( faces[i] );
int x = faces[i].x;
int y = faces[i].y;
int h =0.3*y+faces[i].height;
int w = faces[i].width;
printf("Orig dimensions after h * w crop 1: %dx%d\n",h,w);
printf("Orig dimensions after x* y crop 2: %dx%d\n",x,y);
rectangle(src,Point (x,y),Point(x + w,y +h),Scalar(255,0,255),1,4,0);
imshow("mmmmmmmmmmm.jpg",src ); //show image in windows
}
///////////////////////////////
waitKey(0);
return 0;
}
To expand the OpenCV faces rectangle, you can also use below operators(1) to cv::Rect
class
//expanding or shrinking a rectangle by a certain amount
cv::Rect += cv::Size
//shifting a rectangle by a certain offset
cv::Rect -= cv::Point
Example for expanding face rectangle by 10% would be
cv::Size deltaSize( faces[i].width * 0.1f, faces[i].height * 0.1f ); // 0.1f = 10/100
cv::Point offset( deltaSize.width/2, deltaSize.height/2);
faces[i] += deltaSize;
faces[i] -= offset;
You need to adjust the height and starting y coordinate appropriately.
On a short look, I felt height of box should be increases by a factor of 0.3 on both the sides (top and bottom). So I subtracted 0.3*h
from y
and added 0.3*2*h
(i.e. 0.6*h) to h
.
It is just my rough calculation. For fine adjustment, you analyze it for different faces and come up with a measurement that best suits your purpose.
Here is the changed code:
int x = faces[i].x;
int h_temp = faces[i].height; // storing original height
int y = faces[i].y - h_temp*0.3; // y is reduced by 0.3*h
int w = faces[i].width;
int h = h_temp*1.6; // height is increases by 60%
And below is the result I got for example. Green shows original I got. Blue is the modified:
Remember, how much you want to select, depends on you. Make adjustments to above values to get your required result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With