gpt4 book ai didi

python - OpenCV 和 Python : quickly superimpose mask over image without overflow

转载 作者:太空宇宙 更新时间:2023-11-03 21:08:49 25 4
gpt4 key购买 nike

我想在彩色图像上叠加一个二进制掩码,这样在掩码“打开”的地方,像素值的变化量我可以设置。结果应如下所示:

enter image description here

我正在使用 OpenCV 2.4 和 Python 2.7.6。我有一种方法效果很好,但速度很慢,另一种方法速度很快,但存在上溢和下溢问题。这是更快代码的结果,带有上溢/下溢工件:

enter image description here

这是我的代码,显示了快速版本和慢速版本:

def superimpose_mask_on_image(mask, image, color_delta = [20, -20, -20], slow = False):
# superimpose mask on image, the color change being controlled by color_delta
# TODO: currently only works on 3-channel, 8 bit images and 1-channel, 8 bit masks

# fast, but can't handle overflows
if not slow:
image[:,:,0] = image[:,:,0] + color_delta[0] * (mask[:,:,0] / 255)
image[:,:,1] = image[:,:,1] + color_delta[1] * (mask[:,:,0] / 255)
image[:,:,2] = image[:,:,2] + color_delta[2] * (mask[:,:,0] / 255)

# slower, but no issues with overflows
else:
rows, cols = image.shape[:2]
for row in xrange(rows):
for col in xrange(cols):
if mask[row, col, 0] > 0:
image[row, col, 0] = min(255, max(0, image[row, col, 0] + color_delta[0]))
image[row, col, 1] = min(255, max(0, image[row, col, 1] + color_delta[1]))
image[row, col, 2] = min(255, max(0, image[row, col, 2] + color_delta[2]))

return

有没有一种快速的方法(可能使用一些 numpy 的函数)来获得我的慢速代码当前产生的相同结果?

最佳答案

可能有更好的方法将着色蒙版应用到图像,但如果您想按照您建议的方式进行操作,那么这个简单的剪辑将达到您想要的效果:

import numpy as np

image[:, :, 0] = np.clip(image[:, :, 0] + color_delta[0] * (mask[:, :, 0] / 255), 0, 255)
image[:, :, 1] = np.clip(image[:, :, 1] + color_delta[1] * (mask[:, :, 0] / 255), 0, 255)
image[:, :, 2] = np.clip(image[:, :, 2] + color_delta[2] * (mask[:, :, 0] / 255), 0, 255)

结果是:

enter image description here

如果您的目标是将颜色应用于某个区域,另一种方法是简单地修改色调/饱和度。例如:

mask = np.zeros((image.shape[0], image.shape[1]), dtype=np.bool)
mask[100:200, 100:500] = True

image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
image[mask, 0] = 80
image[mask, 1] = 255
image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR)

关于python - OpenCV 和 Python : quickly superimpose mask over image without overflow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30824718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com