【问题标题】:How to add signed array to cv2 image如何将签名数组添加到 cv2 图像
【发布时间】:2021-07-14 11:25:31
【问题描述】:

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

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

【问题讨论】:

  • 保持图片为uint8,制作校正掩码int16。将两者相加,结果也将是int16。现在使用np.clip 将结果钳制到有效范围(0-255),并使用astype 将其转换回uint8

标签: python numpy opencv python-imaging-library cv2


【解决方案1】:

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

确保两个相减图像的类型均为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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-02
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 2021-06-20
    • 2011-09-28
    相关资源
    最近更新 更多