79 lines
3.1 KiB
Python
79 lines
3.1 KiB
Python
import cv2
|
|
import numpy as np
|
|
from minio import Minio
|
|
|
|
from app.core.config import MINIO_URL, MINIO_ACCESS, MINIO_SECRET, MINIO_SECURE
|
|
from app.schemas.mannequin_edit import MannequinModel
|
|
from app.service.utils.new_oss_client import oss_get_image, oss_upload_image
|
|
|
|
minio_client = Minio(MINIO_URL, access_key=MINIO_ACCESS, secret_key=MINIO_SECRET, secure=MINIO_SECURE)
|
|
|
|
|
|
class MannequinEditService():
|
|
def __init__(self, request_data):
|
|
self.scale = request_data.scale
|
|
self.top = request_data.top
|
|
self.bottom = request_data.bottom
|
|
self.image = oss_get_image(oss_client=minio_client, bucket=request_data.mannequins.split('/')[0], object_name=request_data.mannequins[request_data.mannequins.find('/') + 1:], data_type="cv2")
|
|
self.mannequin_name = request_data.mannequin_name
|
|
self.bucket_name = request_data.bucket_name
|
|
if self.image.shape[2] == 4:
|
|
self.bgr = self.image[:, :, :3]
|
|
self.alpha = self.image[:, :, 3]
|
|
self.bgr = cv2.bitwise_and(self.bgr, self.bgr, mask=cv2.normalize(self.alpha, None, 0, 1, cv2.NORM_MINMAX))
|
|
self.h, self.w, _ = self.bgr.shape
|
|
else:
|
|
self.bgr = self.image
|
|
self.h, self.w, _ = self.bgr.shape
|
|
self.alpha = None
|
|
|
|
def __call__(self, *args, **kwargs):
|
|
new_mannequin = self.resize_leg(self.top, self.bottom)
|
|
_, encoded_image = cv2.imencode('.png', new_mannequin)
|
|
image_bytes = encoded_image.tobytes()
|
|
req = oss_upload_image(oss_client=minio_client, bucket=self.bucket_name, object_name=f"{self.mannequin_name}.png", image_bytes=image_bytes)
|
|
return req.bucket_name + "/" + req.object_name
|
|
|
|
def resize_leg(self, top, bottom):
|
|
# 上部
|
|
top_part = self.bgr[:top, :]
|
|
top_part_alpha = self.alpha[:top, :]
|
|
|
|
# 需要resize 部分
|
|
part_resize = self.bgr[top:bottom, :]
|
|
part_resize_alpha = self.alpha[top:bottom, :]
|
|
|
|
# 下部
|
|
part_bottom = self.bgr[bottom:, :]
|
|
part_bottom_alpha = self.alpha[bottom:, :]
|
|
|
|
new_height = int((bottom - top) * self.scale)
|
|
|
|
resized_thigh = cv2.resize(part_resize, (self.w, new_height), interpolation=cv2.INTER_LINEAR)
|
|
resized_thigh_alpha = cv2.resize(part_resize_alpha, (self.w, new_height), interpolation=cv2.INTER_LINEAR)
|
|
|
|
# 组合
|
|
new_bgr = np.vstack((top_part, resized_thigh, part_bottom))
|
|
new_bgr_alpha = np.vstack((top_part_alpha, resized_thigh_alpha, part_bottom_alpha))
|
|
|
|
if self.alpha is not None:
|
|
# 拼接 alpha 通道
|
|
# 合并 BGR 通道和 alpha 通道
|
|
new_image = np.dstack((new_bgr, new_bgr_alpha))
|
|
else:
|
|
new_image = new_bgr
|
|
return new_image
|
|
|
|
|
|
if __name__ == '__main__':
|
|
request_data = MannequinModel(
|
|
mannequins="aida-sys-image/models/male/dc36ce58-46c3-4b6f-8787-5ca7d6fc26e6.png",
|
|
scale=0.1,
|
|
bucket_name="test",
|
|
mannequin_name="mannequin_name",
|
|
top=270,
|
|
bottom=432
|
|
)
|
|
service = MannequinEditService(request_data)
|
|
print(service())
|