Here’s the deal where this maths helps:-
Lets say I have a large image or webcam view, and can find a face in it and have the x,y,width,height rectangle coordinates for that face in that image, and I want to take that face and make it fit a template (fit in another rectangle in a second image).
Simply just copy the rectangle pixels from image 1 and paste it to the new rectangle in image 2, right..
however what if I want to take some of the image surrounding the face so I can use a feathered mask on image 2 as such, i.e. image 2 is 512px x 512px and I want the face to go into a rectangle somewhere in the lower middle of this second image, but wish fill the entire of image2 with available data (obviously if the face is right at the border of an image some will be left blank).
Well the below helped me with some javascript I was doing with canvas and webcams etc, but is applicable across the board hence the maths section. Firstly I found this:-
1 2 3 4 5 6 7 |
Rectangle 1 has (x1, y1) origin and (w1, h1) for width and height, and Rectangle 2 has (x2, y2) origin and (w2, h2) for width and height, then Given point (x, y) in terms of Rectangle 1 coords, to convert it to Rectangle 2 coords: xNew = ((x-x1)/w1)*w2 + x2; yNew = ((y-y1)/h1)*h2 + y2; |
So taking that I created this code, javascript/pseudocode.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
//pseudo: first clear/create image 2 //source rect1 is in image1, destination rect2 is in image2, //result is rect to copy from image1 to completly fill image2. //depending on system you may need to check bounds of result rect is within //image 1 borders otherwise you may get pixel copying errors, principle is the //same nonetheless. result.x = ((0-rect2.x)/rect2.width)*rect1.width + rect1.x; result.y = ((0-rect2.y)/rect2.height)*rect1.height + rect1.y; result.width = (((image2.width-rect2.x)/rect2.width)*rect1.width + rect1.x)-result.x; result.height = (((image2.height-rect2.y)/rect2.height)*rect1.height + rect1.y)-result.y; //pseudo //copy result rect pixel coo-rds from image1 to 0,0,image2.width,image2.height of image2 // //canvas.context.drawImage(image1,result.x,result.y,result.width,result.height,0,0,image2.width,image2.height); |
Hope that helps with someone’s brain mangling, if indeed you stumble across this page.