我维护着一个网站,该网站的数据库包含大约 30,000 张与列表相关的图像。这些图像有许多不同的大小和纵横比,所以为了在网站上以统一的方式呈现它们,我编写了一个函数,允许我以特定的纵横比响应地呈现图像。
function image($src,$aspect) {
$html = '<img class="img-responsive" src="furniture/blank-'.$aspect.'.png" style="background:url(\''.$src.'\');background-position:center center;background-size:cover;" >';
return $html;
}
在我的“家具”文件夹中,我有一组所需宽高比的透明 PNG 文件,以强制实际图像成为背景的容器大小。因此,例如有一个 4x3.png 文件,它只是一个 4px 宽 x 3px 高的空图形,我可以用 image('path/to/image.jpg','4x3') 调用它 - 它工作得很好。
但是,当图像中有人的脸时就会出现问题,因为默认的“中心中心”定位有时会切断头部。
我已经完成了人脸检测步骤,数据库中的每条记录都有一个标志,表明是否在图像中发现了人脸,如果是,还有 X、Y 和宽度值。然后问题是试图找出背景位置,因为我正在处理响应式布局,所以不一定知道显示的图像大小。
我假设我需要遵循的逻辑是;
如果图像中有脸 然后使用基于面部 Y 坐标计算的垂直偏移设置背景位置 别的 将背景位置设置为中心中心
在图像尺寸未知的情况下,如何计算出垂直偏移值?
最佳答案
好的,所以想出了这个,但张贴在这里以防其他人遇到困难。
基本逻辑是根据实际图像的宽度计算出 aspect window 的高度(现阶段无需担心响应性)。然后,您找到要放入框架中的图像的理想中心点,并确定该点是高于还是低于图像在宽高比窗口内滑动的限制。
我将其放入我调用的函数中,然后将结果直接放入背景位置 CSS 中。
在下面,变量是:
- $img = 图片路径
- $aspect1 = 例如16(如果 16x9)
- $aspect2 = 例如9(如果 16x9)
- $faceD = 如果图像中检测到人脸则设置为 1
- $faceY = 面部顶部的 Y 像素
$faceW = 面部区域的宽度(和高度)
function calcImagePosition($img,$aspect1,$aspect2,$faceD,$faceY,$faceW) { if($faceD==1) { // Only do this if there's a face in the image list($width, $height) = getimagesize($_SERVER['DOCUMENT_ROOT']."/".$img); // Get the image dimensions $aspectHeight = ($width/$aspect1)*$aspect2; // Get the height of the aspect window based on the actual width of the image $idealCentre = $faceY + ($faceW/2); // The best part of the image to appear in the aspect window is halfway down the face bounds if($idealCentre<($aspectHeight/2)) { // if the ideal centre is higher than half the height of the aspect window, just set it to top $position = "center top"; } elseif(($height-$idealCentre)<($aspectHeight/2)) { // Also, if there's less than half the height of the aspect window at the bottom, set it to bottom $position = "center bottom"; } else { // This will slide the position to best match the face $pixel = $idealCentre-($aspectHeight/2); // Get the absolute pixel value $percent = intval(($pixel/$height)*100); // Convert this to a percentage so it doesn't matter about responsive sizing $position = "center ".$percent."%"; } } else { $position = "center center"; // default for no face detection } return $position; }
我将它与 Karthik Tharavaad 的人脸检测器的 php 端口结合使用,它合理地创建了 $faceY 和 $faceW 所需的数据。
关于php - 使用人脸检测坐标计算背景位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41430048/