首页 > 解决方案 > 如何将签名数组添加到 cv2 图像

问题描述

我需要均衡图像中的背景照明。我想创建校正蒙版,将其添加到新图片中,并且照明将被均衡化。这个掩码显然会有负值。我应该如何将它添加到图片中,以便像素不会溢出或其他东西。lei 是值为 <-255,+255> 的掩码,img 是获取的图像 <0,255>。

    lei = np.ones(height,width)
    lei = 150*lei-backgroundImg # bacgroundImg+lei should be uniform 150 gray image
    img = img + lei #???
    cv2.imshow('img',img)

标签: pythonnumpyopencvpython-imaging-librarycv2

解决方案


您可以使用cv2.subtract- 它会自动进行剪辑。

确保两个减去的图像都是 type np.uint8

这是一个cv2.subtract与 NumPy 减去剪辑进行比较的代码示例:

import numpy as np
import cv2

height, width = backgroundImg.shape[0:2]

lei = np.ones((height, width, 3), np.uint8) * 150
# lei = 150*lei-backgroundImg # bacgroundImg+lei should be uniform 150 gray image
# img = img + lei #???
img = cv2.subtract(lei, backgroundImg)
cv2.imshow('img', img)

# Reference computation:
ref_img = (np.clip(lei.astype(np.int16) - backgroundImg.astype(np.int16), 0, 255)).astype(np.uint8)
print(np.array_equal(img, ref_img))  # True - img = ref_img

cv2.waitKey()
cv2.destroyAllWindows()    

注意:
我不确定您用于均衡背景照明的算法的正确性。

您可能应该使用乘法而不是减法。
例子:

img = (np.clip(np.round((150.0 / np.mean(backgroundImg)) * backgroundImg.astype(float)), 0, 255)).astype(np.uint8)
print(np.mean(img))  # The mean is about 150

推荐阅读