You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python+OpenCV给视频人脸加眼镜后肤色偏蓝的修复方案

问题原因与解决方案

核心问题

输出视频肤色变蓝,根源是OpenCV与PIL的色彩空间不匹配:

  • OpenCV读取视频帧时,默认采用BGR色彩通道顺序
  • PIL处理图像时,使用的是RGB色彩通道顺序
    直接将OpenCV的BGR帧转成PIL图像,会导致红、蓝通道颠倒,最终呈现出偏蓝的肤色。

修复步骤

只需在将OpenCV帧转换为PIL图像前,先把BGR格式转换为RGB格式即可,修改代码中对应片段:

原代码:

ret, frame = cap.read()
if ret == True:
    frame_array = np.array(frame)
    pil_image = Image.fromarray(frame_array)

修改为:

ret, frame = cap.read()
if ret == True:
    # 将OpenCV的BGR帧转换为RGB格式,适配PIL色彩空间
    rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    pil_image = Image.fromarray(rgb_frame)

额外性能优化(可选)

原代码在循环内重复加载Haar分类器,会造成不必要的性能损耗,建议将分类器加载逻辑移到循环外部:

def action():
    # 分类器只加载一次,移出循环
    face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
    eye_cascade = cv2.CascadeClassifier("haarcascade_eye_tree_eyeglasses.xml")
    
    def t():
        cap = cv2.VideoCapture(vidfile)
        ret, frame = cap.read()
        h, w, _ = frame.shape
        clips = []
        while (cap.isOpened()):
            ret, frame = cap.read()
            if ret == True:
                # 后续代码保持不变,移除循环内的分类器加载行
                ...

内容的提问来源于stack exchange,提问作者Karsen Eubanks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 23:42:39