pytorch?液態(tài)算法實現瘦臉效果
論文:Interactive Image Warping(1993年Andreas Gustafsson)
算法思路:

假設當前點為(x,y),手動指定變形區(qū)域的中心點為C(cx,cy),變形區(qū)域半徑為r,手動調整變形終點(從中心點到某個位置M)為M(mx,my),變形程度為strength,當前點對應變形后的目標位置為U。變形規(guī)律如下,
- 圓內所有像素均沿著變形向量的方向發(fā)生偏移
- 距離圓心越近,變形程度越大
- 距離圓周越近,變形程度越小,當像素點位于圓周時,該像素不變形
- 圓外像素不發(fā)生偏移

其中,x是圓內任意一點坐標,c是圓心點,rmax為圓心半徑,m為調整變形的終點,u為圓內任意一點x對應的變形后的位置。
對上面公式進行改進,加入變形程度控制變量strength,改進后瘦臉公式如下,

優(yōu)缺點:
優(yōu)點:形變思路簡單直接
缺點:
- 局部變形算法,只能基于一個中心點,向另外一個點的方向啦。如果想多個點一起拉伸,只能每個點分別做一次液化,通過針對多個部位多次液化來實現。
- 單點拉伸的變形,可以實現瘦臉的效果,但是效果自然度有待提升。
代碼實現:
import cv2
import math
import numpy as np
def localTranslationWarpFastWithStrength(srcImg, startX, startY, endX, endY, radius, strength):
ddradius = float(radius * radius)
copyImg = np.zeros(srcImg.shape, np.uint8)
copyImg = srcImg.copy()
maskImg = np.zeros(srcImg.shape[:2], np.uint8)
cv2.circle(maskImg, (startX, startY), math.ceil(radius), (255, 255, 255), -1)
K0 = 100/strength
# 計算公式中的|m-c|^2
ddmc_x = (endX - startX) * (endX - startX)
ddmc_y = (endY - startY) * (endY - startY)
H, W, C = srcImg.shape
mapX = np.vstack([np.arange(W).astype(np.float32).reshape(1, -1)] * H)
mapY = np.hstack([np.arange(H).astype(np.float32).reshape(-1, 1)] * W)
distance_x = (mapX - startX) * (mapX - startX)
distance_y = (mapY - startY) * (mapY - startY)
distance = distance_x + distance_y
K1 = np.sqrt(distance)
ratio_x = (ddradius - distance_x) / (ddradius - distance_x + K0 * ddmc_x)
ratio_y = (ddradius - distance_y) / (ddradius - distance_y + K0 * ddmc_y)
ratio_x = ratio_x * ratio_x
ratio_y = ratio_y * ratio_y
UX = mapX - ratio_x * (endX - startX) * (1 - K1/radius)
UY = mapY - ratio_y * (endY - startY) * (1 - K1/radius)
np.copyto(UX, mapX, where=maskImg == 0)
np.copyto(UY, mapY, where=maskImg == 0)
UX = UX.astype(np.float32)
UY = UY.astype(np.float32)
copyImg = cv2.remap(srcImg, UX, UY, interpolation=cv2.INTER_LINEAR)
return copyImg
image = cv2.imread("./tests/images/klst.jpeg")
processed_image = image.copy()
startX_left, startY_left, endX_left, endY_left = 101, 266, 192, 233
startX_right, startY_right, endX_right, endY_right = 287, 275, 192, 233
radius = 45
strength = 100
# 瘦左邊臉
processed_image = localTranslationWarpFastWithStrength(processed_image, startX_left, startY_left, endX_left, endY_left, radius, strength)
# 瘦右邊臉
processed_image = localTranslationWarpFastWithStrength(processed_image, startX_right, startY_right, endX_right, endY_right, radius, strength)
cv2.imwrite("thin.jpg", processed_image)實驗效果:

到此這篇關于pytorch 液態(tài)算法實現瘦臉效果的文章就介紹到這了,更多相關pytorch 液態(tài)算法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

