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

OpenCV图像叠加问题:粘贴图像后颜色改变且出现透明效果

问题解决:粘贴图像区域后颜色异常与透明问题

核心问题分析

  1. 显示错误:使用plt.imshow(im, cmap='gray')展示RGB图像会强制灰度映射,直接导致颜色失真。
  2. 像素替换逻辑不当:np.where的逐通道判断可能引发像素混合,产生类似透明的效果。
  3. 语法错误:Image.open("black_image.jpg"))多了一个闭合括号,会导致代码运行失败。

修正后的代码

from PIL import Image
import cv2
import numpy as np
import matplotlib.pyplot as plt

# 读取目标图像并转换为RGB(OpenCV默认BGR格式)
img = cv2.imread("target_image.jpg")
im = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# 定义区域坐标(x起始, y起始, 宽度, 高度)
c_shape_l = (0, 103, 33, 167)
c_shape_r = (446, 0, 34, 157)

# 读取源图像并裁剪指定区域(修复语法错误)
left_shape = Image.open("black_image.jpg")
left_sh_im = left_shape.crop((
    c_shape_l[0], c_shape_l[1],
    c_shape_l[0] + c_shape_l[2], c_shape_l[1] + c_shape_l[3]
))
left_shape_np = np.array(left_sh_im)  # 转换为RGB格式的numpy数组

# 创建非黑色区域掩码:任一通道值>100即判定为彩色像素
mask = (left_shape_np > [100, 100, 100]).any(axis=2)

# 定位目标图像的对应区域
target_region = im[
    c_shape_l[1]:c_shape_l[1]+c_shape_l[3],
    c_shape_l[0]:c_shape_l[0]+c_shape_l[2]
]

# 仅替换目标区域中的彩色像素,避免混合
target_region[mask] = left_shape_np[mask]

# 右侧区域执行相同操作
right_shape = Image.open("black_image.jpg")
right_sh_im = right_shape.crop((
    c_shape_r[0], c_shape_r[1],
    c_shape_r[0] + c_shape_r[2], c_shape_r[1] + c_shape_r[3]
))
right_shape_np = np.array(right_sh_im)
mask_right = (right_shape_np > [100, 100, 100]).any(axis=2)
target_region_right = im[
    c_shape_r[1]:c_shape_r[1]+c_shape_r[3],
    c_shape_r[0]:c_shape_r[0]+c_shape_r[2]
]
target_region_right[mask_right] = right_shape_np[mask_right]

# 正确显示RGB图像(无需灰度映射)
plt.imshow(im)
plt.axis('off')
plt.show()

关键修复点

  • 移除灰度映射:plt.imshow(im)直接显示RGB图像,确保颜色还原。
  • 精确掩码替换:通过any(axis=2)精准识别彩色像素,仅替换目标区域对应位置,消除混合效果。
  • 统一颜色空间:目标图像转RGB、源图像以Pillow默认RGB读取,保证色彩空间一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 14:43:31