逐行详细解释: import gradio as gr from PIL import ImageColor import onnxruntime import cv2…
- User
逐行详细解释: import gradio as gr from PIL import ImageColor
import onnxruntime import cv2 import numpy as np
The common resume photo size is 35mmx45mm
RESUME_PHOTO_W = 350 RESUME_PHOTO_H = 450
modified from https://github.com/opencv/opencv_zoo/blob/main/models/face_detection_yunet/yunet.py
class YuNet: def init( self, modelPath, inputSize=[320, 320], confThreshold=0.6, nmsThreshold=0.3, topK=5000, backendId=0, targetId=0, ): self._modelPath = modelPath self._inputSize = tuple(inputSize) # [w, h] self._confThreshold = confThreshold self._nmsThreshold = nmsThreshold self._topK = topK self._backendId = backendId self._targetId = targetId
self._model = cv2.FaceDetectorYN.create( model=self._modelPath, config="", input_size=self._inputSize, score_threshold=self._confThreshold, nms_threshold=self._nmsThreshold, top_k=self._topK, backend_id=self._backendId, target_id=self._targetId, ) @property def name(self): return self.__class__.__name__ def setBackendAndTarget(self, backendId, targetId): self._backendId = backendId self._targetId = targetId self._model = cv2.FaceDetectorYN.create( model=self._modelPath, config="", input_size=self._inputSize, score_threshold=self._confThreshold, nms_threshold=self._nmsThreshold, top_k=self._topK, backend_id=self._backendId, target_id=self._targetId, ) def setInputSize(self, input_size): self._model.setInputSize(tuple(input_size)) def infer(self, image): # Forward faces = self._model.detect(image) return faces[1]class ONNXModel: def init(self, model_path, input_w, input_h): self.model = onnxruntime.InferenceSession(model_path) self.input_w = input_w self.input_h = input_h
def preprocess(self, rgb, mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)): # convert the input data into the float32 input img_data = ( np.array(cv2.resize(rgb, (self.input_w, self.input_h))) .transpose(2, 0, 1) .astype("float32") ) # normalize norm_img_data = np.zeros(img_data.shape).astype("float32") for i in range(img_data.shape[0]): norm_img_data[i, :, :] = img_data[i, :, :] / 255 norm_img_data[i, :, :] = (norm_img_data[i, :, :] - mean[i]) / std[i] # add batch channel norm_img_data = norm_img_data.reshape(1, 3, self.input_h, self.input_w).astype( "float32" ) return norm_img_data def forward(self, image): input_data = self.preprocess(image) output_data = self.model.run(["argmax_0.tmp_0"], {"x": input_data}) return output_datadef make_resume_photo(rgb, background_color): h, w, _ = rgb.shape bgr = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)
- Assistant
这段代码主要用于将普通照片制作成符合规格的证件照。代码利用了OpenCV的人脸检测模型(YuNet),以及一个ONNX模型进行人体分割(区分前景人物和背景)。代码最后部分包括使用Gradio库创建的一个Web界面,能让用户上传图片,选择背景颜色,并生成证件照。
下面我会逐行详细解释代码的含义:
import gradio as gr # 导入Gradio库,用于构建Web界面 from PIL import ImageColor # 导入ImageColor用于处理颜色 import onnxruntime # 导入onnxruntime用于运行ONNX模型 import cv2 # 导入OpenCV库,用于图像处理 import numpy as np # 导入NumPy库,用于矩阵操作 # 定义证件照的宽度和高度(单位:像素) RESUME_PHOTO_W = 350 RESUME_PHOTO_H = 450 # 定义YuNet类,用于人脸检测 class YuNet: def __init__( self, modelPath, inputSize=[320, 320], confThreshold=0.6, nmsThreshold=0.3, topK=5000, backendId=0, targetId=0, ): # 初始化参数 # ... # 加载OpenCV的人脸检测模型 self._model = cv2.FaceDetectorYN.create( model=self._modelPath, # ... ) # 类的其他方法,包括设置后端和目标设备、设置模型的输入大小以及执行推断 # ... # 定义了一个用来处理和运行ONNX模型的类 class ONNXModel: # ... # 前处理函数,用于将图像数据转化成模型所需要的格式 def preprocess(self, rgb, mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)): # ... # 运行模型并获取输出结果 def forward(self, image): # ... # 主要的函数,用于将输入的RGB图像和背景颜色,转换成证件照 def make_resume_photo(rgb, background_color): # ... # 初始化人脸检测器(YuNet)和人体分割器(ONNXModel) # 使用人脸检测器定位人脸,并进行处理 # 使用人体分割器分割人体和背景 # 将背景替换为指定的颜色,缩放图片以符合证件照的规格 # 将处理结果加入到结果列表 return results # 返回结果列表 # 定义了Web界面的标题 title = "AI证件照:任意照片生成证件照||公众号:正经人王同学" # 使用Gradio创建Web界面,指定输入和输出组件、示例图片、标题等 demo = gr.Interface( fn=make_resume_photo, inputs=[ gr.Image(type="numpy", label="input"), gr.ColorPicker(label="设置背景颜色"), ], outputs=gr.Gallery(label="output"), examples=[ # ... ], title=title, allow_flagging="never", article="<p style='text-align: center;'><a href='https://mp.weixin.qq.com/s/SvQT5elBPuPYJ0CJ_LlBYA' target='_blank'>公众号:正经人王同学</a></p>", ) if __name__ == "__main__": demo.launch(server_name="0.0.0.0",server_port=7860) # 启动Gradio应用