OpenCV & Python: quickly superimpose mask over image without overflow -
i'd superimpose binary mask on color image, such mask "on", pixel value changes amount can set. result should this:
i using opencv 2.4 , python 2.7.6. have way works well, slow, , way fast has issues overflow , underflow. here result of faster code, overflow/underflow artifacts:
here code, showing both fast version , slow version:
def superimpose_mask_on_image(mask, image, color_delta = [20, -20, -20], slow = false): # superimpose mask on image, color change being controlled color_delta # todo: works on 3-channel, 8 bit images , 1-channel, 8 bit masks # fast, 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, no issues overflows else: rows, cols = image.shape[:2] row in xrange(rows): 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 fast way (probably using of numpy's functions) same result slow code produces?
there might better ways of applying colorizing mask image, if want way suggest, simple clipping want:
import numpy 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)
the result is:
another way modify hue/saturation if goal apply color region. instance:
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)
Comments
Post a Comment