Files
colomi 0eb61f3e60 初始化换发型项目:3个微服务代码 + 部署脚本
包含:
- hair_service_sd: 换发型/换发色算法服务 (端口 8801)
- photo_service: LoRA 训练调度服务 (端口 32678)
- stable-diffusion-webui: SD WebUI 推理服务 (端口 57860)
- kohya_ss_home: 训练环境代码
- meidaojia: 监控测试脚本
- setup.sh: 一键部署脚本 (conda环境恢复 + 配置生成 + 完整性检查)
- start_all_services.sh: 启动3个服务
- configure.ini.template: 路径模板化 (BASE_DIR自动推导)
- conda_envs/py310.yml: py310 环境定义

大文件 (weights/, models/, data/, conda_envs/*.tar.gz 等) 通过 .gitignore 排除,
由网盘单独上传。
2026-07-11 18:11:49 +08:00

230 lines
9.6 KiB
Python

import torch
import torch.nn as nn
import math
import sys
import os
from utils import landmark_processor
import cv2
import numpy as np
output_points = 137 * 2
input_size = 192
def op_name(op_name, m):
m.op_name = op_name
return m
class Flatten(nn.Module):
def __init__(self, axis):
super(Flatten, self).__init__()
self.axis = axis
def forward(self, x):
assert self.axis == 1
x = x.reshape(x.shape[0], -1)
return x
def flatten(name, axis):
return op_name(name, Flatten(axis))
def conv_bn_relu(name, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, momentum = 0.1, track_running_stats=True):
return nn.Sequential(
op_name(name, nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, False)),
op_name(name + '/bn', nn.BatchNorm2d(out_channels, momentum = momentum, track_running_stats = track_running_stats)),
op_name(name + '/relu', nn.ReLU(inplace=True)),
)
def linear_bn_relu(name, in_features, out_features, momentum = 0.1, track_running_stats=True):
return nn.Sequential(
op_name(name + '/FC', nn.Linear(in_features, out_features)),
op_name(name + '/bn', nn.BatchNorm1d(out_features, momentum = momentum, track_running_stats = track_running_stats)),
op_name(name + '/relu', nn.ReLU(inplace=True)),
)
# Define a Basic resnet block
class BasicResnetBlock(nn.Module):
def __init__(self, name, in_channels, out_channels, kernel_size=3, stride=2, padding=1, direct_plus=False):
super(BasicResnetBlock, self).__init__()
self.op_name = name
self.conv_block = nn.Sequential(
conv_bn_relu(name=name + '/conv1', in_channels=in_channels, out_channels=out_channels,
kernel_size=kernel_size, stride=stride, padding=padding),
conv_bn_relu(name=name + '/conv2', in_channels=out_channels, out_channels=out_channels,
kernel_size=3, stride=1, padding=1)
)
if direct_plus and (in_channels == out_channels) and (stride == 1):
self.sc_block = None
else:
self.sc_block = conv_bn_relu(name=name + '/sc_conv', in_channels=in_channels, out_channels=out_channels,
kernel_size=1, stride=stride, padding=0)
def forward(self, x):
if self.sc_block is None:
out = x + self.conv_block(x)
else:
out = self.conv_block(x) + self.sc_block(x)
return out
#define SuperBigResNet Frame
class SuperBigResNet(nn.Module):
def __init__(self, name='SuperBigResNet', in_channels=3, out_channels=137 * 2):
super(SuperBigResNet, self).__init__()
self.op_name = name
op_list = []
stride_cnt = 2
op_list += [conv_bn_relu(name + '/first_conv', in_channels, 48, kernel_size=5, stride=2, padding=2)]
ch_num = [48, 64, 96, 128, 192]
for i in range(len(ch_num) - 1):
if ch_num[i] == ch_num[i+1]:
op_list += [BasicResnetBlock(name + '/stage%d'%(i + 1), ch_num[i], ch_num[i+1], kernel_size=3, stride=1, direct_plus=True)]
else:
stride_cnt = stride_cnt * 2
op_list += [BasicResnetBlock(name + '/stage%d'%(i + 1), ch_num[i], ch_num[i+1], kernel_size=3, stride=2)]
item_cnt = int((input_size / stride_cnt) * (input_size / stride_cnt) * ch_num[-1])
op_list += [flatten(name + '/flatten', 1),
linear_bn_relu(name + '/FC1', item_cnt, 512),
op_name(name + '/FC2', nn.Linear(512, out_channels))]
self.conv_block = nn.Sequential(*op_list)
def forward(self, x):
res = self.conv_block(x)
return res.cpu().numpy()
class MomocvFaceAlignmentBigger(object):
def __init__(self, gpu_id=None):
self.gpu_id = gpu_id
self.device = torch.device('cuda:{}'.format(gpu_id) if gpu_id is not None else 'cpu')
self.face_alignment_net = SuperBigResNet('SuperBigResNet', 3, 137 * 2)
self.model_path, _ = os.path.split(os.path.realpath(__file__))
weights = torch.load(os.path.join(self.model_path, 'SuperBigResNet_latest.pth'),
map_location=lambda storage, loc: storage)
self.face_alignment_net.load_state_dict(weights)
self.face_alignment_net.to(self.device)
self.face_alignment_net.eval()
self.trackingFaceRects = []
def detect(self, img, landmarks):
dst_size = 192
landmarks_res = []
with torch.no_grad():
input_numpy = np.zeros((len(landmarks), 3, dst_size, dst_size), dtype=np.float32)
all_mat = []
for ix, landmark in enumerate(landmarks):
M = landmark_processor.get_transform_mat_mmcv_bigger(landmark, dst_size)
all_mat.append(M)
tmp = cv2.warpAffine(img, M, (dst_size, dst_size))
input_numpy[ix, :, :, :] = tmp.transpose((2, 0, 1)).astype(np.float32)
# cv2.imshow('tmp', tmp)
# cv2.waitKey()
in_tensor = torch.from_numpy(input_numpy)
in_tensor = in_tensor.to(self.device)
fullyconnected1 = self.face_alignment_net(in_tensor)
for ix, pts in enumerate(fullyconnected1):
orig_pts = (np.reshape(pts, (2, 137)).transpose((1, 0)) * dst_size)
orig_pts = landmark_processor.transform_points(orig_pts, all_mat[ix], invert=True)
landmarks_res.append(orig_pts)
return landmarks_res
def stable_forward(self, image, detected_faces, reset=False):
if reset is True:
self.trackingFaceRects = []
for face_rect in detected_faces:
if len(self.trackingFaceRects) == 0:
new_tracking_rect = [face_rect, True, [0, 0], 0, None]
self.trackingFaceRects.append(new_tracking_rect)
with torch.no_grad():
landmarks = []
for tracking_face_rect in self.trackingFaceRects:
if tracking_face_rect[1] == True:
d = tracking_face_rect[0]
src_center = np.array([d[2] - (d[2] - d[0]) / 2.0, d[3] - (d[3] - d[1]) / 2.0])
rotate_degree = tracking_face_rect[3]
scale = 192 * 0.6 / min(d[2] - d[0], d[3] - d[1])
dst_center = np.array([0.5, 0.5]) * 192
offset = dst_center - src_center
print('hello')
M = cv2.getRotationMatrix2D((src_center[0], src_center[1]), rotate_degree, scale)
M[:, 2] += offset
else:
# dst_left_anchor = np.array([0.403, 0.52]) * 192
# dst_right_anchor = np.array([1 - 0.403, 0.52]) * 192
# # use last anchors
# src_center = (tracking_face_rect[2][0] + tracking_face_rect[2][1]) / 2
# rotate_radian = math.atan2(tracking_face_rect[2][1][1] - tracking_face_rect[2][0][1], tracking_face_rect[2][1][0] - tracking_face_rect[2][0][0])
# rotate_degree = rotate_radian / math.pi * 180
# print('degree', rotate_degree)
# dst_anchor_len = cv2.norm(dst_left_anchor - dst_right_anchor)
# src_anchor_len = cv2.norm(tracking_face_rect[2][2], tracking_face_rect[2][3])
# scale = 71.0 / src_anchor_len
#
# # bounding_box = cv2.boundingRect(np.array(tracking_face_rect[2]))
# # a = bounding_box[2] * bounding_box[3]
# # print('a', a)
# # scale = float(65*65) / (bounding_box[2] * bounding_box[3])
# # print('scale', scale)
#
# dst_center = (dst_left_anchor + dst_right_anchor) / 2
# offset = dst_center - src_center
rotate_degree = 0
M = landmark_processor.get_transform_mat_mmcv_bigger(tracking_face_rect[4], 192)
inp = cv2.warpAffine(image, M, (192, 192))
orig_inp = inp
inp = inp.transpose((2, 0, 1)).astype(np.float32)
inp = inp[np.newaxis, :, :, :]
t0 = cv2.getTickCount()
in_tensor = torch.from_numpy(inp)
in_tensor = in_tensor.to(self.device)
fullyconnected1 = self.face_alignment_net(in_tensor)
fullyconnected1 = fullyconnected1[0]
orig_pts = (np.reshape(fullyconnected1, (2, 137)).transpose((1, 0)) * 192)
t2 = cv2.getTickCount()
# print('cost', (t2 - t0) / cv2.getTickFrequency() * 1000)
# for ix, pt in enumerate(orig_pts):
# cv2.putText(orig_inp, str(ix), (int(pt[0]), int(pt[1])), cv2.FONT_HERSHEY_SIMPLEX, 0.3, (255, 0, 0))
# cv2.circle(orig_inp, (int(pt[0]), int(pt[1])), 1, (0, 255, 0), 1)
# cv2.imshow('inp_stable', orig_inp)
# cv2.waitKey()
orig_pts = landmark_processor.transform_points(orig_pts, M, invert=True)
# orig_pts = orig_pts.transpose((1, 0))
fullyconnected1 = orig_pts
# update tracking infos
tracking_face_rect[1] = False
tracking_face_rect[2] = [fullyconnected1[68], fullyconnected1[74], fullyconnected1[96], fullyconnected1[113]]
tracking_face_rect[3] = rotate_degree
tracking_face_rect[4] = fullyconnected1
landmarks.append(fullyconnected1)
return landmarks
if __name__=='__main__':
pass