I'd like to superimpose a binary mask over a color image, such that where the mask is "on", the pixel value changes by an amount that I can set. The result should look like this:
I am using OpenCV 2.4 and Python 2.7.6. I have a way that works well, but is slow, and another way that is fast but has issues with overflow and underflow. Here is the result of the faster code, with overflow/underflow artifacts:
Here is my code, showing both the fast version and the slow version:
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
Is there a fast way (probably using some of numpy's functions) to get the same result my slow code currently produces?
There might be better ways of applying a colorizing mask to an image, but if you want to do it the way you suggest, then this simple clipping will do what you want:
The result is:
Another way would be to simply modify the hue/saturation if your goal is to apply a color to a region. For instance: